<?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>Language basics &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/category/language-basics/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Sat, 08 Jul 2023 14:16:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>How to compile and run Java files on Windows</title>
		<link>https://codepills.com/how-to-compile-and-run-java-files-on-windows/</link>
					<comments>https://codepills.com/how-to-compile-and-run-java-files-on-windows/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 01 Jul 2023 17:04:17 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[javac]]></category>
		<guid isPermaLink="false">http://www.budystudio.com/design/?p=197</guid>

					<description><![CDATA[There are several scenarios when you need to compile and run your Java code from the terminal or command prompt on Windows. Here is a tutorial on how to do it. <a href="https://codepills.com/how-to-compile-and-run-java-files-on-windows/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>From time to time, you get into a situation you need to compile and run your Java code, and instead of using any build tool or IDE, you need to do it manually. If you are engaged in software development or writing automated script writing, compiling and executing code from the Windows console should be straightforward and effortless.</p>
<p><span id="more-197"></span></p>
<p>We will use the following simple code to print a code into the terminal or command prompt for demonstration purposes.</p>
<pre><code class="language-java">public class MyJavaApp {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }

}</code></pre>
<h2>Compile and run Java code in a few steps</h2>
<p>You must follow only a few basic steps to compile and run Java code.</p>
<ol>
<li>As a precondition, ensuring the installation of Java Development Kit (JDK) on your system and the accessibility of the <code>javac</code> and <code>java</code> commands from the terminal or command prompt is important.</li>
<li>First, you <strong>have to have a Java source code in Java files</strong>. Open a text editor and write your Java code. Save the file with a <code>.java</code> file extension.</li>
<li>Then you are ready to compile the Java source file. Open a terminal or command prompt and navigate to the directory where your Java source file is placed. Utilize the <code>javac</code> command for compiling the Java source file into bytecode. For example:
<pre><code class="language-bash">javac MyJavaApp.java</code></pre>
<p>        You will generate a bytecode file named <code>MyJavaApp.java</code> if there are no compilation errors.
    </li>
<li>When you have successfully compiled the Java source file into a bytecode file, you can execute the bytecode using the <code>java</code> command. However, select the class which contains valid <code>public static void main(String args[])</code> Java method in order <strong>for JVM to have an access point to your code</strong>.
<p>        Here is an example of running MyJavaApp:</p>
<pre><code class="language-bash">java MyJavaApp</code></pre>
<p>        And here is the output:</p>
<p>        <img decoding="async" src="https://codepills.com/wp-content/uploads/2012/02/javac_and_java_commands.png" alt="javac and java commands" width="283" height="102" class="alignnone size-full wp-image-1347 aligncenter" /></p>
<p>        <code>java MyJavaApp</code> will run your Java program, and if everything is correct, you should see the output in the console.
    </li>
</ol>
<h2>Compiling and running nested classes</h2>
<p>So far, we have seen compile and run only a single class. However, running a multi-class project is no different from compiling and running a single class. Here is an example of a multi-class project we will use next.</p>
<pre><code class="language-java">public class MyJavaApp {

    public static void main(String[] args) {
        InsertedClass.printToWorld();
    }

}

public class InsertedClass {

    public static void printToWorld() {
        System.out.println("Hello World from other class!");
    }

}</code></pre>
<p>For sure, the same as in a single class, you need to pick a class for compiling the class which contains the <code>public static void main(String args[])</code>. That is the only way the compiler can reach and compile all classes in your project.</p>
<p><img decoding="async" src="https://codepills.com/wp-content/uploads/2012/02/javac_and_java_commands-compiled_files.png" alt="javac and java commands - compiled files" width="155" height="93" class="alignnone size-full wp-image-1349 aligncenter" /></p>
<p>And again, same as in the single class, you need to run the multi-class project with the <code>java</code> command on the file, which contains <code>public static void main(String args[])</code> method.</p>
<p><img decoding="async" src="https://codepills.com/wp-content/uploads/2012/02/javac_and_java_commands-compile_and_run_all_files.png" alt="javac and java commands - compile and run all files" width="276" height="109" class="alignnone size-full wp-image-1348 aligncenter" /></p>
<h2>Conclusion</h2>
<p>This article has shown how to compile and run Java code on the Windows platform.</p>
<p>Did you find compiling and running your Java code easy? Do you have your trick or know another way <u>how to compile and run Java code from the terminal or command prompt</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-compile-and-run-java-files-on-windows/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>7 different ways how to get NumberFormatException in Java</title>
		<link>https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/</link>
					<comments>https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 05 May 2022 11:30:51 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[NumberFormatException]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1304</guid>

					<description><![CDATA[This article will show you the NumberFormatException, how you are getting it and what you should do to handle the exception properly. <a href="https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>If you get NumberFormatException in Java, it is highly probable because of the following reasons. This article will uncover the NumberFormatException, how you are getting it and what you should do to handle the exception properly.</p>
<p><span id="more-1304"></span></p>
<h2>What is NumberFormatException</h2>
<p>The NumberFormatException is an unchecked Java exception which happens when there is incorrect string input converted to a numeric value. When the input is wrong, NumberFormatException is thrown to inform the user that the conversion requires a correct input and the transformation did not happen. For example, the NumberFormatException is thrown when a numerical string is parsed to an integer, but the string contains also space.</p>
<p>As the NumberFormatException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. However, when in doubt of input correctness, it should be handled in code using a try-catch block.</p>
<h2>NumberFormatException Example</h2>
<p>Let&#8217;s take a look at the simple example of NumberFormatException being thrown:</p>
<pre><code class="language-java">public class NumberFormatExceptionExample {
    public static void main(String args[]) {
        int orderNumber = Integer.parseInt("Order 66");
        System.out.println(orderNumber);
    }
}</code></pre>
<p>The above code will throw NumberFormatException. While pure input of string &#8220;66&#8221; is a valid input, a string with non-numerical characters like &#8220;Order 66&#8221; is unsuitable for creating a number.</p>
<pre><code class="language-java">Exception in thread "main" java.lang.NumberFormatException: For input string: "Order 66"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:652)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:6)</code></pre>
<h2>8 Different Ways How To Get NumberFormatException</h2>
<p>There are various causes for throwing NumberFormatException, and the improper conversion of invalid input mainly causes them. Here is a list of different ways how to get NumberFormatException:</p>
<p>1. Input string is empty:</p>
<pre><code class="language-java">Integer.parseInt("");</code></pre>
<p>2. Input string is null:</p>
<pre><code class="language-java">Integer.parseInt(null);</code></pre>
<p>3. Input string with non-numeric data:</p>
<p>This case has several different options why it can happen.</p>
<p>a. Input string contains space character:</p>
<pre><code class="language-java">Integer.parseInt("66 66");</code></pre>
<p>b. Input string contains non-numeric character:</p>
<pre><code class="language-java">Integer.parseInt("Sixty");</code></pre>
<p>c. Numeric input with non-numeric character in input string</p>
<pre><code class="language-java">Integer.parseInt("Catch22");</code></pre>
<p>4. Input string with inappropriate symbols in it:</p>
<pre><code class="language-java">Double.parseDouble("66,12345");</code></pre>
<p>5. Input string with leading or tailing white space</p>
<pre><code class="language-java">Integer randomExample = new Integer("  12345  ");</code></pre>
<p><em>Integer</em>, <em>Long</em>, <em>Short</em>, <em>Byte</em> throw NumberFormatException; <em>Double</em>, <em>Float</em> does not.</p>
<p>6. Mismatch of data type between input string and the target data type</p>
<pre><code class="language-java">Integer.parseInt("12.34");</code></pre>
<p>7. Input string exceeding the range of the target data type</p>
<pre><code class="language-java">Integer.parseInt("2147483648");</code></pre>
<p>The example shown above is a case of NumberFormatException upon placing a numeric input string exceeding the range of the target data type, which is in our case <em>Integer</em> class object. The maximum range for Integer class object is from -2_147_483_648 to 2_147_483_647.</p>
<h2>How to handle NumberFormatException</h2>
<p>The NumberFormatException is an unchecked exception in Java. Therefore it can be handled as any other Java exception by wrapping critical code to try-catch block.</p>
<p>Look at the following example of catching NumberFormatException with a try-catch block:</p>
<pre><code class="language-java">public class NumberFormatExceptionExample {

    public static void main(String args[]) {
        String userInput = "Order 66";
        Optional&lt;Integer&gt; orderNumber = processOrder(userInput);
        if (orderNumber.isPresent()) {
            System.out.println("Execute order " + orderNumber.get());
        } else {
            System.out.println("Unrecognized order number. Please try again.");
        }
    }

    public static Optional&lt;Integer&gt; processOrder(String userInput) {
        try {
            int order = Integer.parseInt(userInput);
            return Optional.of(order);
        } catch (NumberFormatException ex) {
            System.out.println("Order exception: Invalid user input!");
        }
        return Optional.empty();
    }

}</code></pre>
<p>Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message or return an empty Optional object if you are using at least Java 8. Like in the example above, wrapping the code in try-catch blocks allows the program to continue execution after the code throws the exception.</p>
<p><b>Output</b>:</p>
<pre><code class="language-bash">Order exception: Invalid user input!
Unrecognized order number. Please try again.</code></pre>
<h2>Conclusion</h2>
<p>This article led us to explain what NumberFormatException and how to handle it. It also showed over seven different ways how the NumberFormatException can occur and how we can defensively take care of it.</p>
<p>Do you know NumberFormatException? In what case did it throw to you? Do you have your trick, or do you see another way <u>how to handle NumberFormatException</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/7-different-ways-how-to-get-numberformatexception-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Flattening Stream Collections in Java</title>
		<link>https://codepills.com/flattening-stream-collections-in-java/</link>
					<comments>https://codepills.com/flattening-stream-collections-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Tue, 01 Mar 2022 15:24:06 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1289</guid>

					<description><![CDATA[This article is about flattening the list of element list with use of Java 8 stream feature <em>flatMap</em> and <em>forEach</em> <a href="https://codepills.com/flattening-stream-collections-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article is about Java 8 stream feature <em>flatMap</em>. If we have a <code>List&lt;List&lt;Object&gt;&gt;</code>, how can we turn the list of lists into a single list that contains all the elements from the lists in the same streamflow using the features of Java 8?</p>
<p><span id="more-1289"></span></p>
<h2>Introduction</h2>
<p>The answer is simply to use <em>flatMap</em> to flatten the lists of elements into one coherent list of the same elements. <code>flatMap</code> converts lists to streams in a single Stream and then collects the result into a list.</p>
<p>The best explanation will probably show the example of <em>flatMap</em> in action.</p>
<h2>Flattening the List with <em>flatMap</em> &#8211; Simple Example</h2>
<p>Let&#8217;s start with a simple example and continue with a more complex case later in the article. Our simple example will have a list of list with <em>String</em> elements. Each inner list contains a list of <em>String</em> elements which is a tuplet denoting at the first position the level of list and in the second position the overall total position of <em>String</em> element.</p>
<pre><code class="language-java">List&lt;List&lt;String&gt;&gt; nestedList = asList(
    asList("1-1", "1-2", "1-3"),
    asList("2-4", "2-5", "2-6", "2-7", "2-8"),
    asList("3-9", "3-10")
);</code></pre>
<p>We take this simple list above, and we will push it to our simple flattening method <em>flatteningTheListOfLists(List&lt;List&lt;String&gt;&gt; list)</em>.</p>
<pre><code class="language-java">public  List&lt;String&gt; flattenListOfLists(List&lt;List&lt;String&gt;&gt; list) {
    return list.stream()
               .flatMap(Collection::stream)
               .collect(Collectors.toList());
}</code></pre>
<p>As a result, we will get a list with all the <em>String</em> elements in one list.</p>
<pre><code class="language-java">@Test
public void testFlatteningTheListOfLists_simpleScenario() {
     List&lt;String&gt; flattenedList = flattenListOfLists(nestedList);

    assertNotNull(flattenedList);
    assertEquals(10, flattenedList.size());

    for (String element : flattenedList) {
        System.out.print(element);
    }
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">1-1, 1-2, 1-3, 2-4, 2-5, 2-6, 2-7, 2-8, 3-9, 3-10, </code></pre>
<h2>Flattening the List with <em>flatMap</em> &#8211; Realistic Scenario</h2>
<p>Instead of a simple play with a happy case scenario, hypothetically, let&#8217;s have a more advanced system where we will generate the list of objects directly in the stream. We will have a list of employees with their job position. And we would like to collect all their possible career options for employees above <i>junior engineer</i> level into a single list of all career options across all employees through a department. The resulting list will give us a list of possible combinations of employee promotions above the junior level.</p>
<p>Here is an example of <em>Employee</em> class:</p>
<pre><code class="language-java">public class Employee {

    private Position position;

    public Employee(Position position) {
        this.position = position;
    }

    public int getPosition() {
        return this.position;
    }
}</code></pre>
<p>And here is an example of <em>Employee</em> and <em>Position</em> class:</p>
<pre><code class="language-java">public class Employee {

    private final String name;
    private final Position position;

    public Employee(String name, Position position) {
        this.name = name;
        this.position = position;
    }

    public Position getPosition() {
        return position;
    }

}</code></pre>
<pre><code class="language-java">public enum Position {

    JUNIOR_ENGINEER(1),
    SENIOR_ENGINEER(2),
    SOFTWARE_ARCHITECT(3),
    ENGINEERING_MANAGER(4);

    private final int level;

    Position(int level) {
        this.level = level;
    }

    public int getLevel() {
        return this.level;
    }
}</code></pre>
<p>In order to get the list of all possible career options for all employees above <i>junior level</i> we would create for example something like <code>getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees)</code> where class <em>employee</em> property is a list of employees of <em>Employee</em> class. <code>getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees)</code> method will go through all the employees, filter employees from the list with level above junior level and create a list of possible career options for that specific employee. All the career options should be than pushed to <code>List</code> and outputted from stream to <code>List</code> collector.</p>
<pre><code class="language-java">public List&lt;Position&gt; getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees) {
    return employees.stream()
                    .filter(employee -> employee.getPosition().getLevel() > Position.JUNIOR_ENGINEER.getLevel())
                    .map(employee -> createPossibleCareerOptions(employee.getPosition().getLevel())) // This is bad practice and will not work
                    .collect(Collectors.toList());
}</code></pre>
<p>Example of <i>createPossibleCareerOptions()</i>:</p>
<pre><code class="language-java">public List&lt;Position&gt; createPossibleCareerOptions(int level) {
    return Arrays.stream(Position.values())
                 .filter(position -> position.getLevel() > level)
                 .collect(Collectors.toList());
}</code></pre>
<p>As we can see above, we mapped an employee to the list of her/his career options. But we want to collect list of all possibilities, not list of lists. Therefore, the code above does not work while stream <code>map</code> function maps <code>employee</code> instance into the list, but stream collector can not collect list of position list into the single list.</p>
<p>To make this code work, we need to introduce a consequent function in a stream that will flatten the list&#8217;s mapping into one stream. We need to place <code>flatMap</code> function for flattening the stream of list of positions into single steam positions for our Java stream.</p>
<pre><code class="language-java">public List&lt;Position&gt; getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees) {
    return employees.stream()
                    .filter(employee -> employee.getPosition().getLevel() > Position.JUNIOR_ENGINEER.getLevel())
                    .map(employee -> createPossibleCareerOptions(employee.getPosition().getLevel()))
                    .flatMap(List::stream) // I need to flatten list streams into one stream
                    .collect(Collectors.toList());
}</code></pre>
<p>Finally, let&#8217;s put all parts together and try the solution on the list of employees.</p>
<pre><code class="language-java">List&lt;Employee&gt; employees = asList(
        new Employee("Mark", Position.JUNIOR_ENGINEER),
        new Employee("Thomas", Position.SENIOR_ENGINEER),
        new Employee("Janet", Position.SOFTWARE_ARCHITECT),
        new Employee("Percy", Position.ENGINEERING_MANAGER)
);</code></pre>
<p>We can test the result with the test written below:</p>
<pre><code class="language-java">@Test
public void testFlatteningTheListOfLists_realisticScenario() {
    List&lt;Position&gt; allPossiblePromotions = getAllCareerOptionsAboveJunior(employees);

    assertNotNull(allPossiblePromotions);
    assertEquals(3, allPossiblePromotions.size());

    for (Position position : allPossiblePromotions) {
        System.out.print(position + ", ");
    }
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">SOFTWARE_ARCHITECT, ENGINEERING_MANAGER, ENGINEERING_MANAGER, </code></pre>
<p><b>Note</b> : If you have better idea for <code>Map</code> sorting, let me know in comments below.</p>
<h2>Flattening the <em>List</em> With <em>forEach</em></h2>
<p>To flatten this nested collection into a list of the same elements, we can also use <em>forEach</em> together with a Java 8 method reference. However, the solution with <em>forEach</em> might be discouraged by some developers as it needs to create a new reference on the list with results before it returns the complete results. Thus, creating the result variable will make the code more cumbersome and brittle. And while it might be suitable for small lists and simple applications, it brings pointlessly more complexity with its wrapping code for more complex scenarios as described above. On the contrary, it provides no advantage in the form of, for example, code readability.</p>
<p>Neither to say, let&#8217;s take a look at the option of flattening the stream of element&#8217;s list with the help of <em>forEach</em> method.</p>
<pre><code class="language-java">public List&lt;String&gt; useOfForEach(Stream&lt;List&lt;String&gt;&gt; streamOfLists) {
    List&lt;String&gt; result = new ArrayList<>();
    streamOfLists.forEach(result::addAll);
    return result;
}</code></pre>
<p>If we use the same list of simple <em>String</em> elements as for happy case scenario with <em>flatMap</em> we will get the same results.</p>
<h2>Conclusion</h2>
<p>We have seen in this article how to use a Java 8 Stream method <em>flatMap</em> first on a simple example and then on a more realistic scenario. We have also seen the option of flattening the stream with <em>forEach</em>. However, use of <em>forEach</em> might be discouraged on more realistic scenario when used on stream of <i>Objects</i> which generates the lists.</p>
<p>Did you find use of <em>flatMap</em> hard? Do you have your trick or you know another way <u>how to use <em>flatMap</em></u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
<p>As always, you can find all our examples on our <a href="https://github.com/codekopf/tutorials-jvm/tree/master/java-basics/java8/" title="Tutorial JVM - Java Basics - Java 8" target="_blank" rel="nofollow noopener">GitHub project</a>!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/flattening-stream-collections-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>What does the double star operator mean in Python?</title>
		<link>https://codepills.com/what-does-the-double-star-operator-mean-in-python/</link>
					<comments>https://codepills.com/what-does-the-double-star-operator-mean-in-python/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Tue, 01 Feb 2022 16:40:19 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[**kwargs]]></category>
		<category><![CDATA[double star]]></category>
		<category><![CDATA[double-asterisk]]></category>
		<category><![CDATA[method arguments]]></category>
		<category><![CDATA[power operator]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python functions]]></category>
		<category><![CDATA[two stars]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1283</guid>

					<description><![CDATA[In some Python code, you might spot double stars standing next to each other. What do those two stars mean, and what is their job? We will answer all the questions in this article. <a href="https://codepills.com/what-does-the-double-star-operator-mean-in-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In some Python code, you might spot double stars standing next to each other. What do those two stars mean, and what is their job? We will answer all the questions in this article.</p>
<p><span id="more-1283"></span></p>
<h2>Introduction</h2>
<p>Double star or double asterisk (**) in Python code can mean two different things based on the position in the code. First, if a double asterisk stands in the equation, it is part of it and is considered a <strong>Power operator</strong>. Otherwise, double-asterisk can occur in function and method argument input, and in such a case, it should be followed by <b>kwargs</b> shortcut (keyword arguments).</p>
<h2>Power Operator</h2>
<h3>What is double start operator in equation?</h3>
<p>Double star (or double-asterisk) in mathematical equation is one of the arithmetic operator (like +, -, *, **, /, //, %) in Python programming language. Double stars are also known as <strong>Power operator</strong>.</p>
<h3>What Power Operator does?</h3>
<p>For numerical data types Power operator works as an Exponential operator &#8211; anything on the right is the power of the left side.</p>
<p>Rather than talking about it, let&#8217;s demonstrate the Exponential operator on example:</p>
<pre><code class="language-python">two = 2
three = 3
# We can read the following notation as two to the power of the three
result = two ** three
# Result is according to the math laws, and it is equal to 2 * 2 * 2
print(result)

# Example of using double asterisk operator.
result_2 = 10 * (4 ** 2) - (2 ** 2) * 20
print(result_2)</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">8
80</code></pre>
<h2>What is the order of arithmetic operators?</h2>
<p>Arithmetic operators in Python follow the same precedence rule as in mathematics. The order is as follows: first performs exponential operator, then multiplication and division; as last executed are addition and subtraction, retrospectively.</p>
<p>Arithmetic operators ordered in decreasing order by priority:</p>
<pre><code class="language-bash">() -> ** -> * -> / -> // ->  % -> + -> -</code></pre>
<h2>** as variable argument length in functions and methods</h2>
<p>Interestingly, in Python, two starts fulfil also a different role. In Python&#8217;s function and method definition, the double-asterisk is also known for its role in defining variable argument length. Double asterisk concatenate with <i>kwargs</i> word and form <b><i>**kwargs</i></b>. So every time you see it, it means that the method or function it contains has a variable-length argument dictionary in the place of <b><i>**kwargs</i></b> occurrence. So when we use <i>**kwargs</i> as a parameter, we don&#8217;t need to know how many arguments we will need to pass to a function/method.</p>
<p>Btw. kwargs is not a Python reserved word and can be used in Python code independently.</p>
<h3>**kwargs examples</h3>
<p>Let&#8217;s write a simple function with <i>**kwargs</i>, taking various length arguments and passing them to a function.</p>
<pre><code class="language-java">def function(**kwargs):
    for key, value in kwargs.items():
        print("key: {} - value: {}".format(key, value))

function(pos1="John", pos2="Thomas", pos3="Paul")</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">key: pos1 - value: John
key: pos2 - value: Thomas
key: pos3 - value: Paul</code></pre>
<p>And now, let&#8217;s use the same function with additional arguments. Then, we will see how the function with <i>**kwargs</i> will accept a different number of arguments:</p>
<pre><code class="language-java">def function(**kwargs):
    for key, value in kwargs.items():
        print("key: {} - value: {}".format(key, value))

function(pos1="John", pos2="Thomas", pos3="Paul", pos4="Isabella", pos5="Carry", pos6="Angela")</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">key: pos1 - value: John
key: pos2 - value: Thomas
key: pos3 - value: Paul
key: pos4 - value: Isabella
key: pos5 - value: Carry
key: pos6 - value: Angela</code></pre>
<p><b>Note</b>: It is a good idea to create functions that accept <i>**kwargs</i> where you expect the number of inputs within the argument list to remain relatively small.</p>
<h2>Conclusion</h2>
<p>This article has shown two different ways how the double asterisk is used. First, we have seen the order of arithmetic operators in Python and how a double asterisk denotes a mathematical Power operator. The second usage is variable argument length in Python&#8217;s functions and class methods. Usage of <b><i>**kwargs</i></b> provides us flexibility to use keyword arguments in our program.</p>
<p>Did you find the usage of double stars in Python confusing? Do you have any tricks or know another way <u>how to use double stars in Python</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/what-does-the-double-star-operator-mean-in-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to join List String elements with a comma</title>
		<link>https://codepills.com/how-to-join-list-string-elements-with-a-comma/</link>
					<comments>https://codepills.com/how-to-join-list-string-elements-with-a-comma/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 01 Jan 2022 14:09:21 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[brute force]]></category>
		<category><![CDATA[Java 8]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1277</guid>

					<description><![CDATA[In this article, we will see three different ways to print string elements of the list into one coherent text. <a href="https://codepills.com/how-to-join-list-string-elements-with-a-comma/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will show three different ways to print string elements of the list into one coherent text.</p>
<p><span id="more-1277"></span></p>
<h2>Introduction</h2>
<p>A software developer encounters the trivial task of joining string elements in the list from time to time into one coherent text. Reasons vary widely &#8211; from printing elements to logs to showing the text to the user. But be sure that the solution for this problem should be straightforward when you want to use the Java programming language the most effectively.</p>
<p>We will use a list of random US states codes such as  TX, WA, NY etc., for demonstration in our showcases.</p>
<p>First of all, let me show you the proper way to utilize the Java language most effectively. These solutions will require to use of at least version Java 8.</p>
<h2>String build-in join method</h2>
<p>Java 8 implemented to core String class, in a same way as many other programming languages, <code>join()</code> method. <code>join()</code> method has two arguments:</p>
<ul>
<li>The first argument is called <b>separator</b>. Separator is single character or sequence of characters with which elements should be joined together.</li>
<li>The second argument is the Java&#8217;s object implementing the List interface from which the elements will be taken and joined.</li>
</ul>
<p>Be noted that a separator can be a single character or sequence of characters. We will connect our US state codes on the sequence of characters: space + comma + space. You can use only a comma to get a more concise text.</p>
<pre><code class="language-java">package com.codepills;

import java.util.Arrays;
import java.util.List;

public class JoiningStatesWithJoinMethod {

    public static void main(String[] args) {
        List<String> states = Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA");
        String text = String.join(" , ", states);
        System.out.println(text);
    }

}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">TX , WA , NY , AZ , MI , AL , CA</code></pre>
<h2>Joining String elements in Java Stream</h2>
<p>Another way to join string elements and create a single line of text is to stream through all the list elements and join them on a collection of characters or sequences of characters. Unfortunately, this solution also requires using at least the Java 8 version since handling and collecting streams is a significant release feature of Java 8. Let&#8217;s use Collector&#8217;s <code>joining()</code> static method with single argument &#8211; separator.</p>
<pre><code class="language-java">package com.codepills;

import java.util.Arrays;
import java.util.List;

public class JoiningStatesWithStreamCollection {

    public static void main(String[] args) {
        List<String> states = Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA");
        String text = states.stream().collect(Collectors.joining(","));
        System.out.println(text);
    }

}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">TX , WA , NY , AZ , MI , AL , CA</code></pre>
<h2>Brute force</h2>
<p>The last way to join strings together is to use simply brute force. Using brute force is the last option as it creates more code than necessary. Especially for newer versions of Java, it is recommended to use String&#8217;s build-in <code>join()</code> method. Therefore brute-force is more or less an option for legacy code, code written in Java 7 and less.</p>
<pre><code class="language-java">package com.codepills;

import java.util.Arrays;
import java.util.List;

public class JoiningStatesWithBruteForce {

    public static void main(String[] args) {
        System.out.println(customJoin(",", Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA")));
        System.out.println(customJoin(",", Arrays.asList("TX")));
        System.out.println(customJoin(",", Arrays.asList("")));
        System.out.println(customJoin(",", null));
    }

    private static String customJoin(String separator, List<String> input) {

        if (input == null || input.size() <= 0) return "";

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < input.size(); i++) {
            stringBuilder.append(input.get(i));
            // Do not print separator for the last element
            if (i != input.size() - 1) {
                stringBuilder.append(separator);
            }
        }

        return stringBuilder.toString();
    }

}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">TX , WA , NY , AZ , MI , AL , CA
TX
 // empty
</code></pre>
<p>We placed all possible options for input to <code>main()</code> method in order to test our <code>customJoin()</code> method properly.</p>
<p>Eventually, you can see we are using more custom code than is necessary. All this custom functionality can be replaced by single line in case of String's <code>join()</code> method. Therefore use this custom solution only when it does make sense.</p>
<h2>Conclusion</h2>
<p>This article has shown three different ways to print string elements of the list into one coherent test.</p>
<p>Did you find concatenating easy? Do you have your trick or know another way <u>how to join list elements</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-join-list-string-elements-with-a-comma/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to convert a Map to an Array in Java</title>
		<link>https://codepills.com/how-to-convert-a-map-to-an-array-in-java/</link>
					<comments>https://codepills.com/how-to-convert-a-map-to-an-array-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 12 Mar 2021 13:35:50 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[Collection]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[HashMap]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[LinkedHashMap]]></category>
		<category><![CDATA[Map]]></category>
		<category><![CDATA[TreeMap]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1182</guid>

					<description><![CDATA[This tutorial is about several approaches to converting Java's Map interface implementations into the Java array. <a href="https://codepills.com/how-to-convert-a-map-to-an-array-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This tutorial is about several approaches to converting Java&#8217;s Map interface implementations into the Java array.</p>
<p><span id="more-1182"></span></p>
<h2>Introduction</h2>
<p>In order to turn Java <code>Map</code> to array, it always depend what you actually want to take from the <code>Map</code> itself. You can only want keys or values or transform key-value pairs on a completely different object while turning them into an array.</p>
<p><b>Note</b></p>
<p>We need to note, that in most of our examples we <b>will use</b> <code>HashMap</code> <b>implementation</b> as underlying layer upon which the algorithms are build. If the implementation change and it will affect the algorithm, it will be notably depicted and described.</p>
<h2>Map Map.Entry<K,V> to Array</h2>
<p>Our first approach is the simplest and probably covers most of the cases in real life. The approach obtains <code>Map.Entry<K,V></code> from <code>Map</code> and then turn the collection to an array.</p>
<p>We will use non-parametrized call of <code>Set.toArray()</code> for <code>Entry<K,V></code> collection. Let&#8217;s look at the example below:</p>
<pre><code class="language-java">// Method to convert Map entry set into an Array in Java
public static void entrySetToArray()
{
    final Map<String, String> map = new HashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Gets the Map entry set and turns it into an Array of Objects
    final Object[] objectArray = map.entrySet().toArray();

    System.out.println(Arrays.toString(objectArray));
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">[Paul Smith=555-400-321, John Doe=555-869-759, Thomas Cook=555-906-941]</code></pre>
<h2>Map Keys to Array</h2>
<p>Sometimes we want to map <code>Map</code> keys to an array. For this we need to use combination of <code>Map.keySet()</code> for obtaining keys and parametrized call of <code>Set.toArray(T[] a)</code> method for keeping a set of keys. Than we can turn key set to an <code>Array</code>.</p>
<pre><code class="language-java">// Method to convert Map keys into an Array in Java
public static void keySetToArray()
{
    final Map<String, String> map = new HashMap<>();<>

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Gets the Map set of keys which is turned to an Array of Strings
    String[] keys = map.keySet().toArray(new String[0]);

    System.out.println(Arrays.toString(keys));
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">[Paul Smith, John Doe, Thomas Cook]</code></pre>
<h2>Map Values to Array</h2>
<p>Other times, we want to map <code>Map</code> values to an array. For this we need to use combination of <code>Map.values()</code> for obtaining keys and parametrized call of <code>Collection.toArray(T[] a)</code> method for keeping a collection of values. Than we can turn value collection to an <code>Array</code>.</p>
<pre><code class="language-java">// Method to convert Map values into an Array in Java
public static void valuesCollectionToArray()
{
    final Map<String, String> map = new HashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Gets the Map collection of values and turn it into the Array of Strings
    String[] values = map.values().toArray(new String[0]);

    System.out.println(Arrays.toString(values));
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">[555-400-321, 555-869-759, 555-906-941]</code></pre>
<h2>Map to Array with element order secured</h2>
<p>We have seen that we can get an array of keys and values of the <code>Map</code> using <code>Map.keySet()</code> and <code>Map.values()</code>. Using both methods we can keep the individual elements in separate arrays and construct a new array of key-value pairs from them.</p>
<p>However we will need to use different <code>Map</code> interface implementation than <code>HashMap</code>. We have to use <code>LinkedHashMap</code> which can secure the order of elements in the order of their insertion into the <code>Map</code> data structure implementation. In this way, we can create two different arrays, one for keys and the second for values, but we can rest assure that the order of elements in individual arrays will be matching their mutual pair in the <code>Map</code>.</p>
<pre><code class="language-java">// Method to convert Map elements to an Array in Java
// However, the core of this method lies in the Map's implementation LinkedHashMap
// which maintains the order of inserted elements in the order of their insertion.
public static void useLinkedHashMapElementOrderForArrayConversion()
{
    final Map<String, String> map = new LinkedHashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Get an array of keys in order of the LinkedHashMap
    final String[] keys = map.keySet().toArray(new String[0]);

    // Get an array of values in order of the LinkedHashMap
    final String[] values = map.values().toArray(new String[0]);

    for (int i = 0; i < map.size(); i++) {
        System.out.println( "[ " + keys[i] + " = " + values[i] + " ]" );
    }
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">[ John Doe = 555-869-759 ]
[ Thomas Cook = 555-906-941 ]
[ Paul Smith = 555-400-321 ]</code></pre>
<h2>Map to Array with element order unsecured</h2>
<p>Finally, we need to discuss the option when the elements' order is not secured, but we want to use two different arrays for help.</p>
<p>When we look on the algorithm above, it seems a little bit straightforward how to map elements to an array. However, when <code>HashMap</code> or <code>TreeMap</code> implementation of <code>Map</code> is used, the order of element in both arrays might change. For example for any index <code>i</code>, there is no guarantee that <code>key[i]</code> will represents the pairing key for <code>value[i]</code> value. To guarantee the correct pair position we need to construct helping arrays and map the pair position into the same indexes in helping arrays.</p>
<pre><code class="language-java">// Method to convert Map to an Array in Java
public static void maintainKeySetAndValueCollectionArray()
{
    final Map<String, String> map = new HashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Temporary array to store map keys
    final String[] keys = new String[map.size()];

    // Temporary array to store map values
    final String[] values = new String[map.size()];

    int i = 0;

    for (Map.Entry<String, String> entry : map.entrySet()) {
        keys[i] = entry.getKey();
        values[i] = entry.getValue();
        i++;
    }

    for (i = 0; i < map.size(); i++) {
        System.out.println( "[ " + keys[i] + " = " + values[i] + " ]" );
    }
}</code></pre>
<p><b>Note</b></p>
<p><code>i</code> is local variable. We can insert <code>i</code> incrementation into the <code>values[i]</code> if you like concise code. However for more readable code, we recomment the incrementation to place on to the new line.</p>
<p>Also, local <code>i</code> variable is reseted for <code>System.out</code> line printing.</p>
<p><b>Output</b></p>
<pre><code class="language-java">[ Paul Smith = 555-400-321 ]
[ John Doe = 555-869-759 ]
[ Thomas Cook = 555-906-941 ]</code></pre>
<h2>Conclusion</h2>
<p>This article has shown how to convert Java's <code>Map</code> to an Array by various approaches.</p>
<p>All algorithms are placed in the Java method for quick copy and paste into your projects.</p>
<p>While the first three algorithms (Entry<K,V>, Keys, Values) will cover most of the real-life scenarios of <code>Map</code> to <code>Array</code> conversion, we have shown two more approaches which give you a space for more transformation and conversion. Plus, last two approaches (Map element order secured, Map element order unsecured) pointing out solutions for element order <code>Map</code> security issues.</p>
<p>As always, you can find all our examples on our <a href="https://github.com/codekopf/tutorials-jvm/tree/master/java-basics/java-core/" title="Tutorial JVM - Java Basics - Java Core" target="_blank" rel="nofollow noopener">GitHub project</a>!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-convert-a-map-to-an-array-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to initialize an array with zero values in Java</title>
		<link>https://codepills.com/how-to-initialize-an-array-with-zero-values-in-java/</link>
					<comments>https://codepills.com/how-to-initialize-an-array-with-zero-values-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Mon, 01 Mar 2021 19:56:37 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[primitive type]]></category>
		<category><![CDATA[reference type]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1136</guid>

					<description><![CDATA[This article will look at how to fill up Java array with default values effectively on an array creation. <a href="https://codepills.com/how-to-initialize-an-array-with-zero-values-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will look at how to fill up a Java array with default values effectively on an array creation.</p>
<p><span id="more-1136"></span></p>
<h2>Overview</h2>
<p>Arrays are essential cornerstones of every modern programming language. On a specific occasion, you need to initialize an array with zero values. This article will take you through the pros and cons of the various way how to initialize Java array with default zero values.</p>
<h2>Introduction to Java data types</h2>
<p>In Java we have several different data types. Majority of data types are called primitive data types. To this group belong <strong>byte</strong>, <strong>short</strong>, <strong>int</strong>, <strong>long</strong>, <strong>float</strong>, <strong>double</strong>, <strong>boolean</strong> and <strong>char</strong>.</p>
<p>For more information about Java&#8217;s data type, please read our article about primitive data types.</p>
<p>Speaking about Java&#8217;s data type, there is also a general notation of different data type represented by referencing the object&#8217;s type. We are talking about object references, where the type of the object is classified by the object&#8217;s referencing type. Sound confusing? If you are new to Java, let me point you out to one of the most asked Java questions Is Java pass by value or pass by reference?</p>
<h2>Java data type default values</h2>
<p>Let&#8217;s take a look what is initial (default) value in <strong>Java language</strong> for any variable initialization.</p>
<ul>
<li>The default value for type <strong>byte</strong> is zero. That means in byte the value of (byte) is <strong>0</strong>.</li>
<li>The default value for type <strong>short</strong> is zero. That means in the short the value of (short) is <strong>0</strong>.</li>
<li>The default value for type <strong>int</strong> is zero. That means in int the value of (int) is <strong>0</strong>.</li>
<li>The default value for type <strong>long</strong> is zero. That means in long the value of (long) is <strong>0L</strong>.</li>
<li>The default value for type <strong>float</strong> is positive zero. That means in float the value of (float) is <strong>0.0f</strong>.</li>
<li>The default value for type <strong>double</strong> is positive zero. That means in double the value of (double) is <strong>0.0d</strong>.</li>
<li>The default value for type <strong>boolean</strong> is <strong>false</strong>.</li>
<li>The default value for type <strong>char</strong> is the null character. That means in char the value of (char) is <strong>&#8216;\u0000&#8217;</strong>.</li>
<li>The default value for <strong>all reference</strong> types (Sting or any Object parent or its child) is <strong>null</strong>.</li>
</ul>
<p>If you have noticed, primitive data types are initialized in their form of number zero. The exception is boolean, where the default state is false. However, this representation of the default state comes from generation-lasting philosophical discussion beyond this blog&#8217;s scope.</p>
<h2>Default data type for String and arrays</h2>
<p>It is important to remember that in Java, an array is a container object that holds a fixed number of values of a single type.</p>
<p>The <i>String</i> object is unique in a certain way. It is because it is wrapping object around an array collection of primitive char data types. However, we always reference the <i>String</i> object, not <i>String</i>&#8216;s internal array.</p>
<p><strong>Array of primitive types</strong> keeps initialization value equal default value for each element of primitive data type.</p>
<pre><code class="language-java">double[] treePrimitiveDoubles = new double[3];

double zeroElementPrimitive = treePrimitiveDoubles[0];
System.out.print(zeroElementPrimitive);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">>> 0.0</code></pre>
<p><strong>Array of reference type</strong> keeps initialization value equal null. The <i>String</i> is the same; it keeps the initialization value equal null.</p>
<pre><code class="language-java">Double[] treeReferenceDoubles = new Double[3];

Double zeroElementReference = treeReferenceDoubles[0];
System.out.print(zeroElementReference);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">>> null</code></pre>
<p>We instantly see that we need to create the objects to fill the arrays of the reference type array.</p>
<h2>Filling default values to reference type arrays</h2>
<p>There are two different approaches for reference type arrays on how to fill up an array by a particular type. First is the classic iterative approach, where you loop through the collection and fill the position individually.</p>
<pre><code class="language-java">BankAccount[] arrayOfAllBankAccounts = new BankAccount[50];

for(int i = 0; i < arrayOfAllBankAccounts.length; i++) {
    arrayOfAllBankAccounts[i] = new BankAccount();
}</code></pre>
<p>The second option is to use a more procedural approach with the help of <code>java.util.Arrays</code>. If you want to initialize a one-dimensional array with default values, you can use the static <code>.fill()</code> method. Although, internally <code>.fill()</code> method uses a loop. However, code notation is much more concise. Let's look at the code notation:</p>
<pre><code class="language-java">BankAccount[] arrayOfAllBankAccounts = new BankAccount[50];

Arrays.fill(arrayOfAllBankAccounts, new BankAccount());</code></pre>
<h2>Performance</h2>
<p>Consider the array of arbitrary length which will store reference type for Object counterparts of primitive types such as <strong>Byte</strong>, <strong>Short</strong>, <strong>Integer</strong>, <strong>Long</strong>, <strong>Float</strong>, <strong>Double</strong>, <strong>Boolean</strong> and <strong>Char</strong> class. And imagine now that you would do this for many many arrays like this in your program. This would dramatically decrease performance of your application; you would waste a lot of machine cycles just for initialization. It would affect your application performance by considerable level.</p>
<p>Each array consisted of an Object version of primitive types that would not only take longer to initialize than a regular primitive type array, but it would even require allocating more memory than necessary. Consequently, if you want to use <i>Object</i> version of a primitive type, use them only when essential for your code solution.</p>
<p>Initialization of arrays with primitive types is quick and fast, does not allocate a lot of memory. You can prefer them over their reference type versions.</p>
<h3>String performance</h3>
<p>Java's <i>String</i> class has a special place in our hearts. As we said, <i>String</i> class uses an array of primitive characters for storing text. On each addition or change text, <i>String</i> needs to compute if the allocated array length is sufficient. If it is not, it needs to allocate a new - more significant size for the internal array of primitive characters and copy the existing text to a new array of primitive characters. Resizing mechanism naturally decrease performance. There are two ways how to mitigate this issue. First, it is highly recommended to not use concatenation on <i>String</i>s in your code. And second, if you know you will be using a lot of text manipulation, use the <i>StringBuilder</i> class.</p>
<h2>Conclusion</h2>
<p>In this article, we have seen how to initialize the array in Java with zero values. As always, you can find all codes in this article in out <a href="https://github.com/codekopf/tutorials-jvm/tree/master/java-basics/java-core" title="Tutorial JVM - Java Core" target="_blank" rel="nofollow noopener">GitHub repository</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-initialize-an-array-with-zero-values-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Bit manipulation operators in Java</title>
		<link>https://codepills.com/bit-manipulation-operators-in-java/</link>
					<comments>https://codepills.com/bit-manipulation-operators-in-java/#comments</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 12 Dec 2020 09:11:51 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[bit manipulation]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java SE]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1099</guid>

					<description><![CDATA[Java offers a possibility for bit manipulation with bit operators in its code. This article will go through all the operators with real-life <a href="https://codepills.com/bit-manipulation-operators-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>As in many programming languages, Java offers a possibility for bit manipulation with bit operators. While the <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.htm" title="Bitwise and Bit Shift Operators" target="_blank" rel="nofollow noopener">official documentation</a> is kind of sparse, this article will give you more information about individual operators.</p>
<p><span id="more-1099"></span></p>
<p>We can divide bit manipulating operators into two categories categorized by the kind of operation operators do. We have <strong>bitwise operators</strong> such as AND, OR, XOR and bitwise complement; and <strong>shift operators</strong> such as Signed right shift, Unsigned right shift and Unsigned left shift operators. Let&#8217;s take a closer look at individual operators with real-life examples.</p>
<h2>Bitwise operators</h2>
<p>Bitwise operators are used to perform individual bits manipulation. However, we can also use them with integral types such as char, short, int, etc.</p>
<h3>Bitwise operator AND &#8211; &#038;</h3>
<p><b>AND</b> operator is binary operator, denoted by <b>&#8216;&#038;&#8217;</b> character in Java. It returns bit result of AND operation on input variables.</p>
<p>Let&#8217;s take a look on AND table and explain the OR bit operator on example below:</p>
<table>
<thead>
<tr>
<th scope="col">A</th>
<th scope="col">B</th>
<th scope="col">A &#038; B</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<pre><code class="language-bash">    A = 3 = 0011 [Binary]
    B = 5 = 0101 [Binary]

    Bitwise AND Operation of 3 and 5
    0011 &
    0101
    ________
    0001  = 1 [Decimal]</code></pre>
<h4>&#038; assignment trick</h4>
<p><b>&#038;</b> can be in Java also combined with assignment operator to provide shorthand assignment e.g.:</p>
<pre><code class="language-bash">    a = a&b
    a &= b;</code></pre>
<h3>Bitwise operator OR &#8211; |</h3>
<p><b>OR</b> operator is binary operator, denoted by <b>&#8216;|&#8217;</b> character in Java. It returns bit result of OR operation on input variables.</p>
<p>Let&#8217;s take a look on OR table and explain the OR bit operator on example below:</p>
<table>
<thead>
<tr>
<th scope="col">A</th>
<th scope="col">B</th>
<th scope="col">A | B</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<pre><code class="language-bash">    A = 3 = 0011 [Binary]
    B = 5 = 0101 [Binary]

    Bitwise OR Operation of 3 and 5
    0011 |
    0101
    ________
    0111  = 7 [Decimal]</code></pre>
<h3>Bitwise operator XOR &#8211; ^</h3>
<p><b>XOR</b> operator is binary operator, denoted by <b>&#8216;^&#8217;</b> character in Java. It returns bit result of XOR operation on input variables.</p>
<p>Let&#8217;s take a look on XOR table and explain the OR bit operator on example below:</p>
<table>
<thead>
<tr>
<th scope="col">A</th>
<th scope="col">B</th>
<th scope="col">A ^ B</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>0</td>
</tr>
</tbody>
</table>
<pre><code class="language-bash">    A = 3 = 0011 [Binary]
    B = 5 = 0101 [Binary]

    Bitwise XOR Operation of 3 and 5
    0011 ^
    0101
    ________
    0110  = 6 [Decimal]</code></pre>
<h3>Bitwise complement &#8211; ~</h3>
<p>This is unary operator, denoted by <b>&#8216;~&#8217;</b> character in Java. It means it returns one&#8217;s complement representation of the input value. It means flipping bits on the opposite value where 1 is 0 and 0 is 1.</p>
<p>Let&#8217;s take a look on XOR table and explain the OR bit operator on example below:</p>
<pre><code class="language-bash">    A = 3 = 0011 [Binary]

    Bitwise OR Operation of 3 and 5
    ~0011
    ________
    1100  = 12 [Decimal]</code></pre>
<h2>Shift operators</h2>
<p>Shift operators are used to shift the bits for a number of positions to the left or right. Due to bits movement, shifting bits multiply or divide the number by two, respectively.</p>
<p>Generally, shift operators can be used when we have to multiply or divide a number by two.</p>
<h3>Signed right shift operator &#8211; >></h3>
<p>Signed right operator is denoted by <b>&#8216;>>&#8217;</b> characters in Java. The signed right operator shifts the bits for the number of positions <b>to the right and fills the blank bit positions with 0</b> as a result.</p>
<p>The leftmost bit depends on the sign of the initial number. <b>With signed right shift we preserve the sign bit</b>.</p>
<p>Similarly, shifting bits right affects number as if it would be divided by the power of two.</p>
<pre><code class="language-bash">      5 => 0 0101>>2 =  1 = 0 0001
    -10 => 1 0110>>2 = -3 = 1111 1111 1111 1111 1111 1111 1111 1101</code></pre>
<h3>Unsigned right shift operator &#8211; >>></h3>
<p>Unsigned right operator is denoted by <b>&#8216;>>>&#8217;</b> characters in Java. The unsigned right operator shifts the bits for the number of positions to the right and fills the blank bit positions with 0s.</p>
<p>The leftmost bit is set to 0. Difference between signed and unsigned right shift operator is that unsigned-shift operator <b>(>>>)</b> will insert 0 while signed operator <b>(>>)</b> will extend the sign bit. <b><u>With unsigned right shift we do not preserve the sign bit</u></b>.</p>
<pre><code class="language-bash">      5 => 0 0101>>>2 = 1          = 0 0001
        // Similar to 5/(2^2)
      8 => 0 1000>>>2 = 2          = 0 0010
        // Similar to 8/(2^2)
    -10 => 1 0110>>>2 = 1073741821 = 11 1111 1111 1111 1111 1111 1111 1101 = 0011 1111 1111 1111 1111 1111 1111 1101
        // !!! Remember unsigned right shift operator for negative numbers - first 2 bits become 0 (and do not display in binary string)</code></pre>
<h3>Signed left shift operator &#8211; <<</h3>
<p>Signed left operator is denoted by <b>&#8216;<<<'</b> characters in Java. The signed left operator shifts the bits for the number of positions to the left and fills the blank bit positions with 0s.</p>
<p>The leftmost bit depends on the sign of the initial number. <b>With signed left shift we preserve the sign bit</b>.</p>
<p>Similarly, shifting bits left affects the number as if it would be <b>multiplied by the power of two</b>.</p>
<pre><code class="language-bash">      5 => 0 0101<<2 =  20 = 10100
            // Similar to 5*(2^2)
    -10 => 1 0110<<2 = -40 = 1111 1111 1111 1111 1111 1111 1101 1000
            // Similar to -10*(2^2)</code></pre>
<h3>Unsigned left shift operator - <<<</h3>
<p>Unlike unsigned light shift, <b>there is no "<<<" operator in Java</b>. The logical <b>(<<)</b> and arithmetic left-shift <b>(<<<)</b> operations are identical.</p>
<h2>Example code</h2>
<pre><code class="language-java">public class Test {
     public static void main(String []args) {

        int a = 3;
        int b = 5;
        int c = -7;
        int d = -10;

        // For testing of bitwise and assigning operators use
        // Integer.toBinaryString();


        // Bitwise AND
        // 0 0011 & 0 0101 = 0 0001 = 1
        System.out.println("A & B = " + (a & b));
        // 1 0111 & 1 1010 = 1 0000 = -16 = 1111 1111 1111 1111 1111 1111 1111 0000
        System.out.println("C & D = " + (c & d));


        // Bitwise OR
        // 0 0011 | 0 0101 = 0 0111 = 7
        System.out.println("A | B = " + (a | b));
        // 1 0111 | 1 1010 = 1 1111 = -1 = 1111 1111 1111 1111 1111 1111 1111 1111
        System.out.println("C | D = " + (c | d));


        // Bitwise XOR
        // 3 => 0 0011 ^ 0 0101 = 0 0110 = 6
        System.out.println("A ^ B = " + (a ^ b));
        // -7 => 1 0111 ^ 1 1010 = 0 1111 = 15
        System.out.println("C ^ D = " + (c ^ d));


        // Bitwise complement
        // ~0 0011 = -4 = 1111 1111 1111 1111 1111 1111 1111 1100
        System.out.println("~A = " + ~a);
        // 1 0111 = 6 = 110
        // will give 2's complement of 1010 = -6
        System.out.println("~C = " + ~c);


        // Signed right shift operator
        // 5 => 0 0101>>2 = 1 = 0 0001
        System.out.println("B>>2 = " + (b >> 2));
        // -10 => 1 0110>>2 = -3 = 1111 1111 1111 1111 1111 1111 1111 1101
        System.out.println("D>>2 = " + (d >> 2));


        // Unsigned right shift operator
        // 5 => 0 0101>>>2 = 1 = 0 0001
        System.out.println("B>>>2 = " + (b >>> 2));
        // -10 => 1 0110>>>2 = 1073741821 = 11 1111 1111 1111 1111 1111 1111 1101
        System.out.println("D>>>2 = " + d >>> 2);
        // !!! Important observation for negative numbers - first 2 bits become 0
        // (and do not display in binary string)


        // 5 => 0 0101<<2 = 20 = 10100
        // Similar to 5*(2^2)
        System.out.println("C<<2 = " + (b << 2));
        // -10 => 1 0110<<2 = -40 = 1111 1111 1111 1111 1111 1111 1101 1000
        // Similar to -10*(2^2)
        System.out.println("D<<2 = " + (d << 2));
     }
}</code></pre>
<p><b>Note:</b> Just to help with some bit transformation, here is a bit integer number transformation table to binary 4-bit and 8-bit representation.</p>
<table>
<thead>
<tr>
<th scope="col">Decadical</th>
<th scope="col">16</th>
<th scope="col">255</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0000</td>
<td>00000000</td>
</tr>
<tr>
<td>1</td>
<td>0001</td>
<td>00000001</td>
</tr>
<tr>
<td>2</td>
<td>0010</td>
<td>00000010</td>
</tr>
<tr>
<td>3</td>
<td>0011</td>
<td>00000011</td>
</tr>
<tr>
<td>4</td>
<td>0100</td>
<td>000000100</td>
</tr>
<tr>
<td>5</td>
<td>0101</td>
<td>00000101</td>
</tr>
<tr>
<td>6</td>
<td>0110</td>
<td>00000110</td>
</tr>
<tr>
<td>7</td>
<td>0111</td>
<td>00000111</td>
</tr>
<tr>
<td>8</td>
<td>1000</td>
<td>00001000</td>
</tr>
<tr>
<td>9</td>
<td>1001</td>
<td>00001001</td>
</tr>
<tr>
<td>10</td>
<td>1010</td>
<td>00001010</td>
</tr>
<tr>
<td>11</td>
<td>1011</td>
<td>00001011</td>
</tr>
<tr>
<td>12</td>
<td>1100</td>
<td>00001100</td>
</tr>
<tr>
<td>13</td>
<td>1101</td>
<td>00001101</td>
</tr>
<tr>
<td>14</td>
<td>1110</td>
<td>00001110</td>
</tr>
<tr>
<td>15</td>
<td>1111</td>
<td>00001111</td>
</tr>
<tr>
<td>16</td>
<td>----</td>
<td>00010000</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>254</td>
<td>----</td>
<td>11111110</td>
</tr>
<tr>
<td>255</td>
<td>----</td>
<td>11111111</td>
</tr>
</tbody>
</table>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/bit-manipulation-operators-in-java/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>How to show first n characters in JavaScript or TypeScript string</title>
		<link>https://codepills.com/how-to-show-first-n-characters-in-javascript-or-typescript-string/</link>
					<comments>https://codepills.com/how-to-show-first-n-characters-in-javascript-or-typescript-string/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Wed, 09 Dec 2020 12:57:38 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[substring]]></category>
		<category><![CDATA[TypeScript]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1089</guid>

					<description><![CDATA[This article will show you three different ways how to obtain substring from a string in JavaScript or TypeScript <a href="https://codepills.com/how-to-show-first-n-characters-in-javascript-or-typescript-string/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>To get a substring from a string in JavaScript or TypeScript, you have three different methods to call as an option. Besides TypeScript compiling to JavaScript, the method&#8217;s names a behaviour stay the same.</p>
<p><span id="more-1089"></span></p>
<h2>What is the difference between slice(), substr() and substring() string methods?</h2>
<p>The <code>slice()</code> method extracts parts of a string and returns the extracted parts in a <u>new string</u>. <code>slice()</code> does not change original string.</p>
<p><b>Syntax</b></p>
<p><code>string.slice(start_position, end_position_excluded)</code></p>
<p>The <code>substr()</code> method extracts parts of a string, beginning at the character at the specified position, and returns the limited number of characters. <code>substr()</code> does not change original string.</p>
<p><b>Syntax</b></p>
<p><code>string.substr(start_position, length)</code></p>
<p>The <code>substring()</code> method extracts parts of a string and returns the extracted parts in a <u>new string</u>. <code>substring()</code> does not change original string.</p>
<p><b>Syntax</b></p>
<p><code>string.substring(start_position, end_position_excluded)</code></p>
<p>As a conclusion we can say that there is a difference between <code>slice()</code> and <code>substr()</code>, while <code>substring()</code> is basically a copy of <code>slice()</code>.</p>
<p>Let&#8217;s take a better look at the differences between the individual methods.</p>
<h2>Slice()</h2>
<pre><code class="language-typescript">var string = "1234567890"
var substr=string.slice(4);
console.log(substr);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">567890</code></pre>
<p><code>substr(4)</code> will remain everything after first 4 characters.</p>
<pre><code class="language-typescript">var string = "1234567890"
var substr = string.slice(0, 4);
console.log(substr);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">1234</code></pre>
<p><code>substr(0, 4)</code> will keep the first 4 characters. Second argument exclude the argument position (upper bound excluded).</p>
<pre><code class="language-typescript">var string = "1234567890"
var substr = string.slice(-4);
console.log(substr);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">890</code></pre>
<p><code>substr(-4)</code> will keep the last 4 characters.</p>
<h2>Substr()</h2>
<pre><code class="language-typescript">var string = "1234567890"
var substr=string.substr(4);
console.log(substr);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">567890</code></pre>
<p><code>substr(4)</code> will remain everything after first 4 characters.</p>
<pre><code class="language-typescript">var string = "1234567890"
var substr = string.substr(0, 4);
console.log(substr);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">1234</code></pre>
<p><code>substr(0, 4)</code> will keep the first 4 characters. Second argument denotes the number of characters to extract.</p>
<pre><code class="language-typescript">var string = "1234567890"
var substr = string.substr(-4);
console.log(substr);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">890</code></pre>
<p><code>substr(-4)</code> will keep the last 4 characters.</p>
<h2>Substring()</h2>
<pre><code class="language-typescript">var string = "1234567890"
var substr=string.substring(4);
console.log(substr);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">567890</code></pre>
<p><code>substr(4)</code> will remain everything after first 4 characters.</p>
<pre><code class="language-typescript">var string = "1234567890"
var substr = string.substring(0, 4);
console.log(substr);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">1234</code></pre>
<p><code>substr(0, 4)</code> will keep the first 4 characters. Second argument exclude the argument position (upper bound excluded).</p>
<p><strong>General note regarding indexes in all 3 methods:</strong> Strings are arrays of characters. Therefore they start character order from 0.</p>
<h2>Conclusion</h2>
<p>As you can see, using <code>substring</code> is nearly identical to <code>split()</code> or <code>substr()</code> method. However there are some small differences. For example <code>substring()</code> does not have option to add negative number and count string split backwards. Also if first argument is greater than the second, <code>substring</code> will swap the two arguments, and perform as usual.</p>
<p>Basically, if you know the the position (index) on which you will start and the length of the of characters to be extracted, use <code>subst(start_position, length)</code>. Otherwise if you know the position (index) you want to start and end, but <b>NOT</b> include the end position, use <code>slice(start_position, end_position_excluded)</code>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-show-first-n-characters-in-javascript-or-typescript-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to use IntStream range in Java</title>
		<link>https://codepills.com/how-to-use-intstream-range-in-java/</link>
					<comments>https://codepills.com/how-to-use-intstream-range-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sun, 06 Dec 2020 11:55:43 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[range]]></category>
		<category><![CDATA[streams]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1079</guid>

					<description><![CDATA[This article talks about the average use case of loop count variable usage via IntStream API <a href="https://codepills.com/how-to-use-intstream-range-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>I often encounter a situation where I need to loop through a collection in Java. While looping through the collection sequentially, I usually want to use a temporal loop count variable as a variable with which I will be working inside the loop.</p>
<p><span id="more-1079"></span></p>
<p>Java 8 come with beautiful solution on this pattern. It is called <code>IntStream</code>.</p>
<h2>Example of IntStream range() method</h2>
<p>Static method <code>range(startInclusive, endExclusive)</code> of <code>IntStream</code> class returns a sequential ordered of integer numbers from range of <b>startInclusive (inclusive)</b> to <b>endExclusive (exclusive)</b> by an incremental step of 1. Therefore <i>startInclusive</i> is inclusive initial value and <i>endInclusive</i> is exclusive upper bound.</p>
<p>All this is equivalent of sequence increasing values sequentially using a for loop as follows: <code>for (int i = startInclusive; i < endInclusive ; i++) { ... }</code></p>
<p><b>Example code:</b></p>
<pre><code class="language-java">IntStream intStream = IntStream.range(1, 5);
intStream.forEach(i -> {
    System.out.print(i + " ");
});</code></pre>
<p><b>Example output:</b></p>
<pre><code class="language-bash">1 2 3 4 </code></pre>
<h2>Example of IntStream rangeClosed() method</h2>
<p>Static method <code>rangeClosed(startInclusive, endInclusive)</code> of <code>IntStream</code> class returns a sequential ordered of integer numbers from range of <b>startInclusive (inclusive)</b> to <b>endInclusive (inclusive)</b> by an incremental step of 1. Therefore <i>startInclusive</i> is inclusive initial value and <i>endInclusive</i> is inclusive upper bound.</p>
<p>All this is equivalent of sequence increasing values sequentially using a for loop as follows: <code>for (int i = startInclusive; i <= endInclusive ; i++) { ... }</code></p>
<p><b>Example code:</b></p>
<pre><code class="language-java">IntStream intStream = IntStream.rangeClosed(1, 5);
intStream.forEach(i -> {
    System.out.print(i + ", ");
});</code></pre>
<p><b>Example output:</b></p>
<pre><code class="language-bash">1 2 3 4 5</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-use-intstream-range-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
