Showing posts with label data types. Show all posts
Showing posts with label data types. Show all posts

Monday, 22 May 2023

Utility class to get primitive type from wrapper type and vice versa

 

Define an utility class to work with the following features.

1.   Get all the primitive types

2.   Get all the wrapper types

3.   Check whether the given class is a primitive or not

4.   Check whether the given class is a wrapper or not

5.   Convert given primitive type to wrapper type

6.   Convert given wrapper type to the primitive type

 

Primitive types

Java language supports 8 primitive types of data.

1.   boolean

2.   char

3.   byte

4.   short

5.   int

6.   long

7.   float

8.   double

 

Wrapper types

Every primitive type has a correspondent wrapper type in java.

 

Primitive Type

Wrapper Type

boolean

Boolean

char

Character

byte

Byte

short

Short

int

Integer

long

Long

float

Float

double

Double

 

Find the below working application.


 

PrimitiveUtil.java

package com.sample.app.util;

import static java.util.Objects.requireNonNull;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class PrimitiveUtil {
	private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE_TYPE_MAP;
	private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER_TYPE_MAP;

	private PrimitiveUtil() throws InstantiationException {
		throw new InstantiationException("Object creation is restricted");
	}

	static {
		Map<Class<?>, Class<?>> primitiveToWrapperMap = new HashMap<>();
		Map<Class<?>, Class<?>> wrapperToPrimitiveMap = new HashMap<>();

		populateMaps(primitiveToWrapperMap, wrapperToPrimitiveMap, boolean.class, Boolean.class);

		populateMaps(primitiveToWrapperMap, wrapperToPrimitiveMap, char.class, Character.class);

		populateMaps(primitiveToWrapperMap, wrapperToPrimitiveMap, byte.class, Byte.class);
		populateMaps(primitiveToWrapperMap, wrapperToPrimitiveMap, short.class, Short.class);
		populateMaps(primitiveToWrapperMap, wrapperToPrimitiveMap, int.class, Integer.class);
		populateMaps(primitiveToWrapperMap, wrapperToPrimitiveMap, long.class, Long.class);

		populateMaps(primitiveToWrapperMap, wrapperToPrimitiveMap, float.class, Float.class);
		populateMaps(primitiveToWrapperMap, wrapperToPrimitiveMap, double.class, Double.class);

		PRIMITIVE_TO_WRAPPER_TYPE_MAP = Collections.unmodifiableMap(primitiveToWrapperMap);
		WRAPPER_TO_PRIMITIVE_TYPE_MAP = Collections.unmodifiableMap(wrapperToPrimitiveMap);
	}

	private static void populateMaps(Map<Class<?>, Class<?>> primitiveToWrapperMap,
			Map<Class<?>, Class<?>> wrapperToPrimitiveMap, Class<?> primitiveClass, Class<?> wrapperClass) {
		primitiveToWrapperMap.put(primitiveClass, wrapperClass);
		wrapperToPrimitiveMap.put(wrapperClass, primitiveClass);
	}

	public static Set<Class<?>> primitiveTypes() {
		return PRIMITIVE_TO_WRAPPER_TYPE_MAP.keySet();
	}

	public static Set<Class<?>> wrapperTypes() {
		return WRAPPER_TO_PRIMITIVE_TYPE_MAP.keySet();
	}

	public static boolean isPrimitiveType(Class<?> type) {
		return type.isPrimitive();
	}

	public static boolean isWrapperType(Class<?> type) {
		return WRAPPER_TO_PRIMITIVE_TYPE_MAP.containsKey(requireNonNull(type));
	}

	@SuppressWarnings("unchecked")
	public static <T> Class<T> toWrapperType(Class<T> type) {
		Class<T> wrapperType = (Class<T>) PRIMITIVE_TO_WRAPPER_TYPE_MAP.get(requireNonNull(type));
		return (wrapperType == null) ? type : wrapperType;
	}

	@SuppressWarnings("unchecked")
	public static <T> Class<T> toPrimitiveType(Class<T> type) {
		Class<T> primitiveType = (Class<T>) WRAPPER_TO_PRIMITIVE_TYPE_MAP.get(requireNonNull(type));
		return (primitiveType == null) ? type : primitiveType;
	}
}

 

PrimitiveUtilDemo.java

package com.sample.app;

import com.sample.app.util.PrimitiveUtil;

public class PrimitiveUtilDemo {

	public static void main(String[] args) {
		// 1. Get all the primitive types
		System.out.println("Primitive types");
		PrimitiveUtil.primitiveTypes().forEach(System.out::println);

		// 2. Get all the wrapper types
		System.out.println("\nWrapper types");
		PrimitiveUtil.wrapperTypes().forEach(System.out::println);

		// 3. Check whether the given class is a primitive or not
		System.out.println("\nIs " + long.class + " primitive ? " + PrimitiveUtil.isPrimitiveType(long.class));
		System.out.println("Is " + Long.class + " primitive ? " + PrimitiveUtil.isPrimitiveType(Long.class));

		// 4. Check whether the given class is a wrapper or not
		System.out.println("\nIs " + long.class + " wrapper ? " + PrimitiveUtil.isWrapperType(long.class));
		System.out.println("Is " + Long.class + " wrapper ? " + PrimitiveUtil.isWrapperType(Long.class));

		// 5. Convert given primitive type to wrapper type
		System.out.println("\ntoWrapperType(long.class) : " + PrimitiveUtil.toWrapperType(long.class));

		// 6. Convert given wrapper type to the primitive type
		System.out.println("\ntoPrimitiveType(Long.class) : " + PrimitiveUtil.toPrimitiveType(Long.class));
	}

}

 

Output

Primitive types
int
short
long
boolean
float
byte
double
char

Wrapper types
class java.lang.Byte
class java.lang.Short
class java.lang.Integer
class java.lang.Long
class java.lang.Double
class java.lang.Character
class java.lang.Float
class java.lang.Boolean

Is long primitive ? true
Is class java.lang.Long primitive ? false

Is long wrapper ? false
Is class java.lang.Long wrapper ? true

toWrapperType(long.class) : class java.lang.Long

toPrimitiveType(Long.class) : long

 

 


You may like

Interview Questions

Implementation of Bag data structure in Java

Scanner throws java.util.NoSuchElementException while reading the input

How to get all the enum values in Java?

Extend the thread to check it’s running status

Implement retry handler for a task in Java

Design an utility class to capture application metrics summary in Java

Monday, 15 August 2022

PostgreSQL: How to get all available datatypes?

‘\dT *’ command print all the available data types available in PostgresSQL.

test=# \dT *
                                                 List of data types
   Schema   |             Name             |                               Description                               
------------+------------------------------+-------------------------------------------------------------------------
 pg_catalog | "any"                        | pseudo-type representing any type
 pg_catalog | "char"                       | single character
 pg_catalog | aclitem                      | access control list
 pg_catalog | anyarray                     | pseudo-type representing a polymorphic array type
 pg_catalog | anycompatible                | pseudo-type representing a polymorphic common type
 pg_catalog | anycompatiblearray           | pseudo-type representing an array of polymorphic common type elements
 pg_catalog | anycompatiblemultirange      | pseudo-type representing a multirange over a polymorphic common type
 pg_catalog | anycompatiblenonarray        | pseudo-type representing a polymorphic common type that is not an array
 pg_catalog | anycompatiblerange           | pseudo-type representing a range over a polymorphic common type
 pg_catalog | anyelement                   | pseudo-type representing a polymorphic base type
 pg_catalog | anyenum                      | pseudo-type representing a polymorphic base type that is an enum
 pg_catalog | anymultirange                | pseudo-type representing a polymorphic base type that is a multirange
 pg_catalog | anynonarray                  | pseudo-type representing a polymorphic base type that is not an array
 pg_catalog | anyrange                     | pseudo-type representing a range over a polymorphic base type
 pg_catalog | bigint                       | ~18 digit integer, 8-byte storage
 pg_catalog | bit                          | fixed-length bit string
 pg_catalog | bit varying                  | variable-length bit string
 pg_catalog | boolean                      | boolean, 'true'/'false'
 pg_catalog | box                          | geometric box '(lower left,upper right)'
 pg_catalog | bytea                        | variable-length string, binary values escaped
 pg_catalog | character                    | char(length), blank-padded string, fixed storage length
 pg_catalog | character varying            | varchar(length), non-blank-padded string, variable storage length
 pg_catalog | cid                          | command identifier type, sequence in transaction id
 pg_catalog | cidr                         | network IP address/netmask, network address
 pg_catalog | circle                       | geometric circle '(center,radius)'
 pg_catalog | cstring                      | C-style string
 pg_catalog | date                         | date
 pg_catalog | datemultirange               | multirange of dates
 pg_catalog | daterange                    | range of dates
 pg_catalog | double precision             | double-precision floating point number, 8-byte storage
 pg_catalog | event_trigger                | pseudo-type for the result of an event trigger function
 pg_catalog | fdw_handler                  | pseudo-type for the result of an FDW handler function
 pg_catalog | gtsvector                    | GiST index internal text representation for text search
 pg_catalog | index_am_handler             | pseudo-type for the result of an index AM handler function
 pg_catalog | inet                         | IP address/netmask, host address, netmask optional
 pg_catalog | int2vector                   | array of int2, used in system tables
 pg_catalog | int4multirange               | multirange of integers
 pg_catalog | int4range                    | range of integers
 pg_catalog | int8multirange               | multirange of bigints
 pg_catalog | int8range                    | range of bigints
 pg_catalog | integer                      | -2 billion to 2 billion integer, 4-byte storage
 pg_catalog | internal                     | pseudo-type representing an internal data structure
 pg_catalog | interval                     | @ <number> <units>, time interval
 pg_catalog | json                         | JSON stored as text
 pg_catalog | jsonb                        | Binary JSON
 pg_catalog | jsonpath                     | JSON path
 pg_catalog | language_handler             | pseudo-type for the result of a language handler function
 pg_catalog | line                         | geometric line
 pg_catalog | lseg                         | geometric line segment '(pt1,pt2)'
 pg_catalog | macaddr                      | XX:XX:XX:XX:XX:XX, MAC address
 pg_catalog | macaddr8                     | XX:XX:XX:XX:XX:XX:XX:XX, MAC address
 pg_catalog | money                        | monetary amounts, $d,ddd.cc
 pg_catalog | name                         | 63-byte type for storing system identifiers
 pg_catalog | numeric                      | numeric(precision, decimal), arbitrary precision number
 pg_catalog | nummultirange                | multirange of numerics
 pg_catalog | numrange                     | range of numerics
 pg_catalog | oid                          | object identifier(oid), maximum 4 billion
 pg_catalog | oidvector                    | array of oids, used in system tables
 pg_catalog | path                         | geometric path '(pt1,...)'
 pg_catalog | pg_brin_bloom_summary        | BRIN bloom summary
 pg_catalog | pg_brin_minmax_multi_summary | BRIN minmax-multi summary
 pg_catalog | pg_ddl_command               | internal type for passing CollectedCommand
 pg_catalog | pg_dependencies              | multivariate dependencies
 pg_catalog | pg_lsn                       | PostgreSQL LSN datatype
 pg_catalog | pg_mcv_list                  | multivariate MCV list
 pg_catalog | pg_ndistinct                 | multivariate ndistinct coefficients
 pg_catalog | pg_node_tree                 | string representing an internal node tree
 pg_catalog | pg_snapshot                  | snapshot
 pg_catalog | point                        | geometric point '(x, y)'
 pg_catalog | polygon                      | geometric polygon '(pt1,...)'
 pg_catalog | real                         | single-precision floating point number, 4-byte storage
 pg_catalog | record                       | pseudo-type representing any composite type
 pg_catalog | refcursor                    | reference to cursor (portal name)
 pg_catalog | regclass                     | registered class
 pg_catalog | regcollation                 | registered collation
 pg_catalog | regconfig                    | registered text search configuration
 pg_catalog | regdictionary                | registered text search dictionary
 pg_catalog | regnamespace                 | registered namespace
 pg_catalog | regoper                      | registered operator
 pg_catalog | regoperator                  | registered operator (with args)
 pg_catalog | regproc                      | registered procedure
 pg_catalog | regprocedure                 | registered procedure (with args)
 pg_catalog | regrole                      | registered role
 pg_catalog | regtype                      | registered type
 pg_catalog | smallint                     | -32 thousand to 32 thousand, 2-byte storage
 pg_catalog | table_am_handler             | 
 pg_catalog | text                         | variable-length string, no limit specified
 pg_catalog | tid                          | (block, offset), physical location of tuple
 pg_catalog | time with time zone          | time of day with time zone
 pg_catalog | time without time zone       | time of day
 pg_catalog | timestamp with time zone     | date and time with time zone
 pg_catalog | timestamp without time zone  | date and time
 pg_catalog | trigger                      | pseudo-type for the result of a trigger function
 pg_catalog | tsm_handler                  | pseudo-type for the result of a tablesample method function
 pg_catalog | tsmultirange                 | multirange of timestamps without time zone
 pg_catalog | tsquery                      | query representation for text search
 pg_catalog | tsrange                      | range of timestamps without time zone
 pg_catalog | tstzmultirange               | multirange of timestamps with time zone
 pg_catalog | tstzrange                    | range of timestamps with time zone
 pg_catalog | tsvector                     | text representation for text search
 pg_catalog | txid_snapshot                | txid snapshot
 pg_catalog | unknown                      | pseudo-type representing an undetermined type
 pg_catalog | uuid                         | UUID datatype
 pg_catalog | void                         | pseudo-type for the result of a function with no real result
 pg_catalog | xid                          | transaction id
 pg_catalog | xid8                         | full transaction id
 pg_catalog | xml                          | XML content
(107 rows)

 

 

 

Previous                                                 Next                                                 Home

Thursday, 11 March 2021

Php: data types

In real-world application, we need to work with numbers, Booleans, strings and complex data. Php support variety of datatypes to represent different values.

 

Unlike other language (Ex: java, C), you no need to specify the type of data that this variable is going to hold, PHP handles this for us, this makes php a weakly typed language.

 

Example 1

$age = 23;

Variable ‘age’ holds numeric data.

 

Example 2

$name = "Krishna";

Variable ‘name’ holds string data.

 

Example 3

$male = true;

Variable ‘male’ holds Boolean data.

 

data_types_demo.php

#!/usr/bin/php

<?php
$age = 23;
$name = "Krishna";
$male = true;

echo "age is set to $age\n";
echo "name is set to $name\n";
echo "male is set to $male\n";

?> 

Output

$./data_types_demo.php 

age is set to 23
name is set to Krishna
male is set to 1

 

 

Previous                                                    Next                                                    Home

Tuesday, 18 February 2020

Cassandra: Numeric Data Types

Below table summarises the numeric data types supported by Cassandra.

Data Type
Description
tinyint
8-bit signed int
smallint
16-bit signed int
int
32-bit signed int
bigint
64-bit signed long
varint
Arbitrary-precision integer
float
32-bit IEEE-754 floating point
double
64-bit IEEE-754 floating point
decimal
Variable-precision decimal

Example
CREATE TABLE IF NOT EXISTS cassandratutorial.employee (
  id INT PRIMARY KEY, 
  first_name VARCHAR,
  description BLOB,
  male BOOLEAN,
  salary DOUBLE,
  ip_address inet,
  date_of_birth date,
  joining_time timestamp,
  unique_id uuid
);

INSERT INTO cassandratutorial.employee (id, first_name, description, male, salary, ip_address, date_of_birth, joining_time, unique_id) VALUES (1, 'Krishna', textAsBlob('I am Krishna, I am intrested in blogging, trekking'), true, 12345.67, '192.168.2.3', '1985-05-24', 1555494268, uuid());


cqlsh> CREATE KEYSPACE cassandratutorial WITH REPLICATION = 
   ... { 
   ...   'class' : 'SimpleStrategy', 
   ...   'replication_factor' : 1 
   ... };
cqlsh> 
cqlsh> CREATE TABLE IF NOT EXISTS cassandratutorial.employee (
   ...   id INT PRIMARY KEY, 
   ...   first_name VARCHAR,
   ...   description BLOB,
   ...   male BOOLEAN,
   ...   salary DOUBLE,
   ...   ip_address inet,
   ...   date_of_birth date,
   ...   joining_time timestamp,
   ...   unique_id uuid
   ... );
cqlsh> 
cqlsh> INSERT INTO cassandratutorial.employee (id, first_name, description, male, salary, ip_address, date_of_birth, joining_time, unique_id) VALUES (1, 'Krishna', textAsBlob('I am Krishna, I am intrested in blogging, trekking'), true, 12345.67, '192.168.2.3', '1985-05-24', 1555494268, uuid());
cqlsh> 
cqlsh> SELECT * FROM cassandratutorial.employee;

 id | date_of_birth | description                                                                                            | first_name | ip_address  | joining_time                    | male | salary   | unique_id
----+---------------+--------------------------------------------------------------------------------------------------------+------------+-------------+---------------------------------+------+----------+--------------------------------------
  1 |    1985-05-24 | 0x4920616d204b726973686e612c204920616d20696e7472657374656420696e20626c6f6767696e672c207472656b6b696e67 |    Krishna | 192.168.2.3 | 1970-01-19 00:04:54.268000+0000 | True | 12345.67 | bba0d1c0-b4c1-4e14-b36e-8ac2d2519bd3

(1 rows)
cqlsh>



Previous                                                    Next                                                    Home

Basic Data Types in Cassandra

Cassandra support data types to represent numbers, strings, uuid, time etc.,

Data types are categorized like below.
a.   Numeric Types
b.   String types
c.    Time related data types
d.   Uuid data type
e.   Boolean data type
f.     Date data type
g.   Blob data type
h.   Counter data type
i.     Inet data type
j.     Collection data types
k.    Tuple types

Syntax
<type> ::= <native-type>
         | <collection-type>
         | <tuple-type>
         | <string>       // Used for custom types. The fully-qualified name of a JAVA class

<native-type> ::= ascii
                | bigint
                | blob
                | boolean
                | counter
                | date
                | decimal
                | double
                | float
                | inet
                | int
                | smallint
                | text
                | time
                | timestamp
                | timeuuid
                | tinyint
                | uuid
                | varchar
                | varint

<collection-type> ::= list '<' <native-type> '>'
                    | set  '<' <native-type> '>'
                    | map  '<' <native-type> ',' <native-type> '>'
<tuple-type> ::= tuple '<' <type> (',' <type>)* '>'


Previous                                                    Next                                                    Home

Thursday, 25 July 2019

Processing: Data Types


Processing supports below primitive data types.
a.   boolean
b.   char
c.    byte
d.   int
e.   long
f.     float
g.   double

How to define variable

    Syntax:
        dataType variableName = value;

    Example:
       int intVariable = 10;

        Here
            dataType is int
            variableName is intVariable
            value is 10

HelloWorld.pde
boolean status = true;

char charVar = 'a';

byte b = 100;
int i = 123;
long l = 12345;

float f = 123.45;
double d = 123.45678;

println("status = ", status);

println("charVar = ", charVar);

println("b = ", b);
println("i = ", i);
println("l = ", l);

println("f = ", f);
println("d = ", d);


When you ran the application, you can able to see below messages in console window.

status =  true
charVar =  a
b =  100
i =  123
l =  12345
f =  123.45
d =  123.45677947998047




Previous                                                    Next                                                    Home