<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>String &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/string/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Thu, 26 May 2022 13:53:35 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>How to figure out if a character in a string is a number</title>
		<link>https://codepills.com/how-to-figure-out-if-a-character-in-a-string-is-a-number/</link>
					<comments>https://codepills.com/how-to-figure-out-if-a-character-in-a-string-is-a-number/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Tue, 03 May 2022 13:49:33 +0000</pubDate>
				<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[char]]></category>
		<category><![CDATA[Character]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[regular expression]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1301</guid>

					<description><![CDATA[This article is about multiple ways to pull a character from a string and check if it is a number. <a href="https://codepills.com/how-to-figure-out-if-a-character-in-a-string-is-a-number/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will show how to figure out if a character in a string is a number. You might be wondering how to do it. There are multiple ways to determine if an individual or series of characters in the string classify as a number. So let&#8217;s look at various approaches for determining if the character is a number.</p>
<p><span id="more-1301"></span></p>
<h2>Using <em>Character</em> class</h2>
<p>First option is to select a character from string with help of <em>charAt()</em> method and the character position; and use <em>Character</em> class static method <em>isDigit()</em> to return <em>boolean</em> value.</p>
<pre><code class="language-java">String movie = "101 dalmatians";
System.out.println(movie);
boolean result = Character.isDigit(movie.charAt(0));
System.out.println("Is first letter number? Answer: " + result)</code></pre>
<p>The output will be:</p>
<pre><code class="language-bash">101 dalmatians
Is first letter number? true</code></pre>
<p>If we want to check if several characters are numbers, we can place the <em>isDigit()</em> method call inside the loop.</p>
<pre><code class="language-java">String movie = "101 dalmatians";
for (int i = 0; i <= movie.length() - 1; i++) {
    System.out.println(movie.charAt(i) + " -> " + Character.isDigit(movie.charAt(i)));
}</code></pre>
<p>The output of the above code will be:</p>
<pre><code class="language-bash">1 -> true
0 -> true
1 -> true
  -> false
d -> false
a -> false
l -> false
m -> false
a -> false
t -> false
i -> false
a -> false
n -> false
s -> false</code></pre>
<h2>Using Unicode check</h2>
<p>Using <em>Character</em> class static method <em>isDigit()</em> can be used on any Unicode character, not just 0-9 number range. You can use create number check at any <b>Unicode</b> character.</p>
<p>Here is an example of checking a number through a check of Unicode characters:</p>
<pre><code class="language-java">String movie = "101 dalmatians";
System.out.println(movie);
boolean char c = word.charAt(0);
boolean isDigit = (c >= '0' && c <= '9');
System.out.println(isDigit)</code></pre>
<pre><code class="language-bash">101 dalmatians
true</code></pre>
<h2>Using Regex</h2>
<p>Alternative way to using <em>Character</em> class static method <em>isDigit()</em> is to use solution based on <i>regex</i> output. However, this will require string to be instance of <em>String</em> class as we can conduct regex pattern search only on <em>String</em>.</p>
<p>Let us show you first regex pattern for searching digit in substring of length 1 on the instance <em>String</em> class named <em>word</em>:</p>
<pre><code class="language-java">word.substring(0, 1).matches("\\d")</code></pre>
<p>The alternative and equivalent version uses the regex search pattern with the search of digit range.</p>
<pre><code class="language-java">word.substring(0, 1).matches("[0-9]")</code></pre>
<p>The regex solution should be discouraged as it is an over-engineered solution. While there might be a minor performance hit, we can argue it would not affect simple coding solutions. But be aware that regex brings complexity. A solution implementing regular expression should be used with caution and with a fair amount of tests.</p>
<p><b>Note:</b> Regular expressions are very strong, but expensive tool. It is valid to use regular expressions for character check if, e.g. the first character is a digit. But performance-wise, it is also like shooting birds with cannon.</p>
<h2>Using casting</h2>
<p>The last way to check if the character in a string is a number is to use Java casting feature. We will cast string values into one of the numerical object classes. However, this is the worst way how to do it. If you find a code using casting, you should refactor it immediately.</p>
<pre><code class="language-java">public boolean isNumber(String word) {
    boolean isNumber = true;
    try {
        Integer.valueOf(word.substring(0,1));
    } catch (Exception e) {
        isNumber = false;
    }
    return isNumber;
}</code></pre>
<p>There is a lot that can go wrong with the method above. If the entering argument word is an empty string, casting will throw <em>NumberFormatException</em> and catch it. If the first character is not a digit, e.g. letter or special symbol, casting will also throw <em>NumberFormatException</em> and catch it. But if the first character is a digit, it will return true.</p>
<p>You can place any numerical object class to the code such as <em>Integer</em>, <em>Double</em>, <em>Float</em> or <em>Long</em>. But please do not! Using casting with <em>valueOf()</em> method is wrong for two reason:</p>
<ul>
<li>In general, we want to avoid throwing <em>Exceptions</em>, checked or unchecked, as they slow the program and have tremendous performance hit.</li>
<li>Second reason, we can see above at least 3 different ways which provide shorter, more effective and readable way for solving the same problem.</li>
</ul>
<h2>Conclusion</h2>
<p>In the article, we have demonstrated four different ways to find out if the single character or characters from a string is a number or not. The solutions ranged from best to worst, from easiest to most cumbersome. Use as much as possible the first option which use <em>Character</em> class static method <em>isDigit()</em> for determining if the character is a string. Using <em>isDigit()</em> method is, without instantiation of any variables, the most effective and readable solution.</p>
<p>I hope you learned something new and had fun. Thanks for the reading. And if you have any tricks or know a better way <u>how to find out if the character is a string</u>, let us know in the comments below. We would like to hear your ideas.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-figure-out-if-a-character-in-a-string-is-a-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Developer Notes 001</title>
		<link>https://codepills.com/developer-notes-001/</link>
					<comments>https://codepills.com/developer-notes-001/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sun, 01 May 2022 13:34:28 +0000</pubDate>
				<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[curl]]></category>
		<category><![CDATA[Enum]]></category>
		<category><![CDATA[interpunct]]></category>
		<category><![CDATA[Jackson]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[Lombok]]></category>
		<category><![CDATA[NUMBER]]></category>
		<category><![CDATA[Oracle DB]]></category>
		<category><![CDATA[Postman]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[Switch]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1298</guid>

					<description><![CDATA[The list of a few developer notes collected during the software development which were not enough for a self-standing article. <a href="https://codepills.com/developer-notes-001/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article selects a few developer notes collected during the software development, which were unfortunately not enough for a self-standing article.</p>
<p><span id="more-1298"></span></p>
<p>Developer notes will be an irregular series of articles where I will briefly go through some of my notes to make notes for posterity. The notes themself can be pretty long, yet their length is not enough for writing a meaningful article.</p>
<p>Let&#8217;s take a look at a list of content:</p>
<ul>
<li><a href="#oracle_error" title="Oracle Error: Value Larger Than Specified Precision Allowed For This Column">Oracle Error: Value Larger Than Specified Precision Allowed For This Column</a></li>
<li><a href="#switch_on_string_with_enum_name_in_java_8" title="Switch on String in Java">Switch on String with Enum Name in Java 8</a></li>
<li><a href="#lomboks_serialization_error_for_jackson" title="Lombok's serialization error for Jackson">Lombok&#8217;s serialization error for Jackson</a></li>
<li><a href="#interpunct" title="Interpunct">Interpunct</a></li>
<li><a href="#how_to_do_curl_in_postman" title="How To Do CURL in Postman">How To Do <em>curl</em> in Postman</a></li>
</ul>
<h2 id="oracle_error">Oracle Error: Value Larger Than Specified Precision Allowed For This Column</h2>
<p>I was getting errors on inserting data into the Oracle database &#8220;ORA-01438: value larger than specified precision allowed for this column.&#8221;</p>
<p>The reason why I was getting an error was a too big number. When I looked over UI to database column definition, I saw something like this NUMBER(15,2).</p>
<p>Official Oracle documentation, as for <a href="https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Data-Types.html#GUID-75209AF6-476D-4C44-A5DC-5FA70D701B78" title="Number datatype" target="_blank" rel="nofollow noopener">Oracle database v21</a>, depicts <code>NUMBER</code> datatype defined as <code>NUMBER (precision,scale)</code>.</p>
<p><code>NUMBER</code> datatype notation can be rather rewritten to <i>NUMBER (size,precision)</i>) where the first number depicts the total size of the digits in a number, and the second means the decimal point scale.</p>
<p>In other words, for example, for <code>NUMBER(2,2)</code>, we can place the column number consisting of 2 digits, both of which will be decimals. i.e. 0.15, 0.45 etc. But if we would like to have a bigger number in the column, we need to upgrade the size of the column reserved for the whole number &#8211; <code>NUMBER(5,2)</code> will get us five digits, of which 2 are decimals. i.e 125.40, 18.00.</p>
<h2 id="switch_on_string_with_enum_name_in_java_8">Switch on String with Enum Name in Java 8</h2>
<p>Here is an example of how to use <em>Enum</em> values as strings in a <code>switch</code> case. You can only use the strings which are known at compile time. The compiler cannot determine the result of expression. However, in Java <em>Enum</em> case <code>VALUE1, VALUE2</code> are static.</p>
<pre><code class="language-java">String name = ...
switch(CustomEnum.valueOf(name)) {
   case VALUE1:
        ...
        break;
   case VALUE2:
        ...
        break;
    ...
}</code></pre>
<h2 id="lomboks_serialization_error_for_jackson">Lombok&#8217;s serialization error for Jackson</h2>
<p>When I created a new aggregated DTO class on my REST output, I got the following error:</p>
<pre><code class="language-bash">Type definition error: [simple type, class CUSTOM_DTO_CLASS_NAME]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class CUSTOM_DTO_CLASS_NAME and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: CUSTOM_DTO_CLASS_NAME[\"aggregation-class-property\"]->java.util.ArrayList[0])</code></pre>
<p>I am sure this error will be thrown quiet often as the solution on it is very simple. All I was missing on my <i>Custom DTO</i> class was <strong>Lombok&#8217;s</strong> <code>@Getters</code> annotation for serialization. So fix consisted on adding missing <code>@Getters</code> annotation on the top of my custom class for Lombok generating getter methods at compile time.</p>
<h2 id="interpunct">Interpunct</h2>
<p>I was editing my resume this month and wanted to create a nice date range in positions I held in the past. I got this from my LinkedIn profile, where LinkedIn use dates in the form as <em>Jan 2020 – Feb 2020 · 2 mos</em>. But I could not figure out where to take the dot sign as it was an image. However, the character for such sign as little black dot <strong>·</strong> really exists and its name is <strong>Interpunct</strong>,  or <strong>middle dot</strong>. So every time you would like to create a nice division of text with the help of <strong>·</strong>, think about the <strong>Interpunct</strong>.</p>
<h2 id="how_to_do_curl_in_postman">How To Do <em>curl</em> in Postman</h2>
<p>Is there a way hot to make a <em>curl</em> command in Postman? What if we would like to import the <em>curl</em> command easily into Postman and make a Postman GUI request from it.<br />
Is it even possible to easily translate all the <em>curl</em> command parameters into the Postman request?</p>
<p>Surely it is. Postman request are eventually nothing else than more fancy <em>curl</em> requests and Postman supports the <em>curl</em> import feature. Importing <em>curl</em> is very simple. Here is simple list of steps which will lead you to success:</p>
<ol>
<li>Open Postman.</li>
<li>Go to navigation menu, click File and Import option</li>
<li>In <i>Import</i> window select the raw text tab.</li>
<li>Paste the raw text e.g. <code>curl --location --request GET "https://www.google.com/"</code>, then click continue.</li>
<li>Check the name, format and import as.</li>
<li>If everything is correct, click <i>Import</i> button.</li>
</ol>
<p>Following the steps will automatically import the <em>curl</em> command into the Postman on the new tab.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/developer-notes-001/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How To Turn Number To String With Padded Space or Zeroes</title>
		<link>https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/</link>
					<comments>https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 01 Apr 2022 14:59:52 +0000</pubDate>
				<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[Formatter]]></category>
		<category><![CDATA[good practice]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1293</guid>

					<description><![CDATA[Article about a simple solution to turning numbers into specific length <em>String</em> with padded space. <a href="https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will show us how to turn numbers into the <em>String</em> with padded space or numbers.</p>
<p><span id="more-1293"></span></p>
<h2>Introduction</h2>
<p>I have been recently doing code review on other developer pull-request when I found the piece of code below:</p>
<pre><code class="language-java">private static final String DOCUMENT_VERSION = "document_version-";

public String getDocumentVersion(int version) {
    String documentVersion = "";
    if (version > 999) {
        throw new IllegalStateException("Version number " + version + " is too large.");
    } else if (version > 99) {
        documentVersion += version;
    } else if (version > 9) {
        documentVersion += "0" + version;
    } else {
        documentVersion += "00" + version;
    }

    return "DOCUMENT_VERSION_" + documentVersion;
}</code></pre>
<p>As you can immediately see, the code is bad and can be surely rewritten to something more simple. Creating a string from a number can not be so declarative, right? There needs to be a simpler way how to do it. And surely it can. Like many other general-purpose programming languages, Java has multiple libraries and functions for processing text. <em>String</em> class itself has a static method <em>format()</em> which can be fully utilized on the text changes like this.</p>
<h2>Java String format()</h2>
<p>The Java <em>String</em> class <em>format()</em> method returns the formatted string. Let&#8217;s look little bit on parameters of <em>format()</em> method.</p>
<h3>String.format() signature</h3>
<p>There are two type of <em>String format()</em> method:</p>
<pre><code class="language-java">public static String format(String format, Object... args)</code></pre>
<p>and</p>
<pre><code class="language-java">public static String format(Locale locale, String format, Object... args)  </code></pre>
<p>Therefore, method parameters are described as:</p>
<ul>
<li><b>locale</b> is specifies the locale to be applied on the format() method.</li>
<li><b>format</b> is format of the string.</li>
<li><b>args</b> represent arguments for the format string. It may be zero or more.</li>
</ul>
<p><em>format()</em> method returns new <em>String</em>. However, it is also good to be prepared for possibility of two unchecked exception:</p>
<ul>
<li><b>NullPointerException</b> is thrown if <b>format</b> is null.</li>
<li><b>IllegalFormatException</b> is thrown if <b>format</b> is illegal or incompatible.</li>
</ul>
<h3>String.format() internal implementation</h3>
<p>In reality, <em>String.format()</em> method allows usage of multiple <em>Object</em> arguments because internal implementation use nothing else than new instance of <em><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html" title="Java 8 Docs - Formatter Class" target="_blank" rel="nofollow noopener">Formatter</a></em> class.</p>
<pre><code class="language-java">public static String format(String format, Object... args) {
    return new Formatter().format(format, args).toString();
}</code></pre>
<p>Usage of quiet <em>Formatter</em> class explains why we can take multiple arguments depending on the number of elements we want to format inside the string. <em>Formatter</em> class can use several different option of &#8220;%&#8221; character combination in order to define string formatting. In the table below are all options explained:</p>
<table>
<thead>
<tr>
<th>Formatter Argument</th>
<th>Data Type</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>%a %A</td>
<td>floating point (except BigDecimal)</td>
<td>Returns Hex output of floating point number.</td>
</tr>
<tr>
<td>%b</td>
<td>Any type</td>
<td>&#8220;true&#8221; if non-null, &#8220;false&#8221; if null</td>
</tr>
<tr>
<td>%c</td>
<td>character</td>
<td>Unicode character</td>
</tr>
<tr>
<td>%d</td>
<td>integer (incl. byte, short, int, long, bigint)</td>
<td>Decimal Integer</td>
</tr>
<tr>
<td>%e</td>
<td>floating point</td>
<td>decimal number in scientific notation</td>
</tr>
<tr>
<td>%f</td>
<td>floating point</td>
<td>decimal number</td>
</tr>
<tr>
<td>%g</td>
<td>floating point</td>
<td>decimal number, possibly in scientific notation depending on the precision and value.</td>
</tr>
<tr>
<td>%h</td>
<td>any type</td>
<td>Hex String of value from hashCode() method.</td>
</tr>
<tr>
<td>%n</td>
<td>none</td>
<td>Platform-specific line separator.</td>
</tr>
<tr>
<td>%o</td>
<td>integer (incl. byte, short, int, long, bigint)</td>
<td>Octal number</td>
</tr>
<tr>
<td>%s</td>
<td>any type</td>
<td>String value</td>
</tr>
<tr>
<td>%t</td>
<td>Date/Time (incl. long, Calendar, Date and TemporalAccessor)</td>
<td>%t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.</td>
</tr>
<tr>
<td>%x</td>
<td>integer (incl. byte, short, int, long, bigint)</td>
<td>Hex string.</td>
</tr>
</tbody>
</table>
<h2><em>format()</em> examples</h2>
<p>Let us show you few tricks with <em>format()</em></p>
<pre><code class="language-bash">System.out.println(String.format("%d", 100)); // Integer
System.out.println(String.format("%s", "Anna Smith")); // String
System.out.println(String.format("%f", 42.42)); // Float
System.out.println(String.format("%x", 100)); // Hexadecimal
System.out.println(String.format("%c", 'a')); // Char
System.out.println("-----");
System.out.println(String.format("number with text: %d", 100)); // number with other text
System.out.println(String.format("%f", 42.12345)); // prints floating number
System.out.println(String.format("%10.10f", 42.12345)); // prints 10 digits for fractions padded with 0
System.out.println("-----");
System.out.println(String.format("|<-%10d->|", 222)); // Align right, padding with empty space
System.out.println(String.format("|<-%-10d->|", 555)); // Align left, padding with empty space
System.out.println(String.format("|<-% d->|", 777)); // Single space between % and conversion type is allowed
System.out.println(String.format("|<-%010d->|", 999)); // Filling space with zeros</code></pre>
<pre><code class="language-java">100
Anna Smith
42.420000
64
a
-----
number with text: 100
42.123450
42.1234500000
-----
|<-       222->|
|<-555       ->|
|<- 777->|
|<-0000000999->|</code></pre>
<h2>Using <em>format()</em> to turn number into formatted string</h2>
<p>To take for first exemplary code from code review, all what we needed to do in <code>getDocumentVersion()</code> method was to place custom format of string into the <em>String</em> class <em>format</em> method.</p>
<pre><code class="language-java">private static final String DOCUMENT_VERSION = "document_version-";

public String getDocumentVersion(int version) {
    return String.format(DOCUMENT_VERSION + "%03d", revisionNumber);
}</code></pre>
<p>If we place number 1 into the method <code>getDocumentVersion()</code> we will get the same result as boilerplate code from code review:</p>
<p><b>Output</b></p>
<pre><code class="language-bash">document_version-001</code></pre>
<p>We can still quickly write some custom code to test our beliefs. But be thorough and do not forget edge cases as zero and negative numbers.</p>
<pre><code class="language-java">System.out.println(String.format("%03d", 999));
System.out.println(String.format("%03d", 99));
System.out.println(String.format("%03d", 9));
System.out.println(String.format("%03d", 0));
System.out.println(String.format("%03d", -9));</code></pre>
<pre><code class="language-java">999
099
009
000
-09</code></pre>
<p>As you can notice <em>format()</em> takes negative number into account its length with minus sign.</p>
<p><b>Note</b> : If you have any crazy idea how to use <em>format()</em> method, let us know in comments below.</p>
<h2>Conclusion</h2>
<p>This article showed us how to turn a number into a string with a specific length where additional space is padded.</p>
<p>Did you find the <em>String.format()</em> method useful? Do you have your trick, or do you know another way <u>how to turn a number into a string of specific length</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
