Sort numbers in Java to find minimum and maximum values without using Array

7 Comments


Recently a reader contacted me with a question about sorting numbers in Java. After sorting the number the program then needs to print the largest and smallest values. I have written a post earlier that shows one way of finding largest and smallest numbers. That approach used Arrays but the reader wanted to find largest and smallest values from a group of numbers without using Arrays. So here is another approach.

This program accepts input from the user and then prints out the largest and smallest numbers.



import java.util.*;
public class NumberSorter{
	public static void main(String args[]){
	  double a, b, c, x, y;
	  Scanner console = new Scanner(System.in);
	  System.out.print("Enter the first number: " );
	  a = console.nextDouble() ;
	  System.out.print("Enter the second number: " );
	  b  = console.nextDouble() ;
	  System.out.print("Enter the third number: " );
	  c = console.nextDouble();
	  x= Math.min(a, Math.min(b, c));
	  y= Math.max(a, Math.max(b, c));
	  System.out.println("\n" +x + " is the smallest number.\n" + y
	                     +" is the largest number.");
	}
}

Hope you find this useful. Share your ideas on how else can we find largest and smallest values from a group of numbers Java.

article clipper vert Sort numbers in Java to find minimum and maximum values without using Array
 

Java String comparison. The difference between == and equals().

24 Comments

javaString1 300x297 Java String comparison. The difference between == and equals().Many Java beginners find it difficult to differentiate between == operator and the “equals()” method when comparing String variables in Java. They assume that both operations perform the same function and either one can be used to compare two string variables. I have even seen many experienced programmers committing the mistake of using “==” to compare the values of two strings.

So what is the difference between “==” and “equals()” and what is the correct method of comparing two string variables?
More

article clipper vert Java String comparison. The difference between == and equals().
 

How to validate date using Java regular expression

7 Comments


My earlier post on how to validate email address, SSN and phone number validation using Java regex still attracts lot of visitors. Today I realized that another piece of data that many programmers need to validate is the date. Many Java applications have to process input date values, so I thought it will be beneficial to this blog readers to show how regular expression can be used to validate date in java.

First I’ll show you how to validate date using java reg ex in US format and later I’ll show you how that same logic can be applied to validate date in English format (used in most countries outside North America).
More

article clipper vert How to validate date using Java regular expression
 

Best way to check if a Java String is a number.

2 Comments

One of the routine tasks in many Java applications is to convert a string to a number. For instance, you may have a form where user submits his or her age. The input will come to your Java application as a String but if you need the age to do some calculation you need to convert that String into a number.
More

article clipper vert Best way to check if a Java String is a number.
 

Ultimate Java Regular Expression to validate any email address.

31 Comments

My post about Java regular expression gets a lot of hits daily. Someone commented that the regular expression I included in that post does not block certain invalid email addresses. So I updated the Java regular expression to validate email address. I am pretty sure that the following Java regular expression will validate any email address.

"^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";

More

article clipper vert  Ultimate Java Regular Expression to validate any email address.
 

How to configure multiple handlers in a Spring MVC web application

4 Comments


In Spring MVC, DispatcherServlet relies on handler mapping to determine which controller the request should be sent to. All handler mapping classes in Spring implement org.springframework.web.servlet.HandlerMapping interface. Spring distribution contains following four implementation of HandlerMapping interface.

  • BeanNameUrlHandlerMapping
  • SimpleUrlHandlerMapping
  • ControllerClassNameHandlerMappign
  • CommonsPathMapHandlerMapping

BeanNameUrlHandlerMapping is the simplest of all and DispatcherServlet looks for this mapping by default.

You can use any one of these handler mappings in your application by just configuring a bean in your application context file. For e.g; to use BeanNameUrlHandlerMapping you will have a bean declaration similar to



But can you use more than one handler mappings in an application? More

article clipper vert How to configure multiple handlers in a Spring MVC web application
 

Import static elements for more readable Java code

4 Comments

One of the welcome additions to Java language in Java 5 release is the static import declaration. static import works in the same way as traditional import declaration but it imports only the static members of a class.
Traditional import declaration looks like this
import java.util.*;
The above statement will import all the classes under java.util package.

The format of static import declaration is similar with the addition of keyword static. E.g;

import static java.lang.Math.*;

This statement will import all the static members of java.lang.Math class.

Similar to import declaration the static import offers two options. You can import all static members of a class or import only the members that you need in your program.

import static java.lang.Math.PI;
will import only PI.
import static java.lang.Math.*;
will import all static elements from Math class.
More

article clipper vert Import static elements for more readable Java code
 

Three ways to find minimum and maximum values in a Java array.

43 Comments

minmax Three ways to find minimum and maximum values in a Java array.

In Java you can find maximum or minimum value in a numeric array by looping through the array. Here is the code to do that.

public static int getMaxValue(int[] numbers){
  int maxValue = numbers[0];
  for(int i=1;i < numbers.length;i++){
    if(numbers[i] > maxValue){
	  maxValue = numbers[i];
	}
  }
  return maxValue;
}

public static int getMinValue(int[] numbers){
  int minValue = numbers[0];
  for(int i=1;i<numbers.length;i++){
    if(numbers[i] < minValue){
	  minValue = numbers[i];
	}
  }
  return minValue;
}

These are very straight forward methods to get maximum or minimum value of an array but there is a more cleaner way to do this. More

article clipper vert Three ways to find minimum and maximum values in a Java array.
 

How to read properties file in Java.

14 Comments

Reading properties file in Java is much easier than you might have thought. Following example illustrates one simple way of reading properties from a properties file.

Let’s say we need to read from myConfig.properties file.




The properties file has following entries.

Directory = C:/prodFiles/
NumberOfFiles = 25
Extension = java

Here is the java code to read the values of these keys.

import java.util.Properties;
import java.io.*;
public class ReadValues{
   private static final String PROP_FILE="myConfig.properties";
   public void readPropertiesFile(){
       try{
  	     InputStream is = ReadValues.class.getResourceAsStream(PROP_FILE);
	     Properties prop = new Properties();
             prop.load(is);
	     String directory = prop.getProperty("Directory");
             String numberOfFiles = prop.getProperty("NumberOfFiles");
	     String  fileExtension = prop.getProperty("Extension");
             is.close();
	  /* code to use values read from the file*/
       }catch(Exception e){
         System.out.println("Failed to read from " + PROP_FILE + " file.");
       }
   }
  }

The code is quite simple and self explanatory. Let me know if you have any questions.

article clipper vert How to read properties file in Java.
 

How to validate email, SSN, phone number in Java using Regular expressions.

38 Comments


email 300x225 How to validate email, SSN, phone number in Java using Regular expressions.

Email

Regular Expressions offer a concise and powerful search-and-replace mechanism.
They are patterns of characters used to perform search, extract or replace operations on the given text. Regular expressions can also be used to validate that the input conforms to a given format.

For example, we can use Regular Expression to check whether the user input is a valid Social Security number, a valid phone number or a valid email number, etc.
More

article clipper vert How to validate email, SSN, phone number in Java using Regular expressions.