Loading...

Follow Java tutorial for beginners on Feedspot

Continue with Google
Continue with Facebook
or

Valid

In this post, we will see how to validate email address in java.

There are times when you have to validate email address provided by user. You might want to write your own logic to validate email addresses but there are lots of standard regular expressions or libraries which can help you validate email address and provide great results.

Email address is made up of local part, @ and followed by domains. You can go through wiki page for format of email address.

Using regular expressions

We can use regular expression provided by OWASP Validation Regex Repository which is considered to be safe and will solve the purpose in most of the cases.

Here is the regular expression

^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$

Here is complete java program for email address validation in java

package org.arpit.java2blog;

import java.util.regex.Pattern; 

public class EmailValidatorMain 
{ 
	public static boolean isValid(String email) 
	{ 
		String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@" +  //part before @
				"(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"; 

		Pattern pat = Pattern.compile(emailRegex); 
		if (email == null) 
			return false; 
		return pat.matcher(email).matches(); 
	} 

	/* driver function to check */
	public static void main(String[] args) 
	{ 
		String email1 = "admin@java2blog.com"; 
		String email2 = "@java2blog.com";
		String email3 = "arpit.mandliya@java2blog.com";
		String[] emails= {email1,email2,email3};

		for (int i = 0; i < emails.length; i++) {
			String email=emails[i];
			if (isValid(email)) 
				System.out.print(email+" is valid email"); 
			else
				System.out.print(email+" is invalid email"); 
			
			System.out.println();
		}
	} 
}

When you run above program, you will get below output

admin@java2blog.com is valid email
@java2blog.com is invalid email
arpit.mandliya@java2blog.com is valid email
Using apache common validator library

You can also use inbuilt apache librabry to validate the address. If you are using maven, then you need to add below dependency in your pom.xml.

<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.4.0</version>
</dependency>

Here is java program for the same.

package org.arpit.java2blog;

import org.apache.commons.validator.routines.EmailValidator;

public class EmailValidatorMain 
{ 
	public static boolean isValid(String email) 
	{ 
		// Get an EmailValidator instance first
		EmailValidator validator = EmailValidator.getInstance();

		// check valid email address
		if (!validator.isValid(email)) {
			return false;
		}
		return true;
	} 

	/* driver function to check */
	public static void main(String[] args) 
	{ 
		String email1 = "admin@java2blog.com"; 
		String email2 = "@java2blog.com";
		String email3 = "arpit.mandliya@java2blog.com";
		String[] emails= {email1,email2,email3};

		for (int i = 0; i < emails.length; i++) {
			String email=emails[i];
			if (isValid(email)) 
				System.out.print(email+" is valid email"); 
			else
				System.out.print(email+" is invalid email"); 

			System.out.println();
		}
	} 
}

When you run above program, you will get below output

admin@java2blog.com is valid email
@java2blog.com is invalid email
arpit.mandliya@java2blog.com is valid email

That’s all about validate email address in java.

The post Validate email address in java appeared first on Java2Blog.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post, we will see about Garbage Collection in java.

I will try to explain with the help of diagrams and examples rather than theory.

JVM Memory is divided into three parts

  • Young generation
  • Old generation
  • Metaspace (Perm Gen)
Young Generation

As the name suggests, young generation is the area where newly created objects are allocated.

  • When young generation fills up, it cause minor garbage collection aka Minor GC.
  • When minor Gcs occurs, dead objects will be removed from young generation.
  • If you have lot of dead objects in young generation, Minor GC will be perfomed faster.
  • All minor GCs are “stop the world” events, so when minor GCs occurs, application threads will also stop.

Let’s understand more about how objects are allocated in Young generation.

Young generation is divided into 3 parts.

  • Eden space
  • Survivor space S0
  • Survivor space S1

Here is illustration of the young and old generation.

    • All newly created objects are allocated in eden space.
    • When Eden space is completely filled with objects then minor GC will occur. All the objects which are not dead or unreferenced will be moved to one of the survivors spaces. In our case, let’s say all the objects are moved to S0.


    • When Eden space is filled again, then all the live objects in Eden space andSurvivor space S0 will be moved to Survivor space S1.


  • Once objects are survived multiple cycles of minor GC, they will be moved to old generation. You can control this threshold by MaxTenuringThreshold. The actual tenuring threshold is dynamically adjusted by JVM.

Let’s try to demonstrate this behavior with the help of example:
You have below class in which I am creating short-lived objects for demonstration.

package org.arpit.java2blog;

import java.math.BigDecimal;

public class GCCollectorExample {
	public static void main(String args[])
	{
		createObjects();
	}
	private static void createObjects() {

		long count = 0;
		
		while(true) { 
			// Creating short-lived objects just for illustration
			BigDecimal shortLivedBigDecimal1 = new BigDecimal(count++);
		}
	}
}

When you run the program. Let’s check memory allocation in Visual GC (A visualVM plugin)


As you can see, we have few objects in S0 and once eden space is completely filled, all referenced objects will be moved to S1.

Old generation
  • It is used to hold old long surviving objects
  • It is generally larger than the young generation.
  • When tenured space is completely filled(or predefined threshold) with objects then Major GC will occur. It will reclaim the memory and free up space.
  • Often, Major GCs are slower and less frequent than minor GC.

How can you use this information to optimize memory?
It depends on nature of application.
If you have lots of temporary objects then there will be lot of minor gc. You can provide arguments XX:NewRatio=1 to distribute 50% to young generation and 50% to old.
By default, NewRatio=2 hence young Generation is 1/3 of total heap.
Similarly, If you have too many long-lived objects, then you might need to increase size of tenure space by putting high value of NewRatio.

Why two survivor spaces?

You must be wondering why do we have 2 survivor space. We have 2 survivor spaces to avoid memory fragmentation. Each time you copy objects from eden to survivor and you get empty eden space and 1 empty survivor space.

Garbage Collection Algorithms

JVM comes with several algorithms for young and old generation. There are 3 types of algorithms

serial collector

It uses single thread to perform all the garbage collection and is suitable for basic application with single processor machines.

Parallel collector

It uses multiple CPUs to perform garbage collector. While serial collector uses 1 thread to perform GC, parallel GC uses several threads to perform GC and it is useful when there is enough memory and good number of cores.

Concurrent collector

Concurrent collector performs garbage collection with application threads. It is useful for applications which have medium to large datasets and require quick response time.

You can use different GC algorithms for young and old generations but you can pair only compatible algorithms.

For example: You can not pair Parallel Scavenge for young generation to Concurrent mark sweep for old as parallel scavenge does not provide synchronization which is required in CMS.

Here are garbage collectors which you can use for young and old generation.

Young Collector Old Collector JVM options  
Serial (DefNew) Serial Mark-Sweep-Compact -XX:+UseSerialGC
Parallel scavenge (PSYoungGen) Serial Mark-Sweep-Compact (PSOldGen) -XX:+UseParallelGC
Parallel scavenge (PSYoungGen) Parallel Mark-Sweep-Compact (ParOldGen) -XX:+UseParallelOldGC
Serial (DefNew) Concurrent Mark Sweep -XX:+UseConcMarkSweepGC 
-XX:-UseParNewGC
Parallel (ParNew) Concurrent Mark Sweep -XX:+UseConcMarkSweepGC 
-XX:+UseParNewGC
G1 -XX:+UseG1GC

There are a lot of changes in garbage collectors after Java 8, I will try to cover them in my next articles.

If you have any suggestions on this article, please comment.

The post Garbage Collection in java appeared first on Java2Blog.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post, we will see how to convert LocalDateTime to Date. Java 8 has introduced a lot of new APIs for Date and time.

There can be many ways to convert Java LocalDateTime to date.

Using Instant object

You can convert LocalDateTime to date using Instant object which we can from ZonedDateTime.Here is the code for the same.

Date convertLocalDateTimeToDateUsingInstant(LocalDateTime dateToConvert) {
    return java.util.Date
      .from(dateToConvert.atZone(ZoneId.systemDefault())
      .toInstant());
}

Using TimeStamp

This is easiest way to convert LocalDateTime to date in Java 8. We can use java.sql.Timestamp to convert LocalDateTime to Date.
The easiest way of getting a java.util.Date from LocalDateTime is to use an extension to the java.sql.Timestamp – available with Java 8:

public Date convertLocalDateTimeToDateUsingTimestamp(LocalDateTime dateToConvert) {
    return java.sql.Timestamp.valueOf(dateToConvert);
}

Here is complete program to convert between LocalDateTime to Date.

package org.arpit.java2blog;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class LocalDateTimeToDateMain {

	public static void main(String[] args) {
		LocalDateTime ldt = LocalDateTime.now();
		Date dt1=convertLocalDateTimeToDateUsingInstant(ldt);
		System.out.println(dt1);
		System.out.println("=====================");
		Date dt2=convertLocalDateTimeToDateUsingTimestamp(ldt);
		System.out.println(dt2);
	}

	public static Date convertLocalDateTimeToDateUsingInstant(LocalDateTime localDateTime) {
	    return Date
	      .from(localDateTime.atZone(ZoneId.systemDefault())
	      .toInstant());
	}
	
	public static Date convertLocalDateTimeToDateUsingTimestamp(LocalDateTime localDateTime) {
	    return Timestamp.valueOf(localDateTime);
	}
}

Output:

Sun Apr 14 00:47:05 IST 2019
=====================
2019-04-14 00:47:05.179772

That’s all about Java LocalDateTime to Date in Java 8.

The post Java LocalDateTime to Date appeared first on Java2Blog.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post, we will see about FileNotFoundException in java.

FileNotFoundException is thrown by constructors of FileInputStream, FileOutputStream, RandomAccessFile when file is not found on specified path. Exception can also be raised when file is inaccessible for some reason.For example: When you do not have proper permissions to read the files.

FileNotFoundException is checked exception so you need to handle by java code. You should take proper action to print appropriate exception to the user if FileNotFoundException is thrown.

Let’s understand with the help of example.

package org.arpit.java2blog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
 * FileNotFoundException example
 * @author Krishna
 *
 */
public class FileReadExample {
	public static void main(String[] args) {
		File file = new File("C:/Java2blog.txt");
		FileInputStream fis = null;
		try{
			fis = new FileInputStream(file);
			while (fis.read()!=-1){
				System.out.println(fis.read());
			}
		}catch (FileNotFoundException e){
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			try{
				fis.close();
			}catch (IOException e){
				e.printStackTrace();
			}
		}
	}
}

When you run above program, you will get below output:

java.io.FileNotFoundException: C:/Java2blog.txt (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:196)
at java.base/java.io.FileInputStream.(FileInputStream.java:139)
at org.arpit.java2blog.FileReadExample.main(FileReadExample.java:17)
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.FileReadExample.main(FileReadExample.java:27)

As you can see if file is not present in the path, we are getting FileNotFoundException.

How to resolve FileNotFoundException
  • Check if passed file is present in specified file
  • Check if passed file is actually directory
  • The passed file can not be open due to permission issues. You might be trying to write to file where as you only have read permission.
  • Check if passed file name does not contain any invisible characters such as \r\n symbols.

That’s all about FileNotFoundException in java.

The post FileNotFoundException in Java appeared first on Java2Blog.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post, we will see how to find Minimum Number of Jumps to reach last Index.

Problem

Given an array A of positive integers possibly zeroes, every index indicating the maximum length of a jump that can be made from this index. The length of a jump can vary from 1 to A[index].
If value on any index is zero, this means that you can not move forward from this index.
Find the minimum number of jumps required to reach the last index. If the answer is not possible for any case, print “Not Possible”.

Input :
int[] A = { 2, 3, 1, 1, 4 }
Output :
2

Input :
int[] A = { 2, 0, 0, 1, 4 }

Output :
Not Possible

Solution

APPROACH – I :
A basic brute force solution can be achieved by using a recursive approach and making calls to every possible reachable index from the current index.
Now, what does that mean?

  • We are given the array where each index contains the length of the maximum jumps that can be made from that index.
    For eg if A[i] = x, this means that from index ‘i’ we can jump to index  i+0,  i+1,  i+2 … i+x  and obviously only if these indices are in bounds.
  • Here making a call is equivalent to a jump for which we need to keep a jump variable in the function call and increment it in every recursive call made.
  • The base case condition will be, when the current index in the function call is eventually the end index. In the base case we compare the number of jumps made to reach this end index with the global minimum variable update it if the current number of jumps made to reach end index is less than the previously global minimum jump and return from the current call. If the current index becomes greater than the last index, then return from the current call as this is not the result we are looking for.

Steps:

  1. Start from index zero and initialize the number of jumps made variable to 0.
  2. Now for every index that is, in every call, start a loop from 1 to value at current index in the given array indicating the lengths of jump to be made in the next call. Make the function call with current index incremented by the length of jump and number of jumps by 1.
  3. When in base case, that is, when the current index in the call is equal to the last index, compare the number of jumps with the global min jumps variable, update it if the number of jumps made in this call is less than the previously global minimum jump and return from the current call.
    Here we will be using reactive recursive calls, so when the current index in the call is greater than the last index, we simply return from the call without doing any comparisons.

Time Complexity Discussion:
For an array of length n, at every index ‘i’ we are making A[i] jumps which in the worst case can be equal to n. Hence, there can be a total of ‘n’ potential calls from all the ‘n’ indices, therefore the worst time complexity of this solution is O(n^n).

package Backtracking;

public class minJumpsArr {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] A = { 2, 3, 1, 1, 4 };
		/*current index and number of jumps are zero initially*/
		solve(0, A, 0);
		
		if(minJumps == (int) 1e9 + 1)
		{
			/*if the min jumps is still infinity, this means it has
			 * never been updated that is, we did not reach the end
			 * index even once, hence answer is not possible in this
			 * case*/
			System.out.println("Not Possible");
		}
		else {
			System.out.println(minJumps);
		}

	}
	
	/* global min variable to store the minimum number of
	 * jumps required to reach last index.*/
	public static int minJumps = (int) 1e9 + 1;

	public static void solve(int currIdx, int[] a, int jumps) {
		/* base case : Case 1 - if current index is equal to last
		 * index (destination) update the global min jumps if the
		 * current number of jumps is lesser and return. 
		 * Case 2 - if current index is greater than the last index,
		 * simply return because this is not the result we are looking for*/
		if (currIdx >= a.length - 1) {
			if (currIdx == a.length - 1) {
				minJumps = Math.min(minJumps, jumps);
			}
			return;
		}
		/*maximum length of any jump that can be made from this index*/
		int reachableIdxs = a[currIdx];
		
		/* recursive calls for all lengths of jump varying from 1 to max
		 * length and incrementing number of jumps by 1 in every call */
		for (int jumpLength = 1; jumpLength <= reachableIdxs; jumpLength++) {
			solve(currIdx + jumpLength, a, jumps + 1);
		}
	}

APPROACH 2 :

In the above recursive solution, we can clearly see a lot of redundant calls, therefore for the reduction of the number of calls and eventually for reduced time complexity, we can use Dynamic programming approach.

  • For any index ‘i’ we can actually store the minimum number of jumps required to reach this index and then from here we can calculate the same for all the reachable indices from this index ‘i’ (‘reachable indices’ term is explained in the previous approach).
  • Now for any current index, the minimum number of jumps required to reach any ‘reachable index’ from start(‘0’ th index) is minimum jumps required to reach this current ‘i’th index from start(‘0’ th index) + 1 (to reach index ‘i+x’ directly from index ‘i’) , that is,
    minJumps[i+x] = minJumps[i] + 1
    Where, x can be 1, 2, 3…A[i]
  • Possibly We will be reaching the same index more than once with different number of jumps, but we want the minimum value, therefore, we update any minJumps[i] only if the current number of jumps required to reach ‘i’ is less then the current value at minJumps[i]

Time Complexity Discussion :
Again in this approach, from any index ‘i’ we are calculating minimum number of jumps of all the reachable indices by visiting all the reachable indices from any index, which can be ‘n’ in a worst case, and we are doing this for all n indices.
Therefore, the time complexity of this algorithm is O(n^2).

import java.util.Arrays;

public class minJumpsArr {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] A = { 2, 0, 1, 1, 4 };

		int ans = solveDP(A);
		if(ans == Integer.MAX_VALUE)
		{
			/* if the min jumps for the last index is still infinity,
			 * this means it has never been updated that is, we did
			 * not reach the end index even once, hence answer is not
			 * possible in this case*/
			System.out.println("Not Possible");
		}
		else {
			System.out.println(ans);
		}

	}

	public static int solveDP(int[] a) {
		int[] minJumps = new int[a.length];
		/*
		 * initialize min Jumps for every index to infinity
		 * as the minimum value is to  be calculated for
		 * every index
		 */
		Arrays.fill(minJumps, Integer.MAX_VALUE);
		/* minimum jumps required to reach the very first index is zero */
		minJumps[0] = 0;
		
		/*calculating min jumps for every index */
		for (int i = 0; i < a.length; i++) {
			/* maximum length of jump from this index or the maximum
			 * reachable index from this index*/
			int maxJump = a[i];
			for (int j = 1; j <= maxJump; j++) {
				/*visiting all the reachable index*/
				int reachableIdx = i + j;
				/* updating the minimum jumps required for every reachable
				 * index but only if the reachable index is in bounds and
				 * the intermediate index from which we are making jump to
				 * this reachable index must also be reachable from zeroth
				 * index*/
				if (reachableIdx < a.length && minJumps[i] != Integer.MAX_VALUE) {
					/* min jumps for every reachable index is min jumps for this
					 * intermediate index 'i' + 1 ( for the jump from intermediate
					 * index to this reachable index) */
				minJumps[reachableIdx] = Math.min(minJumps[reachableIdx], minJumps[i] + 1);
				}
			}
		}
		/*finally return the minimum jumps required to reach last index*/
		return minJumps[a.length-1];
	}

Before moving on to the next approach, just think if we could do better by using a greedy approach and making greedy coices for next index to jump on, rather than exploring all the possibilities using Dynamic programming.

Approach – III :
Yes we can definitely solve the given problem more efficiently by adopting a greedy approach.

  • The basic strategy would be to keep the track of Maximum reachable index the whole time which will eventually be updated frequently as we move through the given array and as soon as we reach this Maximum reachable index, we increment our number of jumps.
  • For this, we maintain 2 variables which stores the value of current index and Maximum reachable index. The very first thing we do after reaching any index is update the value of Maximum reachable index by comparing it with current Index + A[current Index] (indicating the maximum length of any jump that can be made from here) and we upadate Maximum reachable index value if value of current Index + A[current Index] is greater than Maximum reachable index. That is,

MaxReachable = max( MaxReachable,  current Index + A[current Index])

  • One point to reconsider is, What if after the updation of this Maximum reachable index its value is less than or equal to current Index?
    Well, this the case where we can not move from this current position and hence we can never reach the end index, therefore, in this case we simply return -1, indicating that no answer is possible in this case.

Now, we need to think about the correctness of our greedy approach again.

Can simply incrementing number of jumps when the value of current index is equal to max reachable index, always yield the correct answer everytime?

The answer would be a No, as max reachable index is getting updated and incremented by a value of A[current index] every time, this way value of current index can never be equal to max reachable index except for the case when the answer for a case isn’t possible.

  • For making our approach perfect, we can take another variable which keeps the track of current reachable index, and instead of incrementing the value of jump when current index is equal to Max reachable index, we will increment jump when the current Index becomes equal to current reachable, and at this moment we update the current reachable to max reachable index also.

Time Complexity Discussion :
We visit every index exactly once and keep updating the declared variables as we traverse the given array having ‘n’ elements. Therefore, the worst time complexity of this algorithm is O(n) where n is the size of the given array.

public class minJumpsArr {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] A = { 2, 3, 1, 1, 4 };
		
		int ans = jump(A);
		if(ans == -1)
		{
			System.out.println("Not Possible");
		}
		else {
			System.out.println("Minimum jumps required : " + ans);
		}

	}

	public static int jump(int[] a) {
		/*three variable as discussed in the editorial*/
		int maxReachable = 0;
		int jumps = 0;
		int currReachable = 0;
		/*exploring every index in the given array */
		for (int currIdx = 0; currIdx < a.length; currIdx++) {
			
			/*updating max reachable index every time we visit a new index*/
			maxReachable = Math.max(maxReachable, currIdx + a[currIdx]);
			
			/* as we have already considered the max jump length at this
			 * index and if max reachable index is still equal to or
			 * less than current index, then we can move forward from
			 * this index therefore answer is not possible in this case*/
			if (maxReachable <= currIdx) {
				return -1;
			}
			
			/*if current index is equal to the current reachable, increment
			 * jumps required and update current reachable*/
			if (currIdx == currReachable) {
				jumps++;
				currReachable = maxReachable;
			}
		}
		return jumps;
	}

That’s all about the Minimum Number of Jumps to reach last Index.

The post Minimum Number of Jumps to reach last Index appeared first on Java2Blog.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

If you are getting below error while running the Maven build.

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

There are 3 ways to solve this error.

Eclipse maven error

If you are getting this error, while doing maven build on eclipse then you must check if you re using JDK rather JRE in eclipse.

    • In eclipse, click on Window -> Prefererences -> Java -> Installed JREs
    • Verify that JDK is checked rather than JRE.

    • If JRE is checked, then you need to add JDK by clicking on Add -> Standard VM -> Next -> Directory and browse the JDK path

This will resolve error in eclipse.

Add executable in pom.xml

You can set fork to true and exectuable to fully qualified JDK path  in maven-compiler-plugin.

<build>
...
    <plugins>
    ...
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <fork>true</fork>
                <executable>C:\Program Files\Java\jdk1.8.0_45\bin\javac.exe</executable>
            </configuration>
        </plugin>
    </plugins>
</build>

Set JAVA_HOME to JDK

Go to System properties -> Advanced system settings -> Advanced -> environment variable and add JAVA_HOME to envrionment variable.

Reference: https://stackoverflow.com/questions/19655184/no-compiler-is-provided-in-this-environment-perhaps-you-are-running-on-a-jre-ra
I hope this will resolve the error.That’s all about No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

The post No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? appeared first on Java2Blog.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post, we will see about System.out.println in java and how it works.

Did you use system.out.println before? I think this is first statement every java developer compiles. It is generally called by the acronym “SOP”.

What is System.out.println?

System.out.println is Java statement which prints argument passed to console.

System is a class
out is static object of type PrintStream.
println is a method

Let’s go through more details.

System: System is class in the package “java.lang”.Since java.lang package is imported into in every program by default,so java.lang package does not require an explicit import statement.

out: out is static member of System class and is an instance of java.io.PrintStream.Internally out object is connected to standard output stream of operating system, so any argument passed to out object goes to OS output stream.

println: println is method of PrintStream class.This method is overloaded to print message to output which is generally console or file.

So you can imagine structure as below.

class System 
{
    public static PrintStream out;
    // other code
}

class PrintStream
{
    // method println
    public void println ..
    {
    }
    // other code
}

Does System.out.println impact performance?

Yes, System.out.println can impact performance if overused. When you call println, it internally calls write() and newLine(). Both write and newLine contain synchronized but have little overhead.

public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }

If multiple threads write at the same time, then performance can suffer but major cost is to add character to buffer and print them.

In any case, you should not have any System.out.println in the production environment.

That’s all about System.out.println in java.

The post System.out.println in java appeared first on Java2Blog.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post, we will see difference between Spring and Spring boot.

If you have followed spring project over time, you might have noticed it has become increasingly complex. If you want to create a spring application, you still need to put a lot of efforts. Spring boot is introduced to save time to bootstrap the spring projects. Spring boot is a way to create an application with zero or minimal configurations. It provides a lot of defaults and configuration to create Spring applications faster.

Spring framework

Spring framework is the most widely used Java framework for building application. Spring framework has a lot of projects to develop java application.

It has good features like dependency injection and modules such as

For example:

You can avoid a lot of boilder plate code with Spring JDBC rather than using Java’s JDBC APIs.

Spring boot

As already stated above, Spring boot helps you to create Spring projects faster by eliminating boilerplate configurations.

It takes an opinionated view of Spring platform to bootstrap application faster.

Here are some advantages of Spring boot

Advantages of Spring Boot
  • Spring provides a lot of default configurations which helps in bootstrapping spring application faster.
  • It comes with embedded tomcat or jetty server.
  • It reduces development time by avoiding a lot of boilerplate code.
  • It increases productivity as you can create Spring application quickly.
  • It provides a lot of starter project for easy maven integration. You don’t have to worry about version mismatch.
  • You can quickly create using sample project using spring boot initializer
Spring vs Spring boot

We will see how Spring boot can reduce your efforts to bootstrapping any spring application.

Let’s say you want to create a web application.

We need to declare DispatcherServlet in web.xml for spring MVC. When DisplatcherServlet is initialized, spring tries to load application context from [servlet name]-servet.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
   <display-name>Archetype Created Web Application</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   <servlet>
      <servlet-name>springmvc-dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>springmvc-dispatcher</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

Configuration in “springmvc-dispatcher-servlet.xml” to provide InternalResourceViewResolver.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
   <context:component-scan base-package="org.arpit.java2blog.springmvc.controller" />
   <bean >
      <property name="prefix">
         <value>/WEB-INF/</value>
      </property>
      <property name="suffix">
         <value>.jsp</value>
      </property>
   </bean>
   <mvc:annotation-driven />
</beans>

If you want to do same thing using Spring boot

spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp

All the Spring configuration will be automatically loaded by adding Spring boot starter and it will take care of all the default configurations.
If you want to do any customization, it is very easy to do with Spring boot.

That’s all about difference between Spring and Spring boot.

The post Difference between Spring and Spring boot appeared first on Java2Blog.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post, we will see how to convert a list to String in Python.

You can simply use string’s join method to convert a list to String in Python.

String’s join method

string’s join method return string in which element of the sequence is joined by separator.

sep.join(sequence)

Let’s see some examples.

Join all the strings in list without any separator
listOfChars = ["a" , "b", "c", "d", "e"] ''.join(listOfChars)

Output:

‘abcde’
Join all strings in list with space
listOfWords=["Hello", "world", "from", "java2blog"] ' '.join(listOfWords)

Output:

‘Hello world from java2blog’
Join all the strings in list with comma
listOfCountries=["India", "China", "Nepal", "France"] countries_str=','.join(listOfCountries) print(countries_str)

Output:

HIndia,China,Nepal,France
Convert list of ints to string in python

If you have list of ints, you can convert each item to string using map function.

list1 = [1, 2, 3, 4] str1 = ''.join(map(str, list1)) print(str1)

Output:

1234

That’s all about Python List to String.

The post Python List to String appeared first on Java2Blog.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post, we will see how to remove an element from list in python.

You can remove elements from list in 3 ways.

Using list object’s remove method

Here you need to specify element which you want to remove. If there are multiple occurrences of element, then first occurrence will be removed.

Please note that this is quite slow as it searches for element in the list and then remove the element by its value.
If the element is not present in the list, then it raises ValueError.

list1=["India", 1, "Nepal", 2,5,1,2,3,4,3,2] list1.remove(2) print(list1) list1.remove(9) print(list1)
[‘India’, 1, ‘Nepal’, 5, 1, 2, 3, 4, 3, 2]
—————————————————————————
ValueError Traceback (most recent call last)
in ()
3 print(list1)
4
—-> 5 list1.remove(9)
6 print(list1)

ValueError: list.remove(x): x not in list

Using list object’s pop method

This method takes index of element as input and remove it. It throws IndexError if index is out of range.

list1=["India", 1, "Nepal", 2,5,1,2,3,4,3,2] list1.pop(2) print(list1) list1.pop(14) print(list1)
[‘India’, 1, 2, 5, 1, 2, 3, 4, 3, 2]
—————————————————————————
IndexError Traceback (most recent call last)
in ()
3 print(list1)
4
—-> 5 list1.pop(14)
6 print(list1)

IndexError: pop index out of range

Using operator del

This operator takes index of element as a input and remove the element. del operator also supports removing range of elements from the list.This is clear and fast way of removing elements from the list.

list1=["India", 1, "Nepal", 2,5,1,"France",2,3,4,3,2] del list1[2] print(list1) del list1[4:7] print(list1)
[‘India’, 1, 2, 5, 1, ‘France’, 2, 3, 4, 3, 2]
[‘India’, 1, 2, 5, 3, 4, 3, 2]

That’s all about Python remove from list.

The post Remove from list Python appeared first on Java2Blog.

Read for later

Articles marked as Favorite are saved for later viewing.
close
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview