Categories
java

convert int to String in java with example

In this post, we will learn to convert int to String in java with example

Even this is a simple post, But it is difficult to remember all syntax. We can easily convert int to String using valueOf() method

Syntax
String.valueOf(i);
Example
public class ConvertInttoString {

	public static void main(String[] args) {

		int i = 99;
		String stringValue = String.valueOf(i);
		System.out.println("Converted String " + stringValue);
	}

}
Output
Converted String 99
Related Articles

Convert String to lowercase using java

convert String to date in java with example

Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/ConvertInttoString.java

Categories
collections java

foreach in java8 using streams

In this tutorial, we will learn about foreach in java8 using streams

In java8, We can easily iterate a list using streams.

Streams API provided a lot of features. In this post, we are going to see about foreach

Syntax
stream().forEach({operations});
Example

import java.util.ArrayList;
import java.util.List;

public class ForEachExample {

	public static void main(String[] args) {
		try {

			List studentList = new ArrayList();
			Student student = null;

			student = new Student();
			student.setId(1);
			student.setName("Rajesh");
			student.setAddress("Mumbai");
			studentList.add(student);

			student = new Student();
			student.setId(1);
			student.setName("Kumar");
			student.setAddress("Chennai");
			studentList.add(student);

			studentList.stream()
					.forEach(x -> System.out.println("Name is " + x.getName() + " Address is " + x.getAddress()));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Student.java

public class Student {

	private int id;
	private String name;
	private String address;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}
Output
Name is Rajesh Address is Mumbai
Name is Kumar Address is Chennai
Related Article

sorting operations in java using streams

Iterate list using streams in java

Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/ForEachExampleUsingStreams.java

Categories
date java

compare two dates in java example

 

In this post, we will learn to compare two dates in java example

There are multiple ways to compare two dates in java.

In the First example we will learn to compare dates using compareTo() method

While using compareTo() method we are having 3 chances of output. Below are the possible output

0 – When both the dates are equal

1 – When date 1 is greater than date 2

-1 – When date 1 is lesser than date 2

Syntax
date1.compareTo(date2)
Example

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateCompareExample {
	public static void main(String[] args) {
		try {

			String date1 = "22/02/2020";
			String date2 = "21/02/2020";
			DateFormat format = new SimpleDateFormat("DD/MM/yyyy");
			Date dateObj1 = format.parse(date1);
			Date dateObj2 = format.parse(date2);

			// If Both the date are same comparTo Method will return 0
			if (dateObj1.compareTo(dateObj2) == 0) {
				System.out.println("Both the dates are Equal !!");
			} // If date1 greater than date 2 it will return 1
			else if (dateObj1.compareTo(dateObj2) > 0) {

				System.out.println("Date 1 is greater than date 2");
			} // If date1 lesser than date 2 it will return -1
			else {
				System.out.println("Date 1 is lesser than date 2");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Date 1 is greater than date 2

Using equals(),after(),before()

In the above example, we learned using compareTo() method. But we can compare dates using predefined functions also.

Below example is another way to compare two dates in java 

equals() – return true if both the dates are equal

after() – return true if date 1 greater than date 2

before() – return true if date 1 lesser than date 2

Example

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateCompareExample {
	public static void main(String[] args) {
		try {

			String date1 = "20/02/2020";
			String date2 = "21/02/2020";
			DateFormat format = new SimpleDateFormat("DD/MM/yyyy");
			Date dateObj1 = format.parse(date1);
			Date dateObj2 = format.parse(date2);

			// If Both the date are same comparTo Method will return 0
			if (dateObj1.equals(dateObj2)) {
				System.out.println("Both the dates are Equal !!");
			} // If date1 greater than date 2 it will return 1
			else if (dateObj1.after(dateObj2)) {

				System.out.println("Date 1 is after than date 2");
			} // If date1 lesser than date 2 it will return -1
			else if (dateObj1.before(dateObj2)) {
				System.out.println("Date 1 is before than date 2");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
Date 1 is before than date 2
Reference

https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#compareTo-java.util.Date-

Related Articles

convert String to date in java with example

Categories
date java

convert String to date in java with example

In this tutorial, we will learn to convert String to date in java with example.While we working with java this is one of the most scenario

We can easily convert String to Data using SimpleDateFormat.java. But before that we should know the date patterns which mentioned below 

Letter Component Presentation Examples
yYearYear1996; 96
MMonth in yearMonthJuly; Jul; 07
dDay in monthNumber10
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978

In this example we will convert 20/02/2020 to Date class 

Syntax
DateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY");
 simpleDateFormat.parse(dateString);
Example

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {

	public static void main(String[] args) {
		try {
			String dateString = "20/02/2020";
			DateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY");
			// Below line will convert from string to date
			Date parse = simpleDateFormat.parse(dateString);
			// The output will be like Sun Dec 29 00:00:00 IST 2019
			System.out.println(" Output :: "+parse);
		} catch (ParseException e) {
			e.printStackTrace();
		}

	}

}
Output
 Output :: Sun Dec 29 00:00:00 IST 2019
Reference

https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html

Download

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/SimpleDateFormatExample.java

Related Articles

print current date in java with example

compare two dates in java example

Categories
date java

add 3 days to the current date in java

In this post we will learn to add 3 days to the current date in java
While we working with dates we will come up with adding or subtracting from the current date

In Java there are lot of method for Date. So it is little bit difficult to remember all the things.

In this example we used Calendar.java and Date.java from java.util package
In below example we added 3 days

Syntax
object.add(Calendar.DAY_OF_YEAR, 1)
Example
import java.util.Calendar;
import java.util.Date;

public class AddDaysToDate {

	public static void main(String[] args) {
		try {
			Calendar calender = Calendar.getInstance();
			Date beforeAdding = calender.getTime();
			System.out.println("Printing the value before adding date ::: " + beforeAdding);

			// Adding the 3 days below
			calender.add(Calendar.DAY_OF_YEAR, 3);
			Date afterAdding = calender.getTime();
			System.out.println("Printing the value after adding date  ::: " + afterAdding);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Printing the value before adding date ::: Thu Feb 13 17:00:21 IST 2020
Printing the value after adding date  ::: Sun Feb 16 17:00:21 IST 2020
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/AddDaysToDate.java

Related Articles

convert String to date in java with example

compare two dates in java example

 

Categories
collections java

sorting operations in java using streams

In this example, we learn sorting operations in java using streams

In Java 8 it is easy to sort records from an arraylist

Streams API providing powerful features to sort the records from a list without modifying it

This will returns a stream consisting of the sorted elements

Syntax

Stream sorted()
list.stream().sorted({operations});

Ascending Example

import java.util.ArrayList;
import java.util.List;

public class AscendingSortingStreams {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Ball");
        list.add("Apple");
        list.add("Cat"); // printitng values before sorting
        System.out.println("Values before sorting ");
        list.stream().forEach(x -> System.out.println(x));
        System.out.println("*** Values After sorting ***");
        list.stream().sorted().forEach(x -> System.out.println(x));
    }
}

Output

Values before sorting 
Ball
Apple
Cat
*** Values After  sorting ***
Apple
Ball
Cat

Descending Example

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class DescendingSortingStreams {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Ball");
        list.add("Apple");
        list.add("Cat");
        // printitng values before sorting
        System.out.println("Values before sorting ");
        list.stream().forEach(x -> System.out.println(x));
        System.out.println("*** Values After sorting ***");
        // Comparator.reverseOrder() will sort the records in descending order
        list.stream().sorted(Comparator.reverseOrder()).forEach(x -> System.out.println(x));
    }
}

Output

Values before sorting 
Ball
Apple
Cat
*** Values After  sorting ***
Cat
Ball
Apple

References

Oracle Docs

Related Articles

filter operations in streams on java 

Iterate list using streams in java

Categories
java maven

Create a Maven Project using command prompt

In this tutorial we will learn to create a maven project using command prompt 

Prerequisites
Syntax
mvn archetype:generate -DgroupId= -DartifactId= -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Sample
mvn archetype:generate -DgroupId=com.beginnergsbug -DartifactId=sample-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Output

C:\Users\USHA RAJESH\Desktop\sample>mvn archetype:generate -DgroupId=com.beginnergsbug -DartifactId=sample-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.0.1:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.0.1:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO]
[INFO] --- maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom (703 B at 1.5 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-bundles/2/maven-archetype-bundles-2.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-bundles/2/maven-archetype-bundles-2.pom (1.5 kB at 3.5 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetype/maven-archetype-parent/1/maven-archetype-parent-1.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetype/maven-archetype-parent/1/maven-archetype-parent-1.pom (1.3 kB at 2.9 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar (4.3 kB at 7.6 kB/s)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\Users\USHA RAJESH\Desktop\sample
[INFO] Parameter: package, Value: com.beginnergsbug
[INFO] Parameter: groupId, Value: com.beginnergsbug
[INFO] Parameter: artifactId, Value: sample-project
[INFO] Parameter: packageName, Value: com.beginnergsbug
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\Users\USHA RAJESH\Desktop\sample\sample-project
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  12.855 s
[INFO] Finished at: 2020-01-31T09:17:42+05:30
[INFO] ------------------------------------------------------------------------

C:\Users\USHA RAJESH\Desktop\sample>     
Syntax Explanation

mvn maven base command

archetype:generate= to generate a maven project

-DgroupId= group id for the project

-DartifactId= artifact id it is similar to project name

-DarchetypeArtifactId= type of archetype

-DinteractiveMode= true/false 

Related Articles

How to install Apache Maven in windows

Categories
java maven

Set Maven Home in Windows

In this tutorial we will learn to set Maven home in windows.

Please refer my previous tutorial to download and install maven.

This is the follow up tutorial of my previous post

Prerequisites

Step 1

Copy Maven installed Path

In my case it is C:\Maven\apache-maven-3.6.3

Apache Maven Home

Step 2

Open My computer 

Step 3

Right click the This PC

Step 4

Click on Properties

Step 5

Click on Advanced system settings

Step 6

Click on the Environment variables

Step 7

Click New on the System variables column

Step 8

Enter Variable name as M2_HOME
Enter Variable value as C:\Maven\apache-maven-3.6.3
click ok
Note :
Variable name should be CAPS
Variable value should be as your maven installed path
don’t copy until bin folder

M2_HOME

Step 9

After Click OK
we can see the M2_HOME variable in environment variables

Step 10

After Click OK
we can see the M2_HOME variable in environment variables

Step 11

Now we need to need to add this JAVA_HOME to Path variable
Search for Path variable in same system variables window

Step 12

After selecting Path variable
Click on Edit button

Step 13

Edit environment variable dialog box will appear
Click on the New button

Step 14

Text box will appear on the list
add %M2_HOME%\bin in the text box

Step 15

Click OK after adding %M2_HOME%\bin
Now close all the windows

Step 16

We can verify by below steps
open the command prompt
type mvn -version

mvn -version

That’s it !! 

Related Articles

Create a Maven Project using command prompt

Categories
java maven

How to install Apache Maven in windows

In this tutorial we will learn about install apache maven in windows operating system

Maven is a software project management tool like gradle
maintaining by Apache 

If you are new to maven then below points will help you to understand maven

  • It is one of the easiest way to create a Java project
  • Easy to manage the dependencies (external jars)
  • Easy to build a jar or war
  • The project size will be so less

pom.xml

pom stands for Project Object Model
pom.xml is the heart of a maven project
It is a xml file which will have all dependency and build details for that project 

Prerequisites

Step 1

Download apache maven binary zip version from below URL 
http://apachemirror.wuchna.com/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.zip

Step 2

After downloading zip file.

Extract and place in some folder

In this example I am creating Maven folder on C: Directory of my windows Operating system

The folder path is like C:\Maven\apache-maven-3.6.3

Apache Maven Home

That’s it !! 

We installed Apache maven in windows. Please follow next tutorial to setup maven home 

We can use mvn command only if we have JAVA_HOME and M2_HOME in environment variables

Refer this tutorial to set M2_HOME 
https://beginnersbug.com/set-maven-home-in-windows/

if not we will face below exceptions

The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE
'mvn' is not recognized as an internal or external command,
operable program or batch file.
Related Articles

Set Maven Home in Windows

Create a Maven Project using command prompt

Categories
java

Run shell script from java with Example

In this example we will learn to run bash command and invoking a shell script file from java 
Java is provided a feature to execute shell script from code 
Runtime.getRuntime().exec(“”)
Above line will help us to execute bash command from java code 
we need to provide the shell script inside the exec method 

Printing Hostname from java

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ShellScriptExample {

	public static void main(String[] args) {
		try {

			Process exec = Runtime.getRuntime().exec("hostname");
			//below line will wait to execute the command
			exec.waitFor();
			BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
DESKTOP-U9R6O19
Printing Ip address from Java

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ShellScriptExample {

	public static void main(String[] args) {
		try {

			Process exec = Runtime.getRuntime().exec("ipconfig");
			//below line will wait to execute the command
			exec.waitFor();
			BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

Windows IP Configuration


Ethernet adapter Ethernet:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : 

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . : 
   Link-local IPv6 Address . . . . . : fe80::dc21:c38b:f5cb:e4e2%17
   IPv4 Address. . . . . . . . . . . : ***
   Subnet Mask . . . . . . . . . . . : ****
   Default Gateway . . . . . . . . . : ***
                                       192.168.1.1

Ethernet adapter vEthernet (Default Switch):

   Connection-specific DNS Suffix  . : 
   Link-local IPv6 Address . . . . . : fe80::1859:16f5:8d15:fd81%20
   IPv4 Address. . . . . . . . . . . : ***
   Subnet Mask . . . . . . . . . . . : **
   Default Gateway . . . . . . . . . : 
Invoking Shell file from Java

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class InvokingShellFileExample {

	public static void main(String[] args) {
		try {

			Process exec = Runtime.getRuntime().exec("C://script//shellscript.bat");
			// below line will wait to execute the command
			exec.waitFor();
			BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
Output
F:\BeginnersBug\BegineersBug>hostname
DESKTOP-U9R6O19
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/ShellScriptExample.java

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/InvokingShellFileExample.java