<?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>JavaBeat</title>
	<atom:link href="https://javabeat.net/feed/" rel="self" type="application/rss+xml" />
	<link>https://javabeat.net/</link>
	<description>Java Tutorial Blog</description>
	<lastBuildDate>Wed, 25 Jun 2025 18:13:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>How to Initialize an Array in Java</title>
		<link>https://javabeat.net/initialize-array-java/</link>
		
		<dc:creator><![CDATA[Anees Asghar]]></dc:creator>
		<pubDate>Wed, 25 Jun 2025 18:12:46 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://javabeat.net/?p=188598</guid>

					<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>
<p>To initialize an array in Java, use square brackets, curly braces, or the built-in methods of the IntStream interface like range(), rangeClosed(), and of(). </p>
]]></description>
										<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>

<p>An array in Java is a collection of elements having the same data type and occupying contiguous memory locations. An array in Java can be declared similar to a variable, but with a couple of square brackets “dataType[] arrayName”. Once an array is declared, we can initialize it using different methods.&nbsp;</p>



<p>In Java, arrays are indexed with a numeric value, by default, starting from 0, the second element stored at the 1st index, and so on. These index numbers can be used to access the elements of an array.&nbsp;</p>



<p>In this write-up, we’ll show you how to initialize an array in Java using square brackets, curly braces, and the Stream interface methods.</p>



<h2 class="wp-block-heading">How to Initialize an Array in Java Using Square Brackets []</h2>



<p>In Java, we can initialize an array with square brackets, as shown in the following syntax:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
dataType &#x5B;] arrayName = new dataType &#x5B;arraySize];
</pre></div>


<p>By default, this syntax will create an array of the specified length and initialize it with the default value. The default values depend on the specified data type, as illustrated in the following table:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><tbody><tr><td><strong>Data Type&nbsp;</strong></td><td><strong>Default Value</strong></td></tr><tr><td>Integer</td><td>0</td></tr><tr><td>Float</td><td>0.0</td></tr><tr><td>Double</td><td>0.0</td></tr><tr><td>Byte&nbsp;</td><td>0</td></tr><tr><td>Short</td><td>0</td></tr><tr><td>Long</td><td>0</td></tr><tr><td>Boolean</td><td>False</td></tr><tr><td>Char</td><td>‘\u0000′ (i.e., Null)</td></tr><tr><td>Object</td><td>Null&nbsp;</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">Example 1: Initializing an Array With Default Values</h3>



<p>In this code, we create arrays of different data types and initialize them with their respective default values:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class InitializeArrays {
    public static void main(String&#x5B;] args) {
Integer &#x5B;] intArray = new Integer &#x5B;3];
Boolean &#x5B;] boolArray = new Boolean &#x5B;2];
String &#x5B;] strArray = new String &#x5B;3];
  }
}
</pre></div>


<p>In this code, we create three arrays of type Integer, Boolean, and String, respectively. Each array will be initialized according to the specified data type and array length, like this:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
&#x5B;0, 0, 0] //output of intArray
&#x5B;false, false] //output of boolArray
&#x5B;null, null, null] //Output of strArray
</pre></div>


<h3 class="wp-block-heading">Example 2: Initializing an Array With Specific Values</h3>



<p>We can use the square bracket syntax to initialize an array with specific values. To do that, we need to initialize each array index one by one. This approach works fine if the array size is small; however, this approach is not recommended for large arrays. Let’s learn how this approach works in Java:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class InitializeArrays {
  public static void main(String&#x5B;] args) {
      Integer &#x5B;] intArray = new Integer &#x5B;3];      String &#x5B;] strArray = new String &#x5B;2]; intArray&#x5B;0] = -1;
intArray&#x5B;1] = 3;
intArray&#x5B;2] = 2;
System.out.println(&quot;The Elements of intArray: &quot;);
  for(int i=0; i&lt;intArray.length; i++)
  {
    System.out.println(intArray&#x5B;i]);
  }
strArray&#x5B;0] = &quot;hi&quot;;
strArray&#x5B;1] = &quot;hello&quot;;
System.out.println(&quot;The Elements of strArray: &quot;);
  for(int j=0; j&lt;strArray.length; j++)
    {
System.out.println(strArray&#x5B;j]);
    }
}
}
</pre></div>


<p>In this code,</p>



<ul class="wp-block-list">
<li>First, we create an integer array of size 3 and a string array of size 2 using the square bracket syntax. </li>



<li>After this, we initialize both arrays by specifying the respective array indexes in the square brackets.</li>



<li>In the end, we employ the for loop to iterate and print elements of each array.</li>
</ul>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="735" height="205" src="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-1.png" alt="" class="wp-image-188604" srcset="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-1.png 735w, https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-1-300x84.png 300w" sizes="(max-width: 735px) 100vw, 735px" /></figure>



<h3 class="wp-block-heading">Example 3: How to Initialize an Array in Java Using a Loop</h3>



<p>We can create an array of a specific size in Java and initialize it using a loop, as shown below:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class InitializeArrays {
  public static void main(String&#x5B;] args) {
Integer&#x5B;] intArray = new Integer&#x5B;4];
for (int i =0; i&lt; intArray.length; i++)
{
        intArray&#x5B;i] = i-3;
}
System.out.println(&quot;Array Elements: &quot;);
for (int i = 0; i &lt; intArray.length; i++) {
  System.out.println(intArray&#x5B;i]);
}
  }
}
</pre></div>


<p>In this code, we create an integer array of size 4 and initialize it using a for loop. The array will be initialized with the following values:</p>



<figure class="wp-block-image size-full"><img decoding="async" width="747" height="181" src="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-2.png" alt="" class="wp-image-188603" srcset="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-2.png 747w, https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-2-300x73.png 300w" sizes="(max-width: 747px) 100vw, 747px" /></figure>



<h2 class="wp-block-heading">How to Initialize an Array in Java Using Curly Braces</h2>



<p>We can use the curly braces syntax to create and initialize an array in one step. For this purpose, use the curly braces with the comma-separated syntax to specify the array values, as shown below:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
datType&#x5B;] arrName  = {val1, val2, val3, ...};
</pre></div>


<p>Here,&nbsp;</p>



<ul class="wp-block-list">
<li>datType indicates the array’s type.</li>



<li>arrName shows the array’s name</li>



<li>“val1, val2, val3, …” represents the array elements/values. </li>
</ul>



<h3 class="wp-block-heading">Example: Creating and Initializing an Array Using the Curly Braces</h3>



<p>Let’s learn how to create an array of any specific data type and initialize it using the curly braces syntax:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class InitializeArrays {
  public static void main(String&#x5B;] args) {
String&#x5B;] strArray = { &quot;Hi&quot;, &quot;Hello&quot;, &quot;Welcome&quot; };
int&#x5B;] intArray = { 100, -10, 50, 101, 256 };
boolean&#x5B;] boolArray = { true, false, true, true };

System.out.println(&quot;The Elements of strArray: &quot;);
for (int j = 0; j &lt; strArray.length; j++) {
System.out.println(strArray&#x5B;j]);
}

System.out.println(&quot;The Elements of intArray: &quot;);
for (int i = 0; i &lt; intArray.length; i++) {
System.out.println(intArray&#x5B;i]);
}

System.out.println(&quot;The Elements of boolArray: &quot;);
for (int i = 0; i &lt; boolArray.length; i++) {
System.out.println(boolArray&#x5B;i]);
}
  }
}
</pre></div>


<p>In this code,&nbsp;</p>



<ul class="wp-block-list">
<li>We create and initialize a String, an integer, and a boolean array.</li>



<li>To confirm the arrays’ data, we iterate each array using a for loop and print their elements using the println() method.</li>
</ul>



<p><strong>Output</strong></p>



<figure class="wp-block-image size-full"><img decoding="async" width="733" height="355" src="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-3.png" alt="" class="wp-image-188602" srcset="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-3.png 733w, https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-3-300x145.png 300w" sizes="(max-width: 733px) 100vw, 733px" /></figure>



<h2 class="wp-block-heading">How to Initialize an Array in Java Using Stream Interface&nbsp;</h2>



<p>We can initialize an array using a stream interface that generates a stream of values and then converts it into an array. For this purpose, we can utilize one of the below-listed methods:</p>



<ul class="wp-block-list">
<li>Method 1: IntStream.range()</li>



<li>Method 2: IntStream.rangeClosed()</li>



<li>Method 3: IntStream.of()</li>
</ul>



<h3 class="wp-block-heading">Method 1: Initializing an Array Using the IntStream.range()</h3>



<p>We can use the range() method of the IntStream interface with the toArray() method to initialize an array of integers between the specified range. The range() method generates a stream of integers between the specified range, while the toArray() method converts this stream into an array:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.stream.IntStream;
public class InitializeArrays {
public static void main(String&#x5B;] args) {
int&#x5B;] intArray = IntStream.range(2, 7).toArray();
System.out.println(&quot;Array Elements: &quot;);
for (int i = 0; i &lt; intArray.length; i++) {
System.out.println(intArray&#x5B;i]);
}
  }
}
</pre></div>


<p>In this example,&nbsp;</p>



<ul class="wp-block-list">
<li>We import the IntStream interface from the “java.util.stream” package. </li>



<li>Next, we use the “IntStream.range()” method with the “toArray()” method to initialize an array between the integers 2 (inclusive) and 7(exclusive). </li>



<li>After this, we utilize a Java for loop to iterate and display each array element in the output.</li>
</ul>



<figure class="wp-block-image size-full"><img decoding="async" width="730" height="186" src="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-4.png" alt="" class="wp-image-188601" srcset="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-4.png 730w, https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-4-300x76.png 300w" sizes="(max-width: 730px) 100vw, 730px" /></figure>



<h3 class="wp-block-heading">Method 2: Initializing an Array Using the IntStream.rangeClosed()</h3>



<p>The rangeClosed() method works similarly to the range() method; the only difference is that it also includes the ending range:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.stream.IntStream;

public class InitializeArrays {
    public static void main(String&#x5B;] args) {
int&#x5B;] intArray = IntStream.rangeClosed(2, 7).toArray();
System.out.println(&quot;Array Elements: &quot;);
for (int i = 0; i &lt; intArray.length; i++) {
System.out.println(intArray&#x5B;i]);
}
  }
}
</pre></div>


<p>In this code, we replace the range() method with the rangeClosed() method; other than this, all the code remains the same as in the previous example:</p>



<figure class="wp-block-image size-full"><img decoding="async" width="735" height="188" src="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-5.png" alt="" class="wp-image-188600" srcset="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-5.png 735w, https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-5-300x77.png 300w" sizes="(max-width: 735px) 100vw, 735px" /></figure>



<p>The output shows that the last element of the specified range is also included in the array.</p>



<h3 class="wp-block-heading">Method 3: Initializing an Array Using the IntStream.of()</h3>



<p>The of() method of the IntStream interface lets us initialize an array with the values of our choice, as shown below:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.stream.IntStream;

public class InitializeArrays {
    public static void main(String&#x5B;] args) {
int&#x5B;] intArray = IntStream.of(12, 14, 17, 5, 1, -1).toArray();
System.out.println(&quot;Array Elements: &quot;);
  for (int i = 0; i &lt; intArray.length; i++) {
System.out.println(intArray&#x5B;i]);
  }
}
}
</pre></div>


<p>In this code, we use the of() method of the IntStream interface to initialize an array with six integers:</p>



<figure class="wp-block-image size-full"><img decoding="async" width="708" height="192" src="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-6.png" alt="" class="wp-image-188599" srcset="https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-6.png 708w, https://javabeat.net/wp-content/uploads/2025/06/How-to-Initialize-an-Array-in-Java-6-300x81.png 300w" sizes="(max-width: 708px) 100vw, 708px" /></figure>



<p>That’s all about initializing an array in Java.</p>



<h2 class="wp-block-heading">Final Thoughts</h2>



<p>In Java, arrays let us keep/store multiple values of the same data type in one variable (instead of creating separate variables for each value). We can initialize the arrays using square brackets “[]”, curly braces “{}”, or Stream Interface methods. Using square brackets, we can initialize the arrays with the default or specific values. Using curly braces syntax, we can create and initialize an array in a single line. Likewise, we can use the stream interface methods to initialize an array with specific values or within the specified range.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Java Scanner Class &#124; How to Import and Use it in Java</title>
		<link>https://javabeat.net/java-scanner-class-how-to-import-and-use-it-in-java/</link>
		
		<dc:creator><![CDATA[Anees Asghar]]></dc:creator>
		<pubDate>Sat, 21 Jun 2025 17:26:52 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://javabeat.net/?p=188593</guid>

					<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>
<p>Scanner is one of the built-in Java classes that is used to interact with the users. It belongs to the “java.util” package. Using this class, we can get the input of string-type or primitive types like “int”, “float”, etc. The Scanner class is the simplest way of getting user input; however, it&#8217;s not the best &#8230;</p>
]]></description>
										<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>

<p>Scanner is one of the built-in Java classes that is used to interact with the users. It belongs to the “java.util” package. Using this class, we can get the input of string-type or primitive types like “int”, “float”, etc. The Scanner class is the simplest way of getting user input; however, it&#8217;s not the best choice where time is a constraint.&nbsp;</p>



<p>Let’s learn how to import and use the Scanner class in Java using suitable examples.</p>



<h2 class="wp-block-heading">Java Scanner Class</h2>



<p>The Java Scanner Class lets us read data of various types and from different sources like strings, files, streams, etc. For this purpose, it offers different constructors and methods, which will be explained in the upcoming sections.</p>



<h3 class="wp-block-heading">1) Scanner Class Constructors</h3>



<p>The Scanner class supports several constructors, which are shown in the following table along with the description:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><tbody><tr><td><strong>Constructor</strong></td><td><strong>Description</strong></td></tr><tr><td>Scanner(File sourceFile);</td><td>It creates a new Scanner object that reads input from the specified file.</td></tr><tr><td>Scanner(File sourceFile, String charsetName);</td><td>It creates a new Scanner object that reads/scans input from the selected file using the provided character encoding.</td></tr><tr><td>Scanner(InputStream source);</td><td>It is used to read input from the given InputStream.</td></tr><tr><td>Scanner(InputStream source, String charsetName);</td><td>It creates a new Scanner object that reads input from the specified InputStream using the provided character encoding.</td></tr><tr><td>Scanner(Readable src);</td><td>It constructs a new scanner object that reads input from the specified readable source.</td></tr><tr><td>Scanner(String src);</td><td>It creates a new scanner object that scans/reads the given string/text.</td></tr><tr><td>Scanner(ReadableByteChannel src);</td><td>It constructs a new scanner object that scans input from the specified ReadableByteChannel source.&nbsp;</td></tr><tr><td>Scanner(ReadableByteChannel src, String charsetName);</td><td>Creates a new scanner object that scans input from the specified ReadableByteChannel source and decodes the bytes via the specified charset.</td></tr><tr><td>Scanner(Path src);</td><td>It constructs a new Scanner object that scans input from the specified file, indicated by the Path object.</td></tr><tr><td>Scanner(Path src, String charsetName);</td><td>It creates a new Scanner object that reads input from the file or path specified by the Path object and uses the specified character set to decode the bytes from the input stream into characters.</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">2) Scanner Class Methods</h3>



<p>The Java Scanner class offers numerous built-in methods to execute different tasks. The functionality of each method is illustrated in the following table:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><tbody><tr><td><strong>Query</strong></td><td><strong>Answer</strong></td></tr><tr><td>How to Close a Scanner in Java?</td><td>Use the close() method.</td></tr><tr><td>How to Reset a Scanner in Java?</td><td>Use the reset() method.</td></tr><tr><td>How to Get String Representation of a Scanner in Java?</td><td>Invoke the toString() method.</td></tr><tr><td>How to Read a Boolean Value in Java?</td><td>Use the nextBoolean() method.</td></tr><tr><td>How to Read a Double Value in Java?</td><td>Use the nextDouble() method.</td></tr><tr><td>How to Read a Float Value in Java?</td><td>Invoke the nextFloat() method.</td></tr><tr><td>How to Read an Integer Value in Java?</td><td>Use the nextInt() method.</td></tr><tr><td>How to Read a Byte Value in Java?</td><td>Use the nextByte() method.</td></tr><tr><td>How to Read a Short Value in Java?</td><td>Use the nextShort() method.</td></tr><tr><td>How to Read a Long Value in Java?</td><td>Use the nextLong() method.</td></tr><tr><td>How to Read a Line in Java?</td><td>Use the nextLine() method.</td></tr><tr><td>How to Set the Scanner’s Default Radix?</td><td>Use the useRadix() method.</td></tr><tr><td>How to Check/Find the Next Occurrence of a Specific Pattern/Input in Java?</td><td>Use the findInLine() method.</td></tr><tr><td>How to Check if There is Another Line in This Scanner&#8217;s Input?</td><td>Use the hasNextLine() method.</td></tr><tr><td>How to Check if the Next Token in a Java Scanner Object&#8217;s Input can be interpreted as a Specific Data Type?</td><td>Use the hasNextXYZ() method. Replace the XYZ with the desired data type, like int, float, long, etc. For example, the hasNextLong() method checks if the next token can be interpreted/read as a Long data type.</td></tr><tr><td>How to Check if there is Another Token in the Scanner?</td><td>Use the hasNext() method.</td></tr><tr><td>How to Get a Complete Next Token from this Scanner?</td><td>Use the next() method.</td></tr><tr><td>How to Scan/Read the Next Token of the Input as a Specific Type like int, boolean, byte, float, etc.</td><td>Use the nextXYZ() method. Replace XYZ with the desired data type. For instance, the nextByte() reads the subsequent input token as a byte.&nbsp;</td></tr><tr><td>How to Skip an Input that Matches the Given Pattern?</td><td>Use the skip() method.&nbsp;</td></tr><tr><td>How to Set this Scanner&#8217;s Delimiting Pattern in Java?</td><td>Use the useDelimiter() method to specify this Scanner’s delimiting pattern.</td></tr><tr><td>How to Get the Current Delimiting Pattern of this Scanner?</td><td>Invoke the delimiter() method to retrieve the current delimiting pattern.</td></tr><tr><td>How to Get the Matching Result of the Last Scanning Operation?</td><td>Use the match() method.</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">What is a System.in in Java</h2>



<p>The “System.in” is an input stream object that is used to get the user&#8217;s input via the keyboard.</p>



<h2 class="wp-block-heading">How to Import Scanner Class in Java</h2>



<p>To use the Scanner class in Java, first, we need to import it into our program. For this purpose, copy and paste the below line of code at the start of your program:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.Scanner;
</pre></div>


<p><strong>Note: </strong>To learn more methods of importing the Scanner class in Java, read our dedicated guide titled “<a href="https://javabeat.net/import-scanner-class-java/">How to Import Scanner in Java</a>”.</p>



<h2 class="wp-block-heading">How to Get User Input Using Java Scanner Class</h2>



<p>Java offers different methods to get the user&#8217;s input. Each method accepts a specific type of input from the user, as discussed in the above table. In the example below, we’ll show you how to interpret various types of data from the user:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.Scanner;
public class ScannerExamples {

  public static void main(String&#x5B;] args) {
Scanner scanInput = new Scanner(System.in);
System.out.println(&quot;Please Enter Your Name: &quot;);
String userName = scanInput.nextLine();

System.out.println(&quot;Enter Your ID: &quot;);
Integer userID = scanInput.nextInt();

System.out.println(&quot;Enter Your Expected Salary: &quot;);
Double userSal = scanInput.nextDouble();

System.out.println(&quot;Are You Above 25: &quot;);
Boolean isEligible = scanInput.nextBoolean();

System.out.println(&quot;Your Name is: &quot; + userName);
System.out.println(&quot;Your ID: &quot; + userID);
System.out.println(&quot;Your Salary: &quot; + userSal);
System.out.println(&quot;Are You Above 25: &quot; + isEligible);

scanInput.close();
}
}
</pre></div>


<p><strong>Code Explanation:</strong></p>



<ul class="wp-block-list">
<li>First, we import the Scanner class to use its methods in our code.</li>



<li>We create an object of the Java Scanner class named “scanInput”. After this, we pass the input stream to the Scanner() constructor to get the user’s input.</li>



<li>Next, we use the “nextLine()”, “nextInt()”, “nextDouble()”, and “nextBoolean()” methods to read a string, an integer, a double, and a boolean value from the user, respectively.</li>



<li>Finally, we print each user-entered value using the println() method.</li>
</ul>



<p><strong>Output:</strong></p>



<figure class="wp-block-image size-full"><img decoding="async" width="735" height="315" src="https://javabeat.net/wp-content/uploads/2025/06/Java-Scanner-Class-How-to-Import-and-Use-it-in-Java-1.png" alt="" class="wp-image-188596" srcset="https://javabeat.net/wp-content/uploads/2025/06/Java-Scanner-Class-How-to-Import-and-Use-it-in-Java-1.png 735w, https://javabeat.net/wp-content/uploads/2025/06/Java-Scanner-Class-How-to-Import-and-Use-it-in-Java-1-300x129.png 300w" sizes="(max-width: 735px) 100vw, 735px" /></figure>



<h2 class="wp-block-heading">How to Check if a Java Scanner Has a Token</h2>



<p>In the below code, we have two strings, inputString1, and inputString2. We create a couple of scanner objects and pass the given strings to the respective Scanner constructors, as shown below:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.Scanner;

public class ScannerExamples {
    public static void main(String&#x5B;] args) {
String inputString1 = &quot;Hello! Let&#039;s Learn Java Programming&quot;;
String inputString2 = &quot;&quot;;

Scanner scanInput1 = new Scanner(inputString1);
Scanner scanInput2 = new Scanner(inputString2);

System.out.println(&quot;Scanner1 Has a String Token? &quot; + scanInput1.hasNext());
System.out.println(&quot;Scanner1 Has an Integer Token? &quot; + scanInput1.hasNextInt());
System.out.println(&quot;Scanner1 Has a Boolean Token? &quot; + scanInput1.hasNextBoolean());
System.out.println(&quot;Scanner2 Has a Token? &quot; + scanInput2.hasNext());

scanInput1.close();
scanInput2.close();
}
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>We use the hasNext() method to check if the scanner “scanInput1” has a string token and prints its resultant value on the console.</li>



<li>Also, we invoke the hasNextInt() and hasNextBoolean() methods on the “scanInput” scanner to check if it has an integer and a boolean token.</li>



<li>Finally, we use the hasNext() method on the “scanInput2” scanner to check if it has a string token.</li>
</ul>



<p><strong>Output:</strong></p>



<figure class="wp-block-image size-full"><img decoding="async" width="734" height="163" src="https://javabeat.net/wp-content/uploads/2025/06/Java-Scanner-Class-How-to-Import-and-Use-it-in-Java-2.png" alt="" class="wp-image-188595" srcset="https://javabeat.net/wp-content/uploads/2025/06/Java-Scanner-Class-How-to-Import-and-Use-it-in-Java-2.png 734w, https://javabeat.net/wp-content/uploads/2025/06/Java-Scanner-Class-How-to-Import-and-Use-it-in-Java-2-300x67.png 300w" sizes="(max-width: 734px) 100vw, 734px" /></figure>



<p><strong>Note: </strong>By default, the delimiter of this scanner is whitespace; however, we can set it according to our preferences using the useDelimiter() method.&nbsp;</p>



<h2 class="wp-block-heading">How to Parse an Input in Java Using Scanner Class</h2>



<p>We can parse an input in Java using the Scanner class’s useDelimiter() method. Here’s a simple example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.Scanner;
public class ScannerExamples {
    public static void main(String&#x5B;] args) {
String inputString1 = &quot;Hello-Let&#039;s-Learn-Java-Programming&quot;;
Scanner scanInput1 = new Scanner(inputString1);
scanInput1.useDelimiter(&quot;-&quot;);

System.out.println(&quot;The Parsed Input is ==&gt; &quot;);
  while (scanInput1.hasNext()){
        System.out.println(scanInput1.next());
  }
scanInput1.close();
}
}
</pre></div>


<p><strong>Code Explanation:</strong></p>



<ul class="wp-block-list">
<li>We create a string “Hello-Let&#8217;s-Learn-Java-Programming” and initialize it to the “inputString1” variable.</li>



<li>We invoke the Scanner() constructor to create a scanner object and pass the input string to it.</li>



<li>Next, we use the “useDelimiter()” method to specify the delimiting pattern (the input string will be parsed accordingly).</li>



<li>After this, we use the while loop that keeps iterating until the scanner has a token. </li>



<li>Within the while loop, we use the next() method within the println() method to read a word from the input string and print it on the console.</li>
</ul>



<p>This way the entire string will be parsed, and the final output will be something like this:</p>



<figure class="wp-block-image size-full"><img decoding="async" width="734" height="181" src="https://javabeat.net/wp-content/uploads/2025/06/Java-Scanner-Class-How-to-Import-and-Use-it-in-Java-3.png" alt="" class="wp-image-188594" srcset="https://javabeat.net/wp-content/uploads/2025/06/Java-Scanner-Class-How-to-Import-and-Use-it-in-Java-3.png 734w, https://javabeat.net/wp-content/uploads/2025/06/Java-Scanner-Class-How-to-Import-and-Use-it-in-Java-3-300x74.png 300w" sizes="(max-width: 734px) 100vw, 734px" /></figure>



<p>That’s all about the Java Scanner Class.</p>



<h2 class="wp-block-heading">Final Thoughts</h2>



<p>Scanner is one of the most widely used built-in Java classes that lets us get the user input of primitive types, like int, float, double, etc., and strings. We can import this class from the “java.util” package and then create its object using the Scanner constructor. We can use this object to invoke any of its methods to perform a specific task.&nbsp;</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Install Java on Ubuntu 24.04</title>
		<link>https://javabeat.net/install-java-ubuntu-24-04/</link>
		
		<dc:creator><![CDATA[Anees Asghar]]></dc:creator>
		<pubDate>Tue, 30 Apr 2024 17:30:17 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://javabeat.net/?p=188232</guid>

					<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>
<p>Java is a versatile programming language that can be installed on Ubuntu 24.04 using different methods, such as “apt”, “deb”, or “SDKMAN”. </p>
]]></description>
										<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>

<p>Java is an open-source globally known programming language used to develop web applications, mobile apps, game development, etc. Java is famous for its robust features like object-oriented, security, scalability, etc. One of the well-known features of Java is its multi-platform compatibility. This means we can install and use Java programming language on any platform like Linux, Windows, Mac, etc.</p>



<p>Ubuntu 24.04, codenamed &#8220;Noble Numbat&#8221;, is the latest LTS release and is available for download on <a href="https://ubuntu.com/download/desktop">Ubuntu&#8217;s official page</a>. We can install Java on Ubuntu 24.04 and benefit from its latest features. For this purpose, we can use different package managers like apt, SDKMAN, etc.</p>



<h2 class="wp-block-heading">How to Install Java on Ubuntu 24.04</h2>



<p>To install Java on Ubuntu 24.04, we can use the “<strong>Apt</strong>” package manager, “<strong>Deb</strong>” package, or “<strong>SDKMAN</strong>”. Let’s start with the apt package manager.</p>



<h3 class="wp-block-heading">Method 1: Installing Java on Ubuntu 24.04 Using Apt</h3>



<p>apt is a well-known command-line tool that can be used to install the default or any specific Java version. This can be done by installing JDK or JRE. The JRE package installs only the components needed to run Java programs, while the JDK package enables both running and developing Java programs. Therefore, it is recommended to install JDK instead of JRE on Ubuntu.&nbsp;</p>



<p>Follow the given stepwise instructions to install Java on Ubuntu 24.04 using Apt.</p>



<p><strong>Step 1: Update and Upgrade System Repositories</strong></p>



<p>Before installing Java, first, execute the provided command to update and upgrade the repository:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sudo apt update &amp;amp;&amp;amp; sudo apt upgrade -y
</pre></div>


<figure class="wp-block-image size-full"><img decoding="async" width="894" height="246" src="http://javabeat.net/wp-content/uploads/2024/04/image-59.png" alt="" class="wp-image-188234" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-59.png 894w, https://javabeat.net/wp-content/uploads/2024/04/image-59-300x83.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-59-768x211.png 768w" sizes="(max-width: 894px) 100vw, 894px" /></figure>



<p>Once the system repositories are updated and upgraded, we can proceed to the next step.</p>



<p><strong>Step 2: Check Available Java Versions</strong></p>



<p>To check all available Java versions, execute the following command:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
javac --version
</pre></div>


<p>The output snippet shows that Java isn’t yet installed on our machine, but it shows several versions that we can install on Ubuntu 24.04:</p>



<figure class="wp-block-image size-full"><img decoding="async" width="890" height="329" src="http://javabeat.net/wp-content/uploads/2024/04/image-60.png" alt="" class="wp-image-188235" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-60.png 890w, https://javabeat.net/wp-content/uploads/2024/04/image-60-300x111.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-60-768x284.png 768w" sizes="(max-width: 890px) 100vw, 890px" /></figure>



<p>You can pick the desired Java version and execute the corresponding command to install it on your system.</p>



<p><strong>Step 3: Install Java Using Apt</strong></p>



<p>From the available Java versions, select the desired one, and execute the below-given command to install it on Ubuntu 24.04:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sudo apt install default-jdk -y
</pre></div>


<p>On successful execution of this command, the default jdk will be installed on Ubuntu, as shown in the following screenshot.&nbsp;</p>



<figure class="wp-block-image size-full"><img decoding="async" width="904" height="533" src="http://javabeat.net/wp-content/uploads/2024/04/image-61.png" alt="" class="wp-image-188236" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-61.png 904w, https://javabeat.net/wp-content/uploads/2024/04/image-61-300x177.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-61-768x453.png 768w" sizes="(max-width: 904px) 100vw, 904px" /></figure>



<p>If you want to install any specific Java version, replace “default-jdk” with the specific version(that you want to install), like this:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sudo apt install java_version
</pre></div>


<p><strong>Step 4: Verify Java Installation</strong></p>



<p>To confirm Java’s installation on Ubuntu 24.04, run the following command that retrieves the currently installed Java version:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
java --version
</pre></div>


<p>The output confirms the successful installation of “openjdk 21.0.3” on our Ubuntu 24.04 machine:</p>



<figure class="wp-block-image size-full"><img decoding="async" width="815" height="113" src="http://javabeat.net/wp-content/uploads/2024/04/image-62.png" alt="" class="wp-image-188237" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-62.png 815w, https://javabeat.net/wp-content/uploads/2024/04/image-62-300x42.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-62-768x106.png 768w" sizes="(max-width: 815px) 100vw, 815px" /></figure>



<h3 class="wp-block-heading">Method 2: Installing Java on Ubuntu 24.04 Using Deb</h3>



<p>We can download the Java deb package using wget command and install it using the apt command. For better understanding, walk through the below-given stepwise instructions:</p>



<p><strong>Step 1: Download Deb Package</strong></p>



<p>The wget is a command line utility that lets us download files from the web. Execute the below-given “wget” command to download the Java deb package from Oracle&#8217;s official page:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sudo wget https://download.oracle.com/java/21/latest/jdk-21_linux-x64_bin.deb
</pre></div>


<figure class="wp-block-image size-full"><img decoding="async" width="895" height="292" src="http://javabeat.net/wp-content/uploads/2024/04/image-63.png" alt="" class="wp-image-188238" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-63.png 895w, https://javabeat.net/wp-content/uploads/2024/04/image-63-300x98.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-63-768x251.png 768w" sizes="(max-width: 895px) 100vw, 895px" /></figure>



<p><strong>Step 2: Install Java Using Deb</strong></p>



<p>Now execute the following command to install Java from the deb package:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sudo apt install ./jdk-21_linux-x64_bin.deb
</pre></div>


<figure class="wp-block-image size-full"><img decoding="async" width="867" height="318" src="http://javabeat.net/wp-content/uploads/2024/04/image-64.png" alt="" class="wp-image-188239" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-64.png 867w, https://javabeat.net/wp-content/uploads/2024/04/image-64-300x110.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-64-768x282.png 768w" sizes="(max-width: 867px) 100vw, 867px" /></figure>



<p><strong>Step 3: Confirm Java Installation</strong></p>



<p>Finally, we can run the given command to verify the Java’s installation on Ubuntu 24.04:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
java --version
</pre></div>


<figure class="wp-block-image size-full"><img decoding="async" width="862" height="117" src="http://javabeat.net/wp-content/uploads/2024/04/image-65.png" alt="" class="wp-image-188240" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-65.png 862w, https://javabeat.net/wp-content/uploads/2024/04/image-65-300x41.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-65-768x104.png 768w" sizes="(max-width: 862px) 100vw, 862px" /></figure>



<h3 class="wp-block-heading">Method 3: Installing Java on Ubuntu 24.04 Using SDKMAN</h3>



<p>SDKMAN is a command-line utility tool that allows us to install and manage multiple versions of software development kits (SDKs) on a system. We can use it to install different versions of Java JDK and switch between them.</p>



<p>To install Java on Ubuntu 24.04 using SDKMAN, follow the steps below:</p>



<p><strong>Step 1: Install Dependencies for SDKMAN</strong></p>



<p>First, execute the given command to install the essential dependencies for SDKMAN:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sudo apt install curl zip -y
</pre></div>


<figure class="wp-block-image size-full"><img decoding="async" width="893" height="394" src="http://javabeat.net/wp-content/uploads/2024/04/image-66.png" alt="" class="wp-image-188241" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-66.png 893w, https://javabeat.net/wp-content/uploads/2024/04/image-66-300x132.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-66-768x339.png 768w" sizes="(max-width: 893px) 100vw, 893px" /></figure>



<p><strong>Step 2: Run the SDKMAN Script</strong></p>



<p>After installing the required dependencies, we can run the below-provided command to download and execute the SDKMAN script on our Ubuntu 24.04:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
curl -s &quot;https://get.sdkman.io&quot; | bash
</pre></div>


<p>This command uses curl to download the SDKMAN script from the URL &#8220;get.sdkman.io&#8221;, and then pipes it to bash to execute it. On successful execution, the following output appears on the screen:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="390" src="http://javabeat.net/wp-content/uploads/2024/04/image-67-1024x390.png" alt="" class="wp-image-188242" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-67-1024x390.png 1024w, https://javabeat.net/wp-content/uploads/2024/04/image-67-300x114.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-67-768x292.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Now execute the given “source” command to save the changes:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
source &quot;/home/linuxuser/.sdkman/bin/sdkman-init.sh&quot;
</pre></div>


<figure class="wp-block-image size-full"><img decoding="async" width="796" height="74" src="http://javabeat.net/wp-content/uploads/2024/04/image-68.png" alt="" class="wp-image-188243" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-68.png 796w, https://javabeat.net/wp-content/uploads/2024/04/image-68-300x28.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-68-768x71.png 768w" sizes="(max-width: 796px) 100vw, 796px" /></figure>



<p><strong>Step 3: Confirm the Installation of SDKMAN</strong></p>



<p>You can confirm the SDKMAN installation using the following command:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sdk version
</pre></div>


<figure class="wp-block-image size-full"><img decoding="async" width="804" height="159" src="http://javabeat.net/wp-content/uploads/2024/04/image-69.png" alt="" class="wp-image-188244" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-69.png 804w, https://javabeat.net/wp-content/uploads/2024/04/image-69-300x59.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-69-768x152.png 768w, https://javabeat.net/wp-content/uploads/2024/04/image-69-800x159.png 800w" sizes="(max-width: 804px) 100vw, 804px" /></figure>



<p><strong>Step 4: Check Available Java Versions</strong></p>



<p>Once SKD is successfully installed, use the given command to check the available Java versions (that can be installed using SDKMAN):</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sdk list java
</pre></div>


<figure class="wp-block-image size-full"><img decoding="async" width="898" height="577" src="http://javabeat.net/wp-content/uploads/2024/04/image-70.png" alt="" class="wp-image-188245" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-70.png 898w, https://javabeat.net/wp-content/uploads/2024/04/image-70-300x193.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-70-768x493.png 768w" sizes="(max-width: 898px) 100vw, 898px" /></figure>



<p>Choose the version that you want to install on your system and hit the q button to exit.</p>



<p><strong>Step 5: Install Java Using SDKMAN</strong></p>



<p>Now run the following sdk command to install Java on Ubuntu 24.04:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sdk install java identifier
</pre></div>


<p>Replace the “identifier” with a specific Java version like “17.0.11”, and run the command:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sdk install java 17.0.11-amzn
</pre></div>


<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="456" src="http://javabeat.net/wp-content/uploads/2024/04/image-71-1024x456.png" alt="" class="wp-image-188246" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-71-1024x456.png 1024w, https://javabeat.net/wp-content/uploads/2024/04/image-71-300x134.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-71-768x342.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong>Step 6: Verify Java Installation&nbsp;</strong></p>



<p>Finally, we can <a href="https://javabeat.net/check-java-version-windows-mac-linux/">check the installed Java version</a> to confirm the installation:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
java --version
</pre></div>


<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="146" src="http://javabeat.net/wp-content/uploads/2024/04/image-72-1024x146.png" alt="" class="wp-image-188247" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-72-1024x146.png 1024w, https://javabeat.net/wp-content/uploads/2024/04/image-72-300x43.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-72-768x110.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">Switching Default Java Version on Ubuntu 24.04</h2>



<p>If we’ve multiple Java versions installed on our system, we can switch between them by executing the following command:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sudo update-alternatives --config java
</pre></div>


<p>Press the “Enter” key to keep the default Java version or select the preferred Java version by specifying the corresponding selection number:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="362" src="http://javabeat.net/wp-content/uploads/2024/04/image-73-1024x362.png" alt="" class="wp-image-188248" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-73-1024x362.png 1024w, https://javabeat.net/wp-content/uploads/2024/04/image-73-300x106.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-73-768x272.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">Setting JAVA_HOME Environment Variable on Ubuntu 24.04</h2>



<p>To set the JAVA_HOME environment variable on Ubuntu, open the “/etc/environment” file in the nano editor by executing the below-given command:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sudo nano /etc/environment
</pre></div>


<p>Now specify the path of the selected Java version in the “/etc/environment” file to set the JAVA_HOME environment variable:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
JAVA_HOME=&quot;/usr/lib/jvm/java-21-openjdk-amd64/bin/java&quot;
</pre></div>


<p>Hit the “CTRL+S” and “CTRL+X” to save the changes and exit the nano editor:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="584" src="http://javabeat.net/wp-content/uploads/2024/04/image-74-1024x584.png" alt="" class="wp-image-188249" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-74-1024x584.png 1024w, https://javabeat.net/wp-content/uploads/2024/04/image-74-300x171.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-74-768x438.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Now execute the given command to reload the “/etc/environment” file and apply changes to the current session:&nbsp;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
source /etc/environment
</pre></div>


<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="132" src="http://javabeat.net/wp-content/uploads/2024/04/image-75-1024x132.png" alt="" class="wp-image-188250" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-75-1024x132.png 1024w, https://javabeat.net/wp-content/uploads/2024/04/image-75-300x39.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-75-768x99.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Now run the given command to ensure the JAVA_HOME is Set:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
echo $JAVA_HOME
</pre></div>


<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="107" src="http://javabeat.net/wp-content/uploads/2024/04/image-76-1024x107.png" alt="" class="wp-image-188251" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-76-1024x107.png 1024w, https://javabeat.net/wp-content/uploads/2024/04/image-76-300x31.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-76-768x80.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">How to Uninstall Java From Ubuntu 24.04</h2>



<p>If Java is no longer needed, we can uninstall/remove it to free up some space. However, uninstallation of Java depends on the installation method.</p>



<h3 class="wp-block-heading">Method 1: Uninstalling Java From Ubuntu 24.04 Using Apt</h3>



<p>If we install Java on our Ubuntu 24.04 using Apt, we can completely uninstall it using the following command:&nbsp;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sudo apt autoremove java* -y
</pre></div>


<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="382" src="http://javabeat.net/wp-content/uploads/2024/04/image-77-1024x382.png" alt="" class="wp-image-188252" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-77-1024x382.png 1024w, https://javabeat.net/wp-content/uploads/2024/04/image-77-300x112.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-77-768x286.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h3 class="wp-block-heading">Method 2: Uninstalling Java From Ubuntu 24.04 Using Deb</h3>



<p>If Java is installed on Ubuntu using the deb package, we can remove it from the system by executing the following command:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sudo apt autoremove jdk-21 -y
</pre></div>


<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="275" src="http://javabeat.net/wp-content/uploads/2024/04/image-78-1024x275.png" alt="" class="wp-image-188253" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-78-1024x275.png 1024w, https://javabeat.net/wp-content/uploads/2024/04/image-78-300x80.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-78-768x206.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h3 class="wp-block-heading">Method 3: Removing Java From Ubuntu Using SDKMAN</h3>



<p>Execute the below-given command to uninstall Java installed via SDKMAN on Ubuntu:&nbsp;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
sdk uninstall --force java 17.0.11-amzn
</pre></div>


<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="113" src="http://javabeat.net/wp-content/uploads/2024/04/image-79-1024x113.png" alt="" class="wp-image-188254" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-79-1024x113.png 1024w, https://javabeat.net/wp-content/uploads/2024/04/image-79-300x33.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-79-768x84.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>This sums up the installation and uninstallation of Java on Ubuntu 24.04.</p>



<h2 class="wp-block-heading">Final Thoughts</h2>



<p>Java is a versatile programming language that can be installed on Ubuntu 24.04 using “apt”, “deb”, or “SDKMAN”. All the mentioned methods let us install the latest version of Java on Ubuntu 24.04. However, each method has its pros and cons, you can choose an installation method according to your requirements. For instance, Java installation using apt and deb is faster and easier while SDKMAN helps us install multiple Java versions and switch between them.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Get a Current Timestamp in Java?</title>
		<link>https://javabeat.net/get-current-timestamp-in-java/</link>
		
		<dc:creator><![CDATA[Anees Asghar]]></dc:creator>
		<pubDate>Tue, 30 Apr 2024 13:55:42 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://javabeat.net/?p=188223</guid>

					<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>
<p>To get a current timestamp in Java, we can use methods like “System.currentTimeMillis()”, “Instant.now()”, “Date()” constructor, etc.</p>
]]></description>
										<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>

<p>When working with Java, obtaining the current timestamp is crucial for various tasks, such as event logging, managing date and time operations, etc. This can be done using different built-in Java methods, such as System.currentTimeMillis(), Instant.now(), Date() constructor, etc.&nbsp;</p>



<p>In this Java guide, you’ll learn six different approaches to get the current timestamp. Each approach will be discussed along with appropriate examples.</p>



<h2 class="wp-block-heading">How to Get Current Timestamp in Java</h2>



<p>A timestamp is an encoded DateTime format, which demonstrates the occurrence of an event. To get a current timestamp in Java, we can use the methods like “currentTimeMillis()”, “now()”, “Date()” constructor, etc.&nbsp;</p>



<h3 class="wp-block-heading">Method 1: Getting the Current Timestamp Using System.currentTimeMillis()</h3>



<p>The “currentTimeMillis()” is a built-in method of the <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/System.html">System</a> class that retrieves the number of milliseconds passed since 1970. These retrieved milliseconds represent the current Timestamp in Java. Here is a simple example that demonstrates the practical implementation of the stated method in Java:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CurrentTS {
  public static void main(String&#x5B;] args) {
//Getting the Current DateTime in Milliseconds
long currentTS = System.currentTimeMillis();
System.out.println(&quot;The Current Timestamp in Milliseconds == &quot; + currentTS);

//Converting Milliseconds to Human-readable Date Format
DateFormat formatedTS = new SimpleDateFormat(&quot;dd MMM yyyy HH:mm:ss:SSS Z&quot;);
Date resultantTS = new Date(currentTS);
System.out.println(&quot;The Formated Current Timestamp == &quot; + formatedTS.format(resultantTS));
}
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>First, we import the required classes like “DateFormat”, “SimpleDateFormat”, and “Date” from their respective packages.</li>



<li>In the main() method, we invoke the “currentTimeMillis()” method of the System class to get the current timestamp in milliseconds. We store the retrieved milliseconds in a long-type variable named “currentTS”.</li>



<li>In the next line, we use the println() method to print the current timestamp in milliseconds on the console.</li>



<li>After this, we use the <a href="https://javabeat.net/convert-date-dd-mm-yyyy-format-java/">SimpleDateFormat</a> class to convert the obtained current timestamp in milliseconds to a specific format.</li>



<li>Next, we invoke the Date() constructor and pass the currentTS to it as an argument. This will convert the milliseconds (long type) to a date instance.&nbsp;</li>



<li>Finally, we invoke the format() method on the current timestamp to convert it into a specific pattern/format.</li>
</ul>



<figure class="wp-block-image size-full"><img decoding="async" width="803" height="108" src="http://javabeat.net/wp-content/uploads/2024/04/image-58.png" alt="" class="wp-image-188229" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-58.png 803w, https://javabeat.net/wp-content/uploads/2024/04/image-58-300x40.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-58-768x103.png 768w, https://javabeat.net/wp-content/uploads/2024/04/image-58-800x108.png 800w" sizes="(max-width: 803px) 100vw, 803px" /></figure>



<h3 class="wp-block-heading">Method 2: Getting the Current Timestamp Using the Date Class</h3>



<p>We can invoke the constructor of the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Date.html">Date</a> class to get the current DateTime with millisecond precision, as shown in the following code:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
import java.util.Date;

public class CurrentTS {
    public static void main(String&#x5B;] args) {
//Getting the Current DateTime
Date currentTS = new Date();
System.out.println(&quot;The Current Timestamp == &quot; + currentTS);

//Converting Current Timestamp in Milliseconds
System.out.println(&quot;The Current Timestamp in Milliseconds == &quot; + currentTS.getTime());

}
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>First, we invoke the Date() constructor to get the current timestamp and println() method to print it on the console.</li>



<li>In the next line, we invoke the getTime() method on the currentTS instance to convert the current timestamp into milliseconds.</li>
</ul>



<figure class="wp-block-image size-full"><img decoding="async" width="729" height="101" src="http://javabeat.net/wp-content/uploads/2024/04/image-57.png" alt="" class="wp-image-188228" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-57.png 729w, https://javabeat.net/wp-content/uploads/2024/04/image-57-300x42.png 300w" sizes="(max-width: 729px) 100vw, 729px" /></figure>



<h3 class="wp-block-heading">Method 3: Getting the Current Timestamp in Java Using java.time.Instant</h3>



<p>Java introduces a new DateTime API in the time package (<a href="https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html">Instant</a>) that represents a specific instantaneous point on the timeline. This instantaneous point is independent of any specific timezone or calendar. Using the instant class we can store the DateTime values in UTC timezone as well. In the below code snippet, we use the Instant class to get the current timestamp:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
import java.time.*;

public class CurrentTS {
    public static void main(String&#x5B;] args) {
//Getting Current DateTime
Instant currentTS = Instant.now();
System.out.println(&quot;The Current Timestamp == &quot; + currentTS);

//Converting Current DateTime into Milliseconds
System.out.println(&quot;The Current Timestamp in Milliseconds == &quot; + currentTS.toEpochMilli());

}
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>First, we import the Instant class from the “time” package and then use it to invoke the now() method to get the current instant. We store the retrieved instant/timestamp in a variable named “currentTS”.</li>



<li>Next, we invoke the toEpochMilli() method on the currentTS to convert the current instant into milliseconds:</li>
</ul>



<figure class="wp-block-image size-full"><img decoding="async" width="729" height="111" src="http://javabeat.net/wp-content/uploads/2024/04/image-56.png" alt="" class="wp-image-188227" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-56.png 729w, https://javabeat.net/wp-content/uploads/2024/04/image-56-300x46.png 300w" sizes="(max-width: 729px) 100vw, 729px" /></figure>



<h3 class="wp-block-heading">Method 4: Getting the Current Timestamp in Java Using the Timestamp Class</h3>



<p><a href="https://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html">Timestamp</a> is an inbuilt Java class that belongs to the “java.sql” package. We can use the constructor of the stated class to get the current DateTime with millisecond precision, as demonstrated in the below example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
import java.sql.Timestamp;

public class CurrentTS {
    public static void main(String&#x5B;] args) {
Timestamp currentTS = new Timestamp(System.currentTimeMillis());
System.out.println(&quot;The Current Timestamp in Milliseconds == &quot; + currentTS.getTime());

//Formating the Current Timestamp
System.out.println(&quot;The Formatted Timestamp == &quot; + currentTS.toString())
}
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>At the start of the program, we import the Timestamp class from the sql package.</li>



<li>After this, we pass the “System.currentTimeMillis()” as an argument to the Timestamp() constructor and store the obtained result in the currentTS variable. Then we invoke the getTime() method on the currentTS to retrieve the current DateTime in milliseconds.</li>



<li>Finally, we use the currentTS with the toString() method to get and print the formatted timestamp on the console:</li>
</ul>



<figure class="wp-block-image size-full"><img decoding="async" width="734" height="102" src="http://javabeat.net/wp-content/uploads/2024/04/image-55.png" alt="" class="wp-image-188226" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-55.png 734w, https://javabeat.net/wp-content/uploads/2024/04/image-55-300x42.png 300w" sizes="(max-width: 734px) 100vw, 734px" /></figure>



<h3 class="wp-block-heading">Method 5: Getting the Current Timestamp in Java Using the LocalDateTime and DateTimeFormatter Classes</h3>



<p>We can also get the current timestamp using the now() method of the <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html">LocalDateTime</a> class. In addition to this, we can format the obtained current timestamp into a specific pattern using the DateTimeFormatter class. In the following example, first, we get the current timestamp and then we convert it into a specific pattern using the “DateTimeFormatter.ofPattern().format()” method:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CurrentTS {
public static void main(String&#x5B;] args) {
LocalDateTime currTS = LocalDateTime.now();
System.out.println(&quot;The Current Timestamp == &quot; + currTS);    

//Formatting Current TimeStamp
String formattedTS = DateTimeFormatter.ofPattern(&quot;yyyy/MM/dd - HH:mm:ss&quot;).format(currTS);
        System.out.println(&quot;The Formatted Timestamp == &quot; + formattedTS);
}
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>We import the LocalDateTime and DateTimeFormatter classes from the respective packages.</li>



<li>Next, we use the now() method to get the current/local DateTime.</li>



<li>After this, we format the obtained DateTime into a specific format using the “ofPattern().format()” method.</li>



<li>Finally, we print the obtained current timestamp and the formatted timestamp on the console.&nbsp;</li>
</ul>



<figure class="wp-block-image size-full"><img decoding="async" width="733" height="116" src="http://javabeat.net/wp-content/uploads/2024/04/image-54.png" alt="" class="wp-image-188225" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-54.png 733w, https://javabeat.net/wp-content/uploads/2024/04/image-54-300x47.png 300w" sizes="(max-width: 733px) 100vw, 733px" /></figure>



<h3 class="wp-block-heading">Method 6: Getting the Current Timestamp in Java Using the LocalDateTime and ZoneId Classes</h3>



<p>The LocalDateTime and <a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html">ZoneId</a> are built-in classes of the “java.time” package. The LocalDateTime class retrieves the DateTime without timezone information while the ZoneId retrieves the timezone id. We use these classes combined to get the current DateTime with timezone information. Here is an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
import java.time.*;
import java.time.format.DateTimeFormatter;

public class CurrentTS {
public static void main(String&#x5B;] args) {
LocalDateTime currDateTime = LocalDateTime.now();
      ZoneId id = ZoneId.systemDefault();
      ZonedDateTime dateTimeZone = ZonedDateTime.of(currDateTime, id);
      //Getting Current Timestamp in Milliseconds
      long currentTS = dateTimeZone.toInstant().toEpochMilli();
      System.out.println(&quot;The Current Timestamp in Milliseconds == &quot; + currentTS);
       
        //Formating the Current Timestamp
        DateTimeFormatter formatPattern = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd HH:mm:ss&quot;);
        String formattedTS = currDateTime.format(formatPattern);
        System.out.println(&quot;The Formatted Timestamp == &quot; + formattedTS);
}
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>Initially, we import the necessary classes like “DateTime”, “ZoneId”, and “ZonedDateTime” from the “java.time” package. Also, we import the DateTimeFormatter class from its respective package to format the current timestamp in a specific format.</li>



<li>After this, we invoke the “now()” method of the LocalDateTime class to fetch the current DateTime.&nbsp;</li>



<li>Next, we use the “ZoneId.systemDefault()” method to get the system’s default zone id.&nbsp;</li>



<li>After this, we use the ZonedDateTime.of() method to represent the DateTime with timezone information.</li>



<li>Next, we invoke the “toInstant().toEpochMilli()” method on the dateTimeZone instance to retrieve the current timestamp(in milliseconds).</li>



<li>Then we use the DateTimeFormatter.ofPattern() method to specify a pattern according to which the current timestamp will be formatted.</li>



<li>Finally, we invoke the format method on the currDateTime instance to format it according to the specified DateTime pattern:</li>
</ul>



<figure class="wp-block-image size-full"><img decoding="async" width="727" height="110" src="http://javabeat.net/wp-content/uploads/2024/04/image-53.png" alt="" class="wp-image-188224" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-53.png 727w, https://javabeat.net/wp-content/uploads/2024/04/image-53-300x45.png 300w" sizes="(max-width: 727px) 100vw, 727px" /></figure>



<p>That’s all about Getting a current timestamp in Java.</p>



<h2 class="wp-block-heading">Final Thoughts</h2>



<p>The current timestamp represents the DateTime at the current instance along with the timezone information. To get a current timestamp in Java, we can use methods like “currentTimeMillis()”, “now()”, and the “Date()” constructor. Also, we can use the “Timestamp” class, or “LocalDateTime and ZoneId” Classes to achieve the same purpose. This write-up presented six different methods to get the current timestamp in Java; each method has its pros and cons; you can use the one that best suits your needs.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Connect to PostgreSQL From Java</title>
		<link>https://javabeat.net/connect-postgresql-from-java/</link>
		
		<dc:creator><![CDATA[Anees Asghar]]></dc:creator>
		<pubDate>Tue, 30 Apr 2024 13:43:26 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://javabeat.net/?p=188211</guid>

					<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>
<p>To connect PostgreSQL to Java, we can use an open-source JDBC driver. For this purpose, we can use the getConnection() method.</p>
]]></description>
										<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>

<p>Java Database Connectivity(JDBC) is a Java API that establishes a connection between Java applications and databases (like PostgreSQL). We can integrate JDBC into a Java application and then establish a connection with the PostgreSQL database. Not sure how to proceed with this? No worries! In this tutorial, we’ll show you how to connect PostgreSQL to Java using step-by-step instructions.&nbsp;</p>



<h2 class="wp-block-heading">How to Connect PostgreSQL to Java</h2>



<p>Postgres JDBC is an open-source driver that helps users establish a connection between a Java program and a Postgres database. We can download this driver and integrate it with Java.</p>



<p>To connect the Postgres database to a Java Program, go through the following steps:</p>



<h3 class="wp-block-heading">Step1: Integrate Postgres JDBC Driver into Your Java Project</h3>



<p>We can integrate the Postgres JDBC driver into a Java project using JAR File or Maven dependency:</p>



<ul class="wp-block-list">
<li><strong>Using JAR File</strong></li>
</ul>



<p>We can download the Postgres JDBC driver from <a href="https://jdbc.postgresql.org/download/">Postgres’ official website</a>. Once downloaded, add its JAR file to your Java project. Follow the below instructions to add the Postgres JDBC JAR file to Eclipse IDE:</p>



<p>First, right-click on the project, hover over the “Build Path”, and select the “Configure Build Path…” option:</p>



<figure class="wp-block-image"><img decoding="async" width="707" height="619" src="http://javabeat.net/wp-content/uploads/2024/04/image-51.png" alt="" class="wp-image-188218" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-51.png 707w, https://javabeat.net/wp-content/uploads/2024/04/image-51-300x263.png 300w" sizes="(max-width: 707px) 100vw, 707px" /></figure>



<p>From the pop-up window, navigate to the “Libraries” tab, left-click on the “Classpath”, and select the “Add External JARs…” button:</p>



<figure class="wp-block-image"><img decoding="async" width="926" height="540" src="http://javabeat.net/wp-content/uploads/2024/04/image-50.png" alt="" class="wp-image-188217" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-50.png 926w, https://javabeat.net/wp-content/uploads/2024/04/image-50-300x175.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-50-768x448.png 768w" sizes="(max-width: 926px) 100vw, 926px" /></figure>



<p>Now select the downloaded Postgres JDBC JAR file and hit the “Open” button:</p>



<figure class="wp-block-image"><img decoding="async" width="668" height="469" src="http://javabeat.net/wp-content/uploads/2024/04/image-52.png" alt="" class="wp-image-188219" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-52.png 668w, https://javabeat.net/wp-content/uploads/2024/04/image-52-300x211.png 300w" sizes="(max-width: 668px) 100vw, 668px" /></figure>



<p>Finally, click the “Apply and Close” button to add the selected JAR file to your project:</p>



<figure class="wp-block-image"><img decoding="async" width="931" height="548" src="http://javabeat.net/wp-content/uploads/2024/04/image-49.png" alt="" class="wp-image-188216" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-49.png 931w, https://javabeat.net/wp-content/uploads/2024/04/image-49-300x177.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-49-768x452.png 768w" sizes="(max-width: 931px) 100vw, 931px" /></figure>



<ul class="wp-block-list">
<li><strong>Using Maven Dependency</strong></li>
</ul>



<p>Alternatively, you can create a maven project and modify its “pom.xml” file. To do that, simply add the <a href="https://jdbc.postgresql.org/download/">latest dependency</a> of the Postgres JDBC driver into the pom file, as follows:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;org.postgresql&lt;/groupId&gt;
    &lt;artifactId&gt;postgresql&lt;/artifactId&gt;
    &lt;version&gt;42.7.3&lt;/version&gt;
&lt;/dependency&gt;
</pre></div>


<p>Using this method, there is no need to download the JDBC driver manually. Instead, Maven will automatically download all the essential JAR files from the remote repositories.</p>



<h3 class="wp-block-heading">Step 2: Establish a Connection Between Postgres and Java</h3>



<p>Now type the following code in your Java file to establish a connection with the Postgres database:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.sql.*;

public class PostgresJavaConnection {
public static void main(String&#x5B;] args) throws ClassNotFoundException, SQLException {
String conn = &quot;jdbc:postgresql://localhost:5432/postgres&quot;;
String username = &quot;postgres&quot;;
String pass = &quot;1212&quot;;
Class.forName(&quot;org.postgresql.Driver&quot;);
      try (Connection connect = DriverManager.getConnection(conn, username, pass)) {
System.out.println(&quot;Connection Established Successfully!&quot;);
} catch (SQLException excep) {
excep.printStackTrace();
}
}
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>First, we import the required classes like “Connection”, “DriverManager”, and “SQLException” from the “java.sql” package.</li>



<li>In the main() method, we specify the URL to establish the Postgres-Java connection using JDBC.&nbsp;</li>



<li>Next, we specify the database username and respective password.</li>



<li>The next line of code registers the Postgres driver.</li>



<li>We invoke the getConnection() method to make a connection between PostgreSQL and Java.</li>



<li>Finally, we use the catch() block to catch the potential exceptions.</li>
</ul>



<p><strong>Output</strong></p>



<figure class="wp-block-image"><img decoding="async" width="724" height="100" src="http://javabeat.net/wp-content/uploads/2024/04/image-46.png" alt="" class="wp-image-188213" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-46.png 724w, https://javabeat.net/wp-content/uploads/2024/04/image-46-300x41.png 300w" sizes="(max-width: 724px) 100vw, 724px" /></figure>



<p>The above snippet confirms the Postgres-Java connection establishment. Now, we can run any SQL query to perform database operations, such as table creation, deletion, etc.</p>



<h3 class="wp-block-heading">Step 3: Fetch Table Data</h3>



<p>We have already created a table named “article_details” in the “postgres” database. Let’s run the following Java code to fetch the data of the “article_details” table:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
Statement sqlStatement = connect.createStatement();
ResultSet tbl = sqlStatement.executeQuery(&quot;SELECT * FROM article_details&quot;);
while (tbl.next()) {
String tableColumns = tbl.getString(&quot;article_title&quot;);
System.out.println(&quot;The Article Title = &quot; + tableColumns);
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>After establishing the connection, we use the “createStatement()” method to send SQL statements to the database.</li>



<li>Next, we use the executeQuery() method to execute the SELECT query. This retrieves the data from the “article_details” table.</li>



<li>In the next line, we use the while loop with the next() method to traverse each record of the selected table.</li>



<li>Finally, we print the retrieved table records on the console using Java’s println() method.</li>
</ul>



<p><strong>Output</strong></p>



<figure class="wp-block-image"><img decoding="async" width="832" height="478" src="http://javabeat.net/wp-content/uploads/2024/04/image-48.png" alt="" class="wp-image-188215" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-48.png 832w, https://javabeat.net/wp-content/uploads/2024/04/image-48-300x172.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-48-768x441.png 768w" sizes="(max-width: 832px) 100vw, 832px" /></figure>



<p>The output shows that table rows have been successfully retrieved.</p>



<h3 class="wp-block-heading">Step 4: Create a New Table</h3>



<p>In the following snippet, we create a new Postgres table named “studentInfo”:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
Statement sqlStatement = connect.createStatement();
String createNewTable = &quot;CREATE TABLE studentInfo (&quot;
                + &quot;std_id serial PRIMARY KEY,&quot;
                + &quot;std_name TEXT,&quot;
                + &quot;std_email VARCHAR(255))&quot;;

sqlStatement.execute(createNewTable);
System.out.println(&quot;Table Created Successfully!&quot;);
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>First, we use the CREATE TABLE statement to create a new &#8221; studentInfo &#8221; table.</li>



<li>Next, we invoke the execute() method to execute the CREATE TABLE statement.</li>
</ul>



<p><strong>Output</strong></p>



<p>The following output shows that a new table has been successfully created in the postgres database:</p>



<figure class="wp-block-image"><img decoding="async" width="828" height="483" src="http://javabeat.net/wp-content/uploads/2024/04/image-47.png" alt="" class="wp-image-188214" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-47.png 828w, https://javabeat.net/wp-content/uploads/2024/04/image-47-300x175.png 300w, https://javabeat.net/wp-content/uploads/2024/04/image-47-768x448.png 768w" sizes="(max-width: 828px) 100vw, 828px" /></figure>



<p>This way we can execute any SQL query from Java to perform database operations like data insertion, table deletion, etc.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>We can connect PostgreSQL to Java using an open-source JDBC driver. We can use the JAR File or Maven dependency to integrate the Postgres JDBC driver into a Java project. Once Postgres is integrated with Java, we can use the getConnection() method to establish the Postgres-Java connection. After establishing a connection, we can execute any SQL query to perform a database operation, as illustrated in this post.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Understanding Java Literals With Examples</title>
		<link>https://javabeat.net/understanding-java-literals-with-examples/</link>
		
		<dc:creator><![CDATA[Anees Asghar]]></dc:creator>
		<pubDate>Tue, 30 Apr 2024 13:36:06 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://javabeat.net/?p=188207</guid>

					<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>
<p>A literal is a synthetic representation of a boolean, char, string, or numeric data.<br />
Java supports various types of literals, such as Integral, boolean, char, etc.</p>
]]></description>
										<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>

<p>Java literals synthetically represent boolean, character, string, numeric, and floating point data. The Java literals let us express particular values within a program. We can directly write these values in our code without requiring computation or evaluation. Java supports multiple literal types that will be discussed in this post along with practical examples.</p>



<h2 class="wp-block-heading">What Are Literals in Java</h2>



<p>A literal in Java is a fixed value directly written into the code and cannot be changed during program execution.&nbsp;</p>



<h2 class="wp-block-heading">What Are Different Types of Literals in Java</h2>



<p>Java supports the below-listed Types of “Literals” and these types are further classified into several subtypes:&nbsp;</p>



<ul class="wp-block-list">
<li>Integral Literals</li>



<li>Floating-Point Literal</li>



<li>Char or Character Literals</li>



<li>String Literals</li>



<li>Boolean Literals</li>



<li>Null Literals</li>



<li>Backslash Literals</li>



<li>Invalid Literals</li>
</ul>



<p>Let’s start with the integral literals.</p>



<h2 class="wp-block-heading">1) Integral Literals in Java</h2>



<p>In Java, we can have four types of integral literals/numbers: “Integer”, “long”, “short”, and “byte”. By default, each literal is of type int or integer, however, we can specify it explicitly as the long type using the “l” or “L” suffix. We can’t specify short or byte literals explicitly, however, we can do that indirectly. If we declare a variable of type byte and assign it with a value that lies within the range of byte, then the Java compiler treats it as a byte literal.&nbsp;</p>



<p>To specify these integral literals, opt for one of the following ways:</p>



<ol class="wp-block-list">
<li>Decimal Literals (Base 10)</li>



<li>Octal Literals (Base 8)</li>



<li>Hexa-Decimal Literals (Base 16)</li>



<li>Binary Literals (Base 2)</li>
</ol>



<h3 class="wp-block-heading">Decimal Literals (Base 10)</h3>



<p>The decimal literals are the most commonly used integral literals that allow digits from 0-9. These literals can be positive or negative. Here are some examples:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
int number = 5;int number1 = -512;int number2 = 51214;
</pre></div>


<h3 class="wp-block-heading">Octal Literals (Base 8)</h3>



<p>Another way of specifying the integer literals is the Octal form that lets us specify digits between 0-7. However, it is important to note that an octal literal must be prefixed with a “0”, as shown in the following example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
int number = 0123
</pre></div>


<h3 class="wp-block-heading">Hexa-Decimal Literals (Base 16)</h3>



<p>We can also specify an integral literal in base 16, known as hexadecimal literals. We can specify digits between 0-9 and characters between “a-f” or “A-F”. Where the characters represent numbers from 10-15, i.e., a &amp; A represent 10, b &amp; B represent 11, and so on. The hexadecimal values/literals are prefixed with “0X” or “0x”. Here are some examples:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
int number = 0X6;
int number1 = 0Xb;
</pre></div>


<h3 class="wp-block-heading">Binary Literals (Base 2)</h3>



<p>Java allows us to specify an integer in base, known as binary literal. The binary literals allow us to specify a digit between 0 and 1. A binary literal must be prefixed with 0B or 0b, as illustrated in the following examples:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
int number = 0b1010;
int number1 = 0B1110;
</pre></div>


<h2 class="wp-block-heading">2) Floating-point Literals in Java</h2>



<p>The numbers that include a floating point or fractional part are known as the “floating-point” or “real” literals. We can specify a floating point value in decimal form or exponential notation. The floating-point literals are positive by default, however, to represent a negative value, we need to specify/use the “-” symbol. The valid digits to specify floating-point literals are 0-9. Here is an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
double number = 654.321;float number = 654.321f;
</pre></div>


<p><strong>Note:</strong> By default, a floating-point literal is of type double, so we can’t assign it to a float-type variable. However, we can use the suffix “f” or “F” to assign it to a float variable. We can’t specify a floating-point literal in octal or hexadecimal form.</p>



<h2 class="wp-block-heading">3) Char or Character Literals in Java</h2>



<p>A char/character literal in Java has a data type “char” and is expressed as a character or an escape sequence. We can specify a char literal in Java in the following ways:</p>



<h3 class="wp-block-heading">Single Quote</h3>



<p>We can assign a literal to a char data type by specifying a single character within single quotes. Here is an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
char gender = &#039;M&#039;;
</pre></div>


<h3 class="wp-block-heading">Char as Integral Literal</h3>



<p>We can represent a character literal as an integral value, which indicates the Unicode value of the character. This integral value can be expressed/represented in Decimal, Hexadecimal, or Octal representation. However, it&#8217;s crucial to note that the valid range for this value is from 0 to 65535. Here is an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
char x = 65;
</pre></div>


<h3 class="wp-block-heading">Unicode Representation</h3>



<p>In Java, we can specify a char literal in <a href="https://javabeat.net/store-unicode-characters-java/">Unicode</a> representation by using the escape sequence “\u” followed by a four-digit hexadecimal number, as illustrated below:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
char x = &#039;\u0065&#039;;  //it represent lowercase letter e
</pre></div>


<h3 class="wp-block-heading">Escape Sequence</h3>



<p>Each escape character can be represented as a char literal, as shown in the following example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
char x = &#039;\t&#039;;  //here horizontal tab is specified as a char literal
</pre></div>


<h2 class="wp-block-heading">4) String Literals in Java</h2>



<p>A string literal in Java represents a sequence of characters specified within double quotations. This sequence may include alphabets, special symbols, numbers, blank spaces, etc. Here are some examples of String literals in Java:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
String str = &quot;javabeat&quot;;
String str = &quot;java@beat&quot;;
String str = &quot;12java123beat12&quot;;
</pre></div>


<h2 class="wp-block-heading">5) Boolean Literals in Java</h2>



<p>The Boolean literals in Java let us specify only one of two values: “true” or “false”. Here is an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
boolean isAvailable = true;  boolean isAvailable = false;
</pre></div>


<h2 class="wp-block-heading">6) Null Literals in Java</h2>



<p>The null keyword represents that a reference-type object isn&#8217;t available. It can be assigned to any variable except those of primitive types. Here is an example that demonstrates how to specify a null literal in Java:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
String productDescription = null;
</pre></div>


<h2 class="wp-block-heading">7) Backslash Literals in Java</h2>



<p>A literal that is prefixed with a backslash is referred to as a backslash literal. These literals are illustrated in the following table:</p>



<figure class="wp-block-table"><table><thead><tr><th><strong>Literal</strong></th><th><strong>Description</strong></th></tr></thead><tbody><tr><td><strong>\t</strong></td><td>It represents/adds a horizontal tab.</td></tr><tr><td><strong>\v</strong></td><td>It represents/adds a vertical tab.</td></tr><tr><td><strong>\n</strong></td><td>It shifts/moves the cursor to a new line.</td></tr><tr><td><strong>\&#8217;</strong></td><td>It is used to add single quotes.</td></tr><tr><td><strong>\&#8221;</strong></td><td>It adds double quotes.</td></tr><tr><td><strong>\a</strong></td><td>It adds a small beep.</td></tr><tr><td><strong>\b</strong></td><td>It adds a blank space.</td></tr><tr><td><strong>\r</strong></td><td>It is used for carriage return, which means it moves the cursor to the start of the current line without proceeding to the next line.&nbsp;</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">8) Invalid Literals</h2>



<p>Be careful while declaring and using literals in Java, otherwise, you may face unwanted results. Here are some examples of invalid declarations of Java Literals:</p>



<ul class="wp-block-list">
<li>Underscores are not allowed immediately before or after a decimal point. For example, “123_.456” and “123._456” are invalid literals.</li>



<li>We can&#8217;t use underscores as the last character of a numeric literal like this “100_”.</li>



<li>We can’t use an underscore immediately before or after the &#8216;0x&#8217; or &#8216;0X&#8217; prefix, like “0x_52” or “0X_44”.</li>
</ul>



<p>All in all, Underscores have to be located within digits.</p>



<h2 class="wp-block-heading">How Literals Work in Java</h2>



<p>This practical example demonstrates how to use literals in Java:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class Example {
public static void main(String&#x5B;] args) {
//Integral Literals
int num = 172;  
int hexaNum = 0x5e3; 
int binaryNum = 0b1110;
int octalNum = 054; 

//Floating-point Literals
double doubleNum = 654.321;
float floatNum = 654.321f;

//Char Literals
char gender = &#039;M&#039;;
char x = 65;
char y = &#039;\u0065&#039;;
char z = &#039;\t&#039;;

//String Literals
String str = &quot;javabeat&quot;;
String str1 = &quot;java@beat&quot;;
String str2 = &quot;12java123beat12&quot;;

//Boolean Literals
boolean isAvailable = true;

//Null Literals
String productDescription = null; 

System.out.println(&quot;Decimal Literals ==&gt; &quot; + num);
System.out.println(&quot;HexaDecimal Literals ==&gt; &quot; + hexaNum);
System.out.println(&quot;Binary Literals ==&gt; &quot; + binaryNum);
System.out.println(&quot;Octal Literals ==&gt; &quot; + octalNum);

System.out.println(&quot;Floating-point Literals ==&gt; &quot; + doubleNum);
System.out.println(&quot;Floating-point Literals ==&gt; &quot; + floatNum);

System.out.println(&quot;Char Literals ==&gt; &quot; + gender);
System.out.println(&quot;Integral Literal as Char Literal ==&gt; &quot; + x);
System.out.println(&quot;Char Literal Unicode Representation ==&gt; &quot; + y);
System.out.println(&quot;Char Literal Escape Sequence ==&gt; &quot; + z);

System.out.println(&quot;String Literal ==&gt; &quot; + str);
System.out.println(&quot;String Literal Containing Special Character ==&gt; &quot; + str1);
System.out.println(&quot;Alphanumeric String Literal ==&gt; &quot; + str2);

System.out.println(&quot;Boolean Literals ==&gt; &quot; + isAvailable);

System.out.println(&quot;Null Literals ==&gt; &quot; + productDescription);
}
}
</pre></div>


<p>The above code implements Integral, Floating-point, Char, String, Boolean, and Null Literals in Java:</p>



<figure class="wp-block-image"><img decoding="async" width="737" height="328" src="http://javabeat.net/wp-content/uploads/2024/04/image-45.png" alt="" class="wp-image-188209" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-45.png 737w, https://javabeat.net/wp-content/uploads/2024/04/image-45-300x134.png 300w" sizes="(max-width: 737px) 100vw, 737px" /></figure>



<p>That’s all about Literals in Java.</p>



<h2 class="wp-block-heading">Final Thoughts</h2>



<p>A literal in Java is a synthetic representation of a boolean, char, string, or numeric data. It is a way of expressing a specific value in a program, such as int age = 28; String name = &#8220;Joseph&#8221;. These values remain constant throughout the program.</p>



<p>Java supports several types of literals, such as “Integral”, “floating-point”, “boolean”, “char”, “string”, “backslash”, and “null” literals. This Java tutorial has demonstrated all these literal types with suitable examples.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Convert a Timestamp to a Date in Java</title>
		<link>https://javabeat.net/convert-timestamp-date-in-java/</link>
		
		<dc:creator><![CDATA[Anees Asghar]]></dc:creator>
		<pubDate>Tue, 30 Apr 2024 13:21:55 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://javabeat.net/?p=188199</guid>

					<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>
<p>We can use the “Date()” constructor, “Calendar” class, or “Date” Reference for converting a timestamp to a date in Java.</p>
]]></description>
										<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>

<p>While manipulating DateTime values, Java users often come across a situation where they need to convert a timestamp to a date. Timestamps are usually represented in numerical values that are difficult to read. Therefore, converting timestamps to dates allows us to display DateTime values in a human-friendly format. To do this in Java, we can use the built-in classes like Date and Calendar.&nbsp;</p>



<p>So, let’s learn how to convert a timestamp to a date in Java using different methods.</p>



<h2 class="wp-block-heading">How to Convert a Timestamp to a Date in Java</h2>



<p>We can use the “Date()” constructor, “Calendar” class, or “Date” Reference for converting a timestamp to a date in Java.</p>



<p>So let’s get started with the Date() constructor.</p>



<h2 class="wp-block-heading">Method 1: Converting a Timestamp to a Date Using Date() Constructor</h2>



<p>The <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Date.html">Date</a> class in Java offers multiple constructors and built-in methods that let us work with the DateTime values efficiently. We can pass a timestamp to the Date() constructor to convert it into a date. Here is an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.sql.Timestamp;
import java.util.Date;

public class Example {
    public static void main(String&#x5B;] args) {
Timestamp currTS = new Timestamp(System.currentTimeMillis());
System.out.println(&quot;The Current Timestamp == &quot; + currTS);
System.out.println(&quot;The Type of Original DateTime == &quot; + currTS.getClass().getName());

Date currDate = new Date(currTS.getTime());
System.out.println(&quot;The Current Date == &quot; + currDate);
System.out.println(&quot;The Type of Converted DateTime == &quot; + currDate.getClass().getName());
}
}
</pre></div>


<p>In this code,&nbsp;</p>



<ul class="wp-block-list">
<li>First, we import the Timestamp and Date classes from the sql and util packages, respectively.</li>



<li>In the main() method, we wrap the “currentTimeMillis()” method within the Timestamp() constructor to get the Current DateTime.</li>



<li>Next, we print the current date, time, and its respective data type on the console.</li>



<li>After this, we pass the current timestamp to the Date() constructor to convert it into a date. It is important to note that the Date() constructor accepts a long-type value, so we use the getTime() method with the Timestamp instance to convert it into a long-type value.</li>



<li>Finally, we print the converted date and its respective data type on the console:</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="737" height="132" src="http://javabeat.net/wp-content/uploads/2024/04/image-44.png" alt="" class="wp-image-188205" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-44.png 737w, https://javabeat.net/wp-content/uploads/2024/04/image-44-300x54.png 300w" sizes="(max-width: 737px) 100vw, 737px" /></figure>



<h2 class="wp-block-heading">Method 2: Converting a Timestamp to a Date Using Calendar Class</h2>



<p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html">Calendar</a> is a built-in abstract class in Java that provides different methods to convert dates between a particular instant in time and calendar fields like, Day, Month, Year, etc. We can use this class to convert a timestamp to a date, as demonstrated in the following code:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.sql.*;
import java.util.*;

public class Example {
  public static void main(String&#x5B;] args) {
Timestamp currTS = new Timestamp(System.currentTimeMillis());
System.out.println(&quot;The Current Timestamp == &quot; + currTS);
System.out.println(&quot;The Type of Original DateTime == &quot; + currTS.getClass().getName());

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(currTS.getTime());
System.out.println(&quot;The Current DateTime == &quot; + cal.getTime());
System.out.println(&quot;The Type of Converted DateTime == &quot; + cal.getClass().getName());
}
}
</pre></div>


<p>In this code,&nbsp;</p>



<ul class="wp-block-list">
<li>We import the essential classes like Timestamp and Calendar from the respective packages.</li>



<li>Next, we use the Timestamp() constructor to get a timestamp that we want to convert.</li>



<li>We print the retrieved timestamp and its respective class on the console.</li>



<li>After this, we create a Calendar class instance and set its time to the timestamp using the setTimeInMillis() method.</li>



<li>Finally, we print the converted date and its corresponding class on the console:</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="733" height="141" src="http://javabeat.net/wp-content/uploads/2024/04/image-41.png" alt="" class="wp-image-188202" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-41.png 733w, https://javabeat.net/wp-content/uploads/2024/04/image-41-300x58.png 300w" sizes="(max-width: 733px) 100vw, 733px" /></figure>



<h2 class="wp-block-heading">Method 3: Converting a Timestamp to a Date Using a Date Reference</h2>



<p>We can directly assign a timestamp object to a date instance to convert a timestamp to a date. Here is an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.sql.Timestamp;import java.util.Date;
public class Example {
public static void main(String&#x5B;] args) {
Timestamp currTS = new Timestamp(System.currentTimeMillis());
System.out.println(&quot;The Current Timestamp == &quot; + currTS);
Date currDate = currTS;
System.out.println(&quot;The Current Date == &quot; + currDate);
}
}
</pre></div>


<p>In this code, first, we get the current DateTime using the Timestamp() constructor and print it on the console. After this, we assign the obtained current timestamp to the Date instance. Finally, we print the converted date on the console:</p>



<figure class="wp-block-image"><img decoding="async" width="736" height="106" src="http://javabeat.net/wp-content/uploads/2024/04/image-40.png" alt="" class="wp-image-188201" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-40.png 736w, https://javabeat.net/wp-content/uploads/2024/04/image-40-300x43.png 300w" sizes="(max-width: 736px) 100vw, 736px" /></figure>



<p><strong>Important:</strong> We can easily convert a timestamp to a date using the Date reference, however, Java experts recommend not using this method due to the potential loss of milliseconds and nanoseconds.</p>



<h3 class="wp-block-heading">How to Convert a Timestamp to a Specific Date Format</h3>



<p>We can use the SimpleDateFormat() constructor to format the converted date into a specific date format, as shown in the following example:&nbsp;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;

public class Example {

public static void main(String&#x5B;] args) {
Timestamp currTS = new Timestamp(System.currentTimeMillis());
System.out.println(&quot;The Current Timestamp == &quot; + currTS);
System.out.println(&quot;The Type of Original DateTime == &quot; + currTS.getClass().getName());

Date currDate = new Date(currTS.getTime());
DateFormat formattedDate = new SimpleDateFormat(&quot;yyyy/MM/dd&quot;);
String date = formattedDate.format(currDate);

System.out.println(&quot;The Formatted Date == &quot; + date);
System.out.println(&quot;The Type of Converted DateTime == &quot; + currDate.getClass().getName());
}
}
</pre></div>


<p>In this code,&nbsp;</p>



<ul class="wp-block-list">
<li>First, we import the required classes like Timestamp, DateFormat, Date, and SimpleDateFormat from the corresponding packages.</li>



<li>Next, we get the timestamp to be converted using the Timestamp() constructor and print it on the console. Also, we print the class name to which the current timestamp belongs on the console.</li>



<li>After this, we pass the given timestamp to the Date() constructor to convert it into a date.</li>



<li>Next, we use the SimpleDateFormat class to format the converted date into &#8220;yyyy/MM/dd&#8221; format.</li>



<li>Finally, we print the formatted date along with its respective class on the console:</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="731" height="152" src="http://javabeat.net/wp-content/uploads/2024/04/image-43.png" alt="" class="wp-image-188204" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-43.png 731w, https://javabeat.net/wp-content/uploads/2024/04/image-43-300x62.png 300w" sizes="(max-width: 731px) 100vw, 731px" /></figure>



<h2 class="wp-block-heading">How to Convert a Date to a Timestamp in Java</h2>



<p>We can also convert a date to a timestamp in Java using the Timestamp() constructor, as shown in the example below:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.sql.Timestamp;
import java.util.Date;

public class Example {
    public static void main(String&#x5B;] args) {
      Date currDate = new Date();       System.out.println(&quot;The Current Date == &quot; + currDate);       System.out.println(&quot;The Type of Original DateTime == &quot; + currDate.getClass().getName());
      Timestamp currTS = new Timestamp(currDate.getTime());
      System.out.println(&quot;The Converted Timestamp == &quot; + currTS);
      System.out.println(&quot;The Type of Converted DateTime == &quot; + currTS.getClass().getName());
  }
}
</pre></div>


<p>In this code,&nbsp;</p>



<ul class="wp-block-list">
<li>We get the current Date using the Date() constructor and print it on the console along with its respective class.</li>



<li>Next, we invoke the “getTime()” method with the Date instance and pass it to the Timestamp() constructor to convert it into a timestamp.</li>



<li>In the end, we print the converted timestamp and its data type on the console:</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="740" height="144" src="http://javabeat.net/wp-content/uploads/2024/04/image-42.png" alt="" class="wp-image-188203" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-42.png 740w, https://javabeat.net/wp-content/uploads/2024/04/image-42-300x58.png 300w" sizes="(max-width: 740px) 100vw, 740px" /></figure>



<p>That’s all about converting a timestamp to a date(or vice versa) in Java.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>We can use the Date() constructor, Calendar class, and date reference to convert a timestamp to a date in Java. To convert a timestamp to a date, simply invoke the getTime() method with the timestamp instance and pass it as an argument to the Date() constructor. In addition to this, we can convert a timestamp to a date and format it according to a specific format pattern using the SimpleDateFormat class. This post demonstrated different methods of converting a timestamp to a date in Java using suitable examples.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Get a Timezone List in Java</title>
		<link>https://javabeat.net/get-timezone-list-in-java/</link>
		
		<dc:creator><![CDATA[Anees Asghar]]></dc:creator>
		<pubDate>Tue, 30 Apr 2024 13:17:33 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://javabeat.net/?p=188190</guid>

					<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>
<p>To get a timezone in Java, invoke the getDefault() method of the Timezone class. Use the getAvailableIDs() method to get all available timezone IDs.</p>
]]></description>
										<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>

<p>Java offers a built-in <a href="https://docs.oracle.com/javase/8/docs/api/java/util/TimeZone.html">TimeZone</a> class that belongs to the “java.util” package. This class provides several methods that help us get timezone information. Using these methods, we can get the current timezone, all available time zones, or a specific timezone. Also, we can set or modify a timezone. Don’t know how to get/set a timezone in Java? No worries, in this tutorial, we’ll provide stepwise instructions to get a time zone in Java. </p>



<h2 class="wp-block-heading">How to Get the Default Timezone in Java</h2>



<p>The TimeZone class belongs to the “java.util” package and offers different methods to work with the timezones. One such method is getDefault() which retrieves the system’s default timezone, as demonstrated in the following example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.TimeZone;
public class GetTimezoneJava {
  public static void main(String args&#x5B;]) {
      TimeZone defaultTZ = TimeZone.getDefault();
      System.out.println(&quot;The Default Timezone is ==&gt; &quot; + defaultTZ);
  }
}
</pre></div>


<p>In the above code:</p>



<ul class="wp-block-list">
<li>First, we import the TimeZone class from the util package to work with the timezones.</li>



<li>In the main() method, we invoke the getDefault() method of the TimeZone class to get the system’s default timezone.&nbsp;</li>



<li>Finally, we print the retrieved timezone on the console using the println() method:</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="619" height="101" src="http://javabeat.net/wp-content/uploads/2024/04/image-38.png" alt="" class="wp-image-188196" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-38.png 619w, https://javabeat.net/wp-content/uploads/2024/04/image-38-300x49.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></figure>



<h2 class="wp-block-heading">How to Get All Timezone IDs in Java</h2>



<p>We can use the getAvailableIDs() method of the TimeZone class to get all available timezone IDs. Here is an example that retrieves all timezone IDs on the console:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.TimeZone;
public class GetTimezoneJava {
    public static void main(String args&#x5B;]) {
String&#x5B;] getIDs = TimeZone.getAvailableIDs();
System.out.println(&quot;The Available Timezone IDs are ==&gt;&quot;);
  for (int i = 0; i &lt; getIDs.length; i++) {
System.out.println(getIDs&#x5B;i]);
}
  }
}
</pre></div>


<p>In this code example,</p>



<ul class="wp-block-list">
<li>We invoke the getAvailableIDs() method and store its result in a string array “getIDs”.</li>



<li>After this, we use a for loop to traverse the complete array, access each array element, and print it on the console:</li>
</ul>



<p>This way, each available timezone is printed on the console, as shown below:</p>



<figure class="wp-block-image"><img decoding="async" width="733" height="355" src="http://javabeat.net/wp-content/uploads/2024/04/image-39.png" alt="" class="wp-image-188197" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-39.png 733w, https://javabeat.net/wp-content/uploads/2024/04/image-39-300x145.png 300w" sizes="(max-width: 733px) 100vw, 733px" /></figure>



<h2 class="wp-block-heading">How to Get the IDs According to a Specific Timezone Offset in Java</h2>



<p>We can also get a list of IDs according to a specific timezone offset. For this purpose, we need to pass the raw offset as an argument to the getAvailableIDs() method, as illustrated below:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.TimeZone;

public class GetTimezoneJava {
public static void main(String args&#x5B;]) {
String&#x5B;] givenID = TimeZone.getAvailableIDs(-21600000);
System.out.println(&quot;The Available Ids in the Given TimeZone are ==&gt;&quot;);
for (int i = 0; i &lt; givenID.length; i++) {
System.out.println(givenID&#x5B;i]);
}
}
}
</pre></div>


<p>In this example,&nbsp;</p>



<ul class="wp-block-list">
<li>We specify a raw offset of “-21600000” to the getAvailableIDs() method that represents -6 hours from GMT.&nbsp;</li>



<li>We assign the result of the getAvailableIDs() method to a string array “givenID”.&nbsp;</li>



<li>Finally, we use a for loop to iterate the array and print each timezone ID on the console:&nbsp;</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="705" height="369" src="http://javabeat.net/wp-content/uploads/2024/04/image-34.png" alt="" class="wp-image-188192" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-34.png 705w, https://javabeat.net/wp-content/uploads/2024/04/image-34-300x157.png 300w" sizes="(max-width: 705px) 100vw, 705px" /></figure>



<h2 class="wp-block-heading">How to Get the Current Time in Another Timezone</h2>



<p>We can also get the current time in any specific timezone (i.e., other than the default timezone). To do this, we need to pass the desired timezone in the getTimeZone() method. For example, the below code prints the current time in the system’s default timezone and a specific timezone, i.e., “America/Chicago”:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.*;

public class GetTimezoneJava {
public static void main(String args&#x5B;]) {
Calendar currInstance = Calendar.getInstance();
System.out.println(&quot;Current Time in Default TimeZone is ==&gt;&quot;);
System.out.println(&quot;Current Hour = &quot; + currInstance.get(Calendar.HOUR_OF_DAY));
System.out.println(&quot;Current Minute = &quot; + currInstance.get(Calendar.MINUTE));
System.out.println(&quot;Current Second = &quot; + currInstance.get(Calendar.SECOND));
System.out.println(&quot;Current Millisecond = &quot; + currInstance.get(Calendar.MILLISECOND));

System.out.println(&quot;Current Time in America/Chicago TimeZone is ==&gt; &quot;);
currInstance.setTimeZone(TimeZone.getTimeZone(&quot;America/Chicago&quot;));
System.out.println(&quot;Current Hour = &quot; + currInstance.get(Calendar.HOUR_OF_DAY));
System.out.println(&quot;Current Minute = &quot; + currInstance.get(Calendar.MINUTE));
System.out.println(&quot;Current Second = &quot; + currInstance.get(Calendar.SECOND));
System.out.println(&quot;Current Millisecond = &quot; + currInstance.get(Calendar.MILLISECOND));

}
}
</pre></div>


<p>In this example,</p>



<ul class="wp-block-list">
<li>First, we import the necessary classes like “Calendar” and “TimeZone” from the Java util package.</li>



<li>In the main() method, we invoke the getInstance() method to get the current date and time (according to the system’s default timezone).</li>



<li>Next, we use the get() method with the “HOUR_OF_DAY”, “MINUTE”, “SECOND”, and “MILLISECONDS” fields to get the current hour, minutes, seconds, and milliseconds, respectively.</li>



<li>Next, we use the getTimeZone() with the &#8220;America/Chicago&#8221; as its argument to get the current time according to the &#8220;America/Chicago&#8221; timezone.</li>



<li>Finally, we use the get() method to retrieve the current hour, minutes, seconds, and milliseconds according to the “America/Chicago” timezone:</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="733" height="231" src="http://javabeat.net/wp-content/uploads/2024/04/image-36.png" alt="" class="wp-image-188194" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-36.png 733w, https://javabeat.net/wp-content/uploads/2024/04/image-36-300x95.png 300w" sizes="(max-width: 733px) 100vw, 733px" /></figure>



<h2 class="wp-block-heading">How to Set the Base Timezone Offset to GMT in Java</h2>



<p>We can use the setRawOffset() method to set the base timezone offset to any specific value relative to GMT. In the following example, we set the raw offset to 8 minutes:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.TimeZone;

public class GetTimezoneJava {
    public static void main(String args&#x5B;]) {
TimeZone givenTZ = TimeZone.getTimeZone(&quot;America/Chicago&quot;);
System.out.println(&quot;Getting RawOffset of Given Timezone ==&gt;&quot; + givenTZ.getRawOffset());

givenTZ.setRawOffset(800000);
System.out.println(&quot;The Current RawOffset Value is ==&gt;&quot; + givenTZ.getRawOffset());

}
}
</pre></div>


<p>In this code,</p>



<ul class="wp-block-list">
<li>First, we use the getTimeZone() method with the ID “America/Chicago”.</li>



<li>Next, we get and print the raw offset of the “America/Chicago” timezone using the getRawOffset() and println() methods, respectively.</li>



<li>After this, we invoke the setRawOffset() method to set the raw offset of the “givenTZ” time zone to 8 minutes.&nbsp;</li>



<li>Finally, we print the updated raw offset value of the &#8220;America/Chicago&#8221; time zone on the console:</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="653" height="99" src="http://javabeat.net/wp-content/uploads/2024/04/image-35.png" alt="" class="wp-image-188193" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-35.png 653w, https://javabeat.net/wp-content/uploads/2024/04/image-35-300x45.png 300w" sizes="(max-width: 653px) 100vw, 653px" /></figure>



<h2 class="wp-block-heading">How to Get a Formatted Timezone in Java</h2>



<p>We use the SimpleDateFormat class to <a href="https://javabeat.net/convert-date-dd-mm-yyyy-format-java/">format</a> a date, time, or timezone. For instance, in the following code, we get different DateTime fields in a formatted manner:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.util.*;
import java.text.*;

public class GetTimezoneJava {
public static void main(String args&#x5B;]){
Calendar currInstance = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat(&quot;yyyy-MM-dd hh:mm:s z&quot;);

System.out.println(&quot;The Current Instance is ==&gt; &quot; + simpleformat.format(currInstance.getTime()));

Format formatter = new SimpleDateFormat(&quot;YYYY&quot;);
String getYear = formatter.format(new Date());
System.out.println(&quot;The Current Year is ==&gt; &quot; + getYear);

formatter = new SimpleDateFormat(&quot;MM&quot;);
String getMonth = formatter.format(new Date());
System.out.println(&quot;The Current Month is ==&gt; &quot; + getMonth);

formatter = new SimpleDateFormat(&quot;dd&quot;);
String getDay = formatter.format(new Date());
System.out.println(&quot;The Current Day is ==&gt; &quot; + getDay);

formatter = new SimpleDateFormat(&quot;H&quot;);
String getHour = formatter.format(new Date());
System.out.println(&quot;The Current Hour is ==&gt; &quot; + getHour);

formatter = new SimpleDateFormat(&quot;mm&quot;);
String getMinute = formatter.format(new Date());
System.out.println(&quot;Current Minutes ==&gt; &quot; + getMinute);

formatter = new SimpleDateFormat(&quot;ss&quot;);
String getSeconds = formatter.format(new Date());
System.out.println(&quot;Current Seconds ==&gt; &quot; + getSeconds);

formatter = new SimpleDateFormat(&quot;a&quot;);
String getMarker = formatter.format(new Date());
System.out.println(&quot;AM or PM ? &quot; + getMarker);

formatter = new SimpleDateFormat(&quot;z&quot;);
String getTimeZone = formatter.format(new Date());
System.out.println(&quot;The Current TimeZone is ==&gt; &quot; + getTimeZone);
}
}
</pre></div>


<p>In this code,&nbsp;</p>



<ul class="wp-block-list">
<li>We use the format() method to get the current DateTime and timezone in a specific format.</li>



<li>Next, we invoke the SimpleDateFormat() constructor multiple times with the &#8220;YYYY&#8221;, &#8220;MM&#8221;, &#8220;dd&#8221;, &#8220;H&#8221;, &#8220;mm&#8221;, &#8220;ss&#8221;, &#8220;a&#8221;, and &#8220;z&#8221; parameters, respectively.&nbsp;</li>



<li>As a result, we get the current year, month, day, hour minutes, seconds, AM or PM marker, and “timezone”, respectively:&nbsp;</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="731" height="223" src="http://javabeat.net/wp-content/uploads/2024/04/image-37.png" alt="" class="wp-image-188195" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-37.png 731w, https://javabeat.net/wp-content/uploads/2024/04/image-37-300x92.png 300w" sizes="(max-width: 731px) 100vw, 731px" /></figure>



<p>That’s all about getting a Timezone in Java.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>To get a timezone in Java, we can invoke the getDefault() method of the Timezone class. This method retrieves the default timezone based on the system&#8217;s timezone setting. To get a specific timezone, we must specify the timezone ID in the getDefault() method. Also, we can get all available timezones by invoking the getAvailableIDs() method of the TimeZone class. In this Java guide, we covered different aspects of timezones, such as getting a timezone, setting a timezone, formatting a timezone, etc.&nbsp;</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Convert a String to a Timestamp Java</title>
		<link>https://javabeat.net/convert-string-timestamp-java/</link>
		
		<dc:creator><![CDATA[Anees Asghar]]></dc:creator>
		<pubDate>Tue, 30 Apr 2024 12:55:02 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://javabeat.net/?p=188176</guid>

					<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>
<p>To convert a date string into a timestamp in Java, you can use built-in methods like “SimpleDateFormat.parse()” and “Timestamp.valueOf()”. </p>
]]></description>
										<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>

<p>A <a href="https://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html">timestamp</a> is a date-time object in Java that is used to represent date-time information with precision. Java users often go through a situation where they need to convert a string representation of a date into a timestamp object.</p>



<p>In this tutorial, we’ll use different built-in Java classes to convert a string date to a timestamp.&nbsp;</p>



<h2 class="wp-block-heading">How to Convert a String to a Timestamp in Java</h2>



<p><strong>To convert a date string into a timestamp in Java, we can use built-in methods like </strong>“<strong>SimpleDateFormat.parse()</strong>”<strong> and </strong>“<strong>Timestamp.valueOf()</strong>”.&nbsp;</p>



<h3 class="wp-block-heading">1. Converting a String to a Timestamp Using SimpleDateFormat.parse()</h3>



<p>The SimpleDateFormat class provides a method named parse() that takes a string and parses it into a date. This method can <a href="https://javabeat.net/parse-string-in-java/">parse a string</a>(date) into a timestamp. For instance, in the following code snippet, we invoke the parse() method on the given date string to parse into a timestamp according to a specific date format:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.sql.Timestamp;
import java.text.*;

public class ExampleClass {
  public static void main(String&#x5B;] args) {
String givenDate = &quot;2020/11/14 10:11:12&quot;;
SimpleDateFormat formatDate = new SimpleDateFormat(&quot;yyyy/MM/dd HH:mm:ss&quot;);
try {
java.util.Date parseDate = formatDate.parse(givenDate);
Timestamp convertedTimestamp = new Timestamp(parseDate.getTime());
System.out.println(&quot;The Given Date String is ==&gt; &quot; + givenDate);
System.out.println(&quot;The Data Type of Given Date is ==&gt; &quot; + givenDate.getClass().getName());
System.out.println(&quot;The Converted Timestamp is ==&gt; &quot; + convertedTimestamp);
System.out.println(&quot;The Data Type of the Converted Timestamp is ==&gt; &quot; + convertedTimestamp.getClass().getName());
} catch (ParseException excep) {
excep.printStackTrace();
}
}
}
</pre></div>


<p><strong>Code Explanation</strong>&nbsp;</p>



<ul class="wp-block-list">
<li>First, we import the required classes from the “sql” and “text” packages.</li>



<li>After this, we initialize a date string to a variable “givenDate”.&nbsp;</li>



<li>Next, we use the SimpleDateFormat() constructor to specify a valid date format (according to which the provided date will be parsed).&nbsp;</li>



<li>In the next line, we invoke the parse() method on the given string to convert it into a date.</li>



<li>Up next, we use the Timestamp() constructor to convert the parsed date into a timestamp.</li>



<li>Finally, we print the given string and the converted timestamp on the console. Also, we printed the data type of the given date string and the converted timestamp to make things clear:</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="731" height="143" src="http://javabeat.net/wp-content/uploads/2024/04/image-28.png" alt="" class="wp-image-188180" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-28.png 731w, https://javabeat.net/wp-content/uploads/2024/04/image-28-300x59.png 300w" sizes="(max-width: 731px) 100vw, 731px" /></figure>



<p>The output confirms the conversion of the given string into a timestamp using the parse() method.&nbsp;</p>



<h3 class="wp-block-heading">2. Converting a String to a Timestamp Using Timestamp.valueOf()</h3>



<p>The valueOf() is an easy-to-use built-in method of the Timestamp class. This method can be used to convert a date string to a timestamp, as shown in the following code snippet:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.sql.Timestamp;public class ExampleClass {
  public static void main(String&#x5B;] args) {
  String givenDate = &quot;2021-04-11 01:12:12&quot;;
  try {
Timestamp convertedDate = Timestamp.valueOf(givenDate);
System.out.println(&quot;The Given Date String is ==&gt; &quot; + givenDate);
System.out.println(&quot;The Data Type of Given Date is ==&gt; &quot; + givenDate.getClass().getName());
System.out.println(&quot;The Converted Timestamp is ==&gt; &quot; + convertedDate);
System.out.println(&quot;The Data Type of the Converted Timestamp is ==&gt; &quot; + convertedDate.getClass().getName());
} catch (Exception excep) {
excep.printStackTrace();
}
  }
}
</pre></div>


<p>In the above code snippet,&nbsp;</p>



<ul class="wp-block-list">
<li>At the program&#8217;s start, we import the Timestamp class from the “java.sql” package.</li>



<li>In the main() method, we create a string-type variable and assign it a date value.</li>



<li>Up next, we invoke the valueOf() method on the given date string to convert it into a timestamp.</li>



<li>Finally, we print the given date and the converted timestamp (along with their corresponding data types) on the console:</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="717" height="136" src="http://javabeat.net/wp-content/uploads/2024/04/image-27.png" alt="" class="wp-image-188179" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-27.png 717w, https://javabeat.net/wp-content/uploads/2024/04/image-27-300x57.png 300w" sizes="(max-width: 717px) 100vw, 717px" /></figure>



<p>The output confirms that the valueOf() method successfully converted the given string to a timestamp.</p>



<h2 class="wp-block-heading">How to Format/Convert a Timestamp to a String in Java?</h2>



<p>The “Timestamp” class of the “java.sql” package offers a “toString()” method that retrieves a string representation of the timestamp in JDBC timestamp escape format. This method lets us convert a timestamp object into a string in Java:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.sql.Timestamp;
public class ExampleClass {
  public static void main(String&#x5B;] args) {
    try {
Timestamp givenTimestamp = Timestamp.valueOf(&quot;2021-04-11 01:12:12&quot;);
System.out.println(&quot;The Given Timestamp is ==&gt; &quot; + givenTimestamp);
System.out.println(&quot;The Data Type of Given Timestamp is ==&gt; &quot; + givenTimestamp.getClass().getName());

String convertedTimestamp = givenTimestamp.toString();
System.out.println(&quot;The Converted Timestamp is ==&gt; &quot; + convertedTimestamp);
System.out.println(&quot;The Data Type of the Converted Timestamp is ==&gt; &quot; + convertedTimestamp.getClass().getName());
} catch (Exception excep) {
excep.printStackTrace();
}
  }
}
</pre></div>


<p>In this example,</p>



<ul class="wp-block-list">
<li>We declare a timestamp using the valueOf() method and initialize it to a variable named “givenTimestamp”.</li>



<li>Also, we print the initialized timestamp and its data type on the console.</li>



<li>After this, we use the toString() method on the given timestamp to convert it into a string.</li>



<li>For verification purposes, we print the converted timestamp along with its data type on the console, as shown in the following screenshot:&nbsp;</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="736" height="146" src="http://javabeat.net/wp-content/uploads/2024/04/image-26.png" alt="" class="wp-image-188178" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-26.png 736w, https://javabeat.net/wp-content/uploads/2024/04/image-26-300x60.png 300w" sizes="(max-width: 736px) 100vw, 736px" /></figure>



<p>That’s all from converting a string to a timestamp in Java.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>To convert a string to a timestamp in Java, use the “parse()” or the “valueOf()” methods of the SimpleDateFormat and Timestamp classes, respectively. On the other hand, if you need to format/convert a timestamp object to a String, you can use the toString() method of the Timestamp class. In this tutorial, all these methods are explained with appropriate examples.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Write Data to a CSV File in Java</title>
		<link>https://javabeat.net/write-data-csv-file-in-java/</link>
		
		<dc:creator><![CDATA[Anees Asghar]]></dc:creator>
		<pubDate>Tue, 30 Apr 2024 12:29:50 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://javabeat.net/?p=188156</guid>

					<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>
<p>Use the built-in classes like FileWriter, PrintWriter, or BufferedWriter to write data to a CSV file in Java. Also, you can use some third-party libraries.</p>
]]></description>
										<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p>

<p>A “Comma-Separated Values or CSV” file simply stores data in a column-by-column format within a normal plain-text file and splits/separates it using a specified separator (typically a comma &#8216;,&#8217;). While working with file handling and file manipulation tasks, Java developers often come across a situation where they need to write data to a CSV file. In such situations, they can use different built-in classes and third-party libraries that will be discussed in this post with suitable examples.</p>



<p>This post illustrates how to write data to a CSV file in Java using Java FileWriter Class, Java PrintWriter Class, Java BufferedWriter Class, OpenCSV Library, and Apache Commons CSV library.</p>



<p>Let’s begin with the PrintWriter Class.</p>



<h2 class="wp-block-heading">1) Writing Data to a CSV File Using Java FileWriter Class</h2>



<p>The Java <a href="https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html">FileWriter</a> class belongs to the “java.io” package that lets us write character data to a file. Using this class we can easily write data to a CSV file, as shown in the following code:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.io.*;

public class WriteDataCSV {
public static void main(String&#x5B;] args) {
                    try {
FileWriter obj = new FileWriter(&quot;C:\\Users\\HP\\Desktop\\sampleFile.txt&quot;);
obj.write(&quot;empName, empDesig, empAge\n&quot;);
obj.write(&quot;Ambrose, Author, 25\n&quot;);
obj.write(&quot;Joseph, Designer, 27\n&quot;);
obj.write(&quot;Alexa, Tutor, 30\n&quot;);
obj.close();
} catch (IOException excep) {
excep.printStackTrace();
}
}
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>First, we import the required classes like FileWriter and <a href="https://javabeat.net/ioexception/">IOException</a> to write data to a CSV file by avoiding any potential exceptions.</li>



<li>We use the FIleWriter() constructor to specify the file’s path to which we want to write data.</li>



<li>After this, we invoke the write() method of the FileWriter class to write the data into the selected CSV class.</li>
</ul>



<p><strong>Output (sampleFile.txt)</strong></p>



<figure class="wp-block-image"><img decoding="async" width="668" height="191" src="http://javabeat.net/wp-content/uploads/2024/04/image-14.png" alt="" class="wp-image-188159" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-14.png 668w, https://javabeat.net/wp-content/uploads/2024/04/image-14-300x86.png 300w" sizes="(max-width: 668px) 100vw, 668px" /></figure>



<h2 class="wp-block-heading">2) Writing Data to a CSV File Using Java BufferedWriter Class</h2>



<p>The BufferedWriter is a built-in Java class that belongs to the same “io” package. This class lets us write text to a character-output stream with buffering. Using this class, you can write data to any CSV file:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.io.*;

public class WriteDataCSV {
public static void main(String&#x5B;] args) {
try {
BufferedWriter obj = new BufferedWriter(new FileWriter(&quot;C:\\Users\\HP\\Desktop\\sampleFile.txt&quot;));
obj.write(&quot;empName, empDesig, empSal\n&quot;);
obj.write(&quot;Ambrose, Author, 25000\n&quot;);
obj.write(&quot;Joseph, Designer, 25000\n&quot;);
obj.write(&quot;Alexa, Tutor, 30000\n&quot;);
obj.close();
} catch (IOException excep) {
excep.printStackTrace();
}
}
}
</pre></div>


<p><strong>Code Explanation:</strong></p>



<ul class="wp-block-list">
<li>In this example, we wrap the FileWriter() constructor within the BufferedWriter() constructor. While the FileWriter() constructor is initialized with the file path (to which the data will be written).</li>



<li>After this, we use the object of the BufferedWriter class to invoke the write() method to write the data to the CSV file</li>
</ul>



<p><strong>Output (sampleFile.txt)</strong></p>



<figure class="wp-block-image"><img decoding="async" width="676" height="206" src="http://javabeat.net/wp-content/uploads/2024/04/image-16.png" alt="" class="wp-image-188161" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-16.png 676w, https://javabeat.net/wp-content/uploads/2024/04/image-16-300x91.png 300w" sizes="(max-width: 676px) 100vw, 676px" /></figure>



<h2 class="wp-block-heading">3) Writing Data to a CSV File Using Java PrintWriter Class</h2>



<p>The PrintWriter is an in-built class of Java’s io package that helps us print the formatted representation of objects to a text-output stream. You can use this class to write data to a CSV file, as demonstrated in the following code:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.io.*;

public class WriteDataCSV {
public static void main(String&#x5B;] args) {
      try {
PrintWriter obj = new PrintWriter(new File(&quot;C:\\Users\\HP\\Desktop\\sampleFile.txt&quot;));
StringBuffer fileHeader = new StringBuffer(&quot;&quot;);
StringBuffer fileData = new StringBuffer(&quot;&quot;);

fileHeader.append( &quot;empName, empDesig, empSal\n&quot;);
obj.write(fileHeader.toString());

fileData.append(&quot;Ambrose&quot;);
fileData.append(&#039;,&#039;);
fileData.append(&quot;Tutor&quot;);
fileData.append(&#039;,&#039;);
fileData.append(&quot;25000&quot;);
fileData.append(&#039;\n&#039;);

fileData.append(&quot;Joseph&quot;);
fileData.append(&#039;,&#039;);
fileData.append(&quot;Designer&quot;);
fileData.append(&#039;,&#039;);
fileData.append(&quot;30000&quot;);
fileData.append(&#039;\n&#039;);

obj.write(fileData.toString());
obj.close();

} catch (FileNotFoundException excep) {
excep.printStackTrace();
}
    }
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>We use the PrintWriter() constructor along with the File() constructor to specify the file path to which we want to write the data.</li>



<li>Next, we create two objects of the StringBuffer class to store the file header and file’s data, respectively.</li>



<li>Next, we use the append() method to append the header line and the content of the file to the respective StringBuffer object.</li>



<li>Finally, the write() method is used to write the file header and the file content to the selected CSV file.</li>
</ul>



<p><strong>Output (sampleFile.txt)</strong></p>



<figure class="wp-block-image"><img decoding="async" width="679" height="181" src="http://javabeat.net/wp-content/uploads/2024/04/image-19.png" alt="" class="wp-image-188164" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-19.png 679w, https://javabeat.net/wp-content/uploads/2024/04/image-19-300x80.png 300w" sizes="(max-width: 679px) 100vw, 679px" /></figure>



<h2 class="wp-block-heading">4) Writing Data to a CSV File in Java Using OpenCSV</h2>



<p>It is a third-party library that can also be used to write data to a CSV file. To do that, first, add the given dependency to the xml file of your Maven project:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;com.opencsv&lt;/groupId&gt;
    &lt;artifactId&gt;opencsv&lt;/artifactId&gt;
    &lt;version&gt;5.9&lt;/version&gt;
&lt;/dependency&gt;
</pre></div>


<p>Once added, you can write data to a CSV file line-by-line or all data at once.</p>



<h3 class="wp-block-heading">Example 1: Writing Data to a CSV File Line-by-line Using OpenCSV</h3>



<p>In the following example, first, we import the CSVWrite class from the OpenCSV:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.io.*;
import com.opencsv.CSVWriter;

public class WriteDataCSV {
public static void main(String&#x5B;] args) {
    File fileObj = new File(&quot;C:\\Users\\HP\\Desktop\\sampleFile.txt&quot;);
    try {
FileWriter resultFile = new FileWriter(fileObj);
CSVWriter csvWriterObj = new CSVWriter(resultFile);
String&#x5B;] fileHeader = { &quot;empName&quot;, &quot;empDesig&quot;, &quot;empSal&quot; };
csvWriterObj.writeNext(fileHeader);
String&#x5B;] emp1 = { &quot;John&quot;, &quot;Tutor&quot;, &quot;35000&quot; };
csvWriterObj.writeNext(emp1);
String&#x5B;] emp2 = { &quot;Joseph&quot;, &quot;Instructor&quot;, &quot;35000&quot; };
csvWriterObj.writeNext(emp2);
String&#x5B;] emp3 = { &quot;Alex&quot;, &quot;Software Engineer&quot;, &quot;40000&quot; };
csvWriterObj.writeNext(emp3);
String&#x5B;] emp4 = { &quot;Seth&quot;, &quot;Designer&quot;, &quot;30000&quot; };
csvWriterObj.writeNext(emp4);
String&#x5B;] emp5 = { &quot;Ambrose&quot;, &quot;Instructor&quot;, &quot;35000&quot; };
csvWriterObj.writeNext(emp5);
System.out.println(&quot;Data Written to the CSV File Successfully&quot;);             csvWriterObj.close();
}
catch (IOException excep) {
              excep.printStackTrace();
}
}
}
</pre></div>


<p><strong>Code Explanation</strong></p>



<ul class="wp-block-list">
<li>First, we create an object of the FilerWriter class to write data to the selected CSV file.&nbsp;</li>



<li>Also, we create an object of the CSVWriter class to write the CSV formatted data to the selected CSV file.&nbsp;</li>



<li>Next, we define a string array to specify the column names(file header). We use the WriteNext() method to write the specified column names as the first row of the selected CSV file.</li>



<li>After this, we create multiple arrays to specify the data of different employees and invoke the writeNext() method on each array to write it to the CSV file.</li>
</ul>



<p><strong>Output (sampleFile.txt)</strong></p>



<figure class="wp-block-image"><img decoding="async" width="673" height="234" src="http://javabeat.net/wp-content/uploads/2024/04/image-18.png" alt="" class="wp-image-188163" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-18.png 673w, https://javabeat.net/wp-content/uploads/2024/04/image-18-300x104.png 300w" sizes="(max-width: 673px) 100vw, 673px" /></figure>



<h3 class="wp-block-heading">Example 2: Writing All Data at Once to a CSV File Using OpenCSV</h3>



<p>The following code demonstrates how to write all data at once to a CSV file using the OpenCSV library:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import com.opencsv.CSVWriter;import java.io.*;
import java.util.*;

public class WriteDataCSV {
public static void main(String&#x5B;] args) {
  File fileObj = new File(&quot;C:\\Users\\HP\\Desktop\\sampleFile.txt&quot;);
try {
        FileWriter resultFile = new FileWriter(fileObj);
        CSVWriter csvWriterObj = new CSVWriter(resultFile);
  List&lt;String&#x5B;]&gt; writeData = new ArrayList&lt;String&#x5B;]&gt;();
  writeData.add(new String&#x5B;] {&quot;empName&quot;, &quot;empDesig&quot;, &quot;empSal&quot;});
        writeData.add(new String&#x5B;] {&quot;John&quot;, &quot;Tutor&quot;, &quot;35000&quot;});
  writeData.add(new String&#x5B;] {&quot;Alex&quot;, &quot;Software Engineer&quot;, &quot;40000&quot;});
  writeData.add(new String&#x5B;] {&quot;Seth&quot;, &quot;Designer&quot;, &quot;30000&quot;});
  csvWriterObj.writeAll(writeData);
  csvWriterObj.close();
}
catch (IOException excep) {
  excep.printStackTrace();
}
}
}
</pre></div>


<p><strong>Output (sampleFile.txt)</strong></p>



<ul class="wp-block-list">
<li>In this example, we create a list of string arrays, and add them to a list named “writeData”.</li>



<li>After this, we invoke the writeAll() method to write all the data to the selected CSV file in one go (instead of writing it line-by-line).</li>
</ul>



<figure class="wp-block-image"><img decoding="async" width="679" height="215" src="http://javabeat.net/wp-content/uploads/2024/04/image-17.png" alt="" class="wp-image-188162" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-17.png 679w, https://javabeat.net/wp-content/uploads/2024/04/image-17-300x95.png 300w" sizes="(max-width: 679px) 100vw, 679px" /></figure>



<h2 class="wp-block-heading">5) Writing Data to a CSV File in Java Using Apache Commons CSV</h2>



<p>Apache Commons is another well-known third-party library that allows us to write data to a CSV file. However, to use Apache Commons, first, you must add the latest version of this library into the “pom.xml” file of your Maven project:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
    &lt;artifactId&gt;commons-csv&lt;/artifactId&gt;
    &lt;version&gt;1.10.0&lt;/version&gt;
&lt;/dependency&gt;
</pre></div>


<p>Once the library is added, import the CSVFormat and CSVPrinter classes to your Java program, as shown below:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class WriteDataCSV {
    public static void main(String&#x5B;] args){
try {
BufferedWriter resultFile = Files.newBufferedWriter(Paths.get(&quot;C:\\Users\\HP\\Desktop\\sampleFile.txt&quot;));
CSVPrinter csvPrinterObj = new CSVPrinter(resultFile,
CSVFormat.DEFAULT.withHeader(&quot;empName&quot;, &quot;empDesig&quot;, &quot;empSal&quot;));

csvPrinterObj.printRecord(&quot;John&quot;, &quot;Tutor&quot;, &quot;35000&quot;);
csvPrinterObj.printRecord(&quot;Alex&quot;, &quot;Software Engineer&quot;, &quot;40000&quot;);
csvPrinterObj.printRecord(&quot;Seth&quot;, &quot;Designer&quot;, &quot;30000&quot;);
csvPrinterObj.printRecord(Arrays.asList(&quot;Alexa&quot;, &quot;Jr. Software Engineer&quot;, &quot;30000&quot;));
csvPrinterObj.flush();
csvPrinterObj.close();
}
catch (IOException excep) {
excep.printStackTrace();
}
}
}
</pre></div>


<p><strong>Code Explanation:</strong></p>



<ul class="wp-block-list">
<li>After importing the required classes, we create a BufferedWriter to specify the file path.</li>



<li>Next, we create an object of the CSVPrint class to set the header line and content of the CSV file.</li>



<li>To set the header line we invoke the withHeader() method and specify the file’s content we use the printRecord() method.</li>



<li>Finally, we flush the buffer before closing the writer.</li>
</ul>



<p><strong>Output (sampleFile.txt)</strong></p>



<figure class="wp-block-image"><img decoding="async" width="677" height="214" src="http://javabeat.net/wp-content/uploads/2024/04/image-15.png" alt="" class="wp-image-188160" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-15.png 677w, https://javabeat.net/wp-content/uploads/2024/04/image-15-300x95.png 300w" sizes="(max-width: 677px) 100vw, 677px" /></figure>



<h2 class="wp-block-heading">How to Write/Append Data into an Existing CSV File in Java?</h2>



<p>To write data into an existing CSV file in Java, you must use a method that lets you append data into a file without overwriting the original content. For instance, you can use the FileWriter instance and specify the append mode as its second argument, as follows:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import java.io.*;

public class WriteDataCSV {
public static void main(String&#x5B;] args) {
try {
FileWriter obj = new FileWriter(&quot;C:\\Users\\HP\\Desktop\\sampleFile.txt&quot;, true);
obj.write(&quot;Ambrose, Author, 25\n&quot;);
obj.close();
} catch (IOException excep) {
excep.printStackTrace();
}
}
}
</pre></div>


<p><strong>Code Explanation:</strong></p>



<ul class="wp-block-list">
<li>We create a FileWriter object and initialize it with the targeted CSV file’s path.</li>



<li>We specify “true” as a second parameter to the FileWrite() method; this means the targeted CSV file will be open in “append” mode.</li>



<li>Finally, we use the write() method to append a new line to an already-existing file.</li>
</ul>



<p>The output demonstrates that this time a new line is appended(instead of overwriting) at the end of the selected file:<br></p>



<figure class="wp-block-image"><img decoding="async" width="678" height="218" src="http://javabeat.net/wp-content/uploads/2024/04/image-13.png" alt="" class="wp-image-188158" srcset="https://javabeat.net/wp-content/uploads/2024/04/image-13.png 678w, https://javabeat.net/wp-content/uploads/2024/04/image-13-300x96.png 300w" sizes="(max-width: 678px) 100vw, 678px" /></figure>



<p>That’s all about writing data to a CSV file in Java.</p>



<h2 class="wp-block-heading">Final Thoughts</h2>



<p>You can use different built-in classes like FileWriter, PrintWriter, or BufferedWriter to write data to a CSV file in Java. Besides these built-in classes, you can also use some third-party libraries like Apache Commons and OpenCSV to write data to a CSV file. Using OpenCSV, you can write data line-by-line or all data at once. All these methods allow you to write data to a CSV file conveniently and efficiently. To write data into an existing CSV file in Java, you must use a method that lets you append data into a file without overwriting the original content.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
