[Java] How To Check if a String is a Valid Number?

If you are someone new to Java and would like to check if a String is a valid number or not, this post will help you get answer to your question.

Below is the coded snippet with explanation for checking out if a string is a valid number. The below mentioned code is written in Java.

In the below mentioned code snippet, i declared an integer called isThisANumber , this integer will be used to save the parsed Integer. Static method parseInt( ) of the Integer class has been used to attempt to convert the string parameter into an Integer. In case if the string is not a valid integer and throws up parsing issues while converting, NumberFormatException is thrown.

int isThisANumber = 0;
try
{
isThisANumber = Integer.parseInt(someStringToTest); 
}
catch (NumberFormatException nfe)
{
System.out.println("This string is not a valid number."); //Oops..not a valid int
}

 

You can also follow me on Twitter at http://twitter.com/vaibhav1981

Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.

Will you use Google App Engine with Java Support?

On a poll being run on Technofriends earlier, 70% voters said they will use Google App engine once it has Java support enabled. 

Do you use Google App Engine

Poll Results: Do you use Google App Engine

Out of 251 total votes casted, 178 votes were polled for the option which said ” I plan to use it when Java Support is Enabled.” 

Seems like we have interesting times coming with Java support for Google App Engine already announced.

Thanks to all the readers who took some time out for casting their valuable votes. The poll is still open and if you wish to cast your votes, please do so by selecting one of the options ( see below).

You can follow me on Twitter at http://twitter.com/vaibhav1981

Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.

Cheers

Vaibhav Pandey


Google App Engine to Support Java

At the recently concluded Google Developers Day in Bangalore, Keynote speaker Prasad Ram said that Google App Engine will now support Java. Earlier, Google had announced the support of HTTPS on Google App Engine

Google App Engine right now supports Python.In my honest opinion, Giving support for Java must be one of the hardest for Google because of the heavyweight runtime and the difficulty in separating code. On the strategic front, it definitely makes sense. 

As of now, Google uses Python, Java, JavaScript and C++ for their applications (anything else for prototypes).Therefore supporting Java, also bringing JavaScript with it via Rhino, is very likely the next step.In any case, Google App Engine does provide the missing piece to the existing Google Puzzle, answering the most often asked question “How will Google grow when Adwords stops growing up at the same rate?”.

Seems like we can see the puzzle getting solved soon 🙂

For those of you who are new to Google App Engine, the below embedded video should help

Also read: [Video] Google for Webmasters Tutorial

You can also follow me on Twitter at http://twitter.com/vaibhav1981

Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.

Cheers

Vaibhav

[Java] Reading a Webpage through URL

Most of the applications written these days require some or the other network feature. Stand-alone Java applications are rare occurence these days. In order to write a Java program which reads a Webpage, follow the steps mentioned below.

1.) Instantiate a URL object by passing the URL string to its constructor. [Line 16 in the code below]

2.) Retrieve a URLConnection object . [ Line 17 in the code below]

3.) Get an input stream from the connection. [Line 18-20 in the code below]

4.) Create a BufferedReader on the input stream and read from it. [Line 23-25 in the code below]

In the code mentioned below, i have tried reading http://technofriends.in

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testapplicationsfortechnofriends;
import java.net.*;
import java.io.*;
/**
 *
 * @author Vaibhav
 */
public class ReadURL {

 public static void main(String[] args) throws Exception {
 URL url = new URL("http://technofriends.in");
 URLConnection tf = url.openConnection();
 BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                tf.getInputStream()));
 String inputLine;

 while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}

Also read:[How-To] Print Date/Time in a Given Format in Java

Understanding Polymorphism in Java : Part 1

Understanding Polymorphism in Java : Part 2

What is the difference between JDK and JRE?

An introduction to JDBC Drivers

You can follow me on Twitter at http://twitter.com/vaibhav1981

Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.

Cheers

Vaibhav

[How-To] Print Date/Time in a Given Format in Java

Often, we wish to Format the Date and Time information into a given format, either for displaying the same to the end user or for further processing. Java contains formatting classes which can be used to format a date into a desired format. The most commonly used class for formatting dates is the SimpleDateFormat class.

The SimpleDateFormat class takes format string as input to its constructor and returns a format object which can then be used to format Date objects. Calling the format() method of the SimpleDateFormat object will return a string that contains the formatted representation of the Date that is passed into the method as a parameter.

The table below contains Time and Date Format Codes which can be used to format the Date Object.

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800

Lets try understanding this better using this code example. The code below formats today’s date.

package testapplicationsfortechnofriends;
import java.util.Date;
import java.text.SimpleDateFormat;
/**
*
* @author Vaibhav
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Date todaysDate = new java.util.Date();
SimpleDateFormat formatter = new SimpleDateFormat(“EEE, dd-MMM-yyyy HH:mm:ss”);

String formattedDate = formatter.format(todaysDate);
System.out.println(“Today’s date and Time is:”+formattedDate);

}

}

Running this program, gives the following output

Today’s date and Time is:Thu, 01-May-2008 14:39:45

For further information on this, follow the Sun Java Documentation on DateFormat and SImpleDateFormat class.

Also read:Understanding Polymorphism in Java : Part 1

Understanding Polymorphism in Java : Part 2

What is the difference between JDK and JRE?

An introduction to JDBC Drivers

You can follow me on Twitter at http://twitter.com/vaibhav1981

Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.

Cheers

Vaibhav

[Java] Why (and how) to comment your code

Although this is primarily a post centered around Programming but because I happen to be a student of Java, I shall be talking about code commenting in Java.

We started with Java posts last year with the post titled What is the difference between JDK and JRE? . As is clear from the title of the post, this particular blogpost described the difference between JDK and JRE and then in the series of posts like Write a Java Application without a main() method which explained the trick of writing a program without a main method ( though this certainly is not useful from a production perspective) and How do I declare a constant in Java which explained the process of declaring a constant in Java.

Later during the last year, we also learnt about the lifecycle of a Java program in the post Java: Lifecycle of a Java Program. What can a programming language be without support for Database operation and that is when we talked about JDBC Drivers in the post JDBC Drivers:What are they?.

Lastly, we even talked about Polymorphism in Java in the posts titled Polymorphism in Java : Part 1 and Polymorphism in Java : Part 2. And now, the time is ripe to talk about Comments in Java; The most important yet often ignored element of coding.

There are three types of comments in Java:
– single line comments start with //, and end when the line ends
– multi line comments start with /* and end with */
– JavaDoc comments start with /** and end with /*

Now this was about How to comment the code in Java. Lets now try shifting our focus a little towards the Why part of the topic… Why to comment your code?

Stan James, a Javaranch forum member has a view against commenting the code. He says

If you’re tempted to put a comment on a method or in the middle of a method to explain what the next few lines do, stop and make the code tell the story. Small methods with great names make all the difference.

Many of the developers and other coding engineers i know don’t agree with Stan. Their point against this argument, is, in Programming Comments are not only for explaining what the code is all about but also to make it more understandable, more approachable and make the reader of the code understand the reason for applying the particular logic in the code.

Kelvin, another JavaRanch forum member says

Comments aren’t just for explaining how code works, though. I use comments mainly to explain why I decided to implement a feature or algorithm a particular way. This is especially useful in situations where there’s an “obvious” way of doing things that actually turns out to have serious but subtle flaws. If I don’t put a comment next to the code in question, it’s quite possible that some future zealous but inexperienced programmer will attempt to “optimize” my code using the flawed implementation approach.

I particularly like this post from J.Timothy King’s blog where he talks about Bad Writing and Poor Programming skills. Timothy in his blog gives an example

Here’s a snippet of code from a well funded, closed-source system that has been deployed in production for years. I’ve tweaked it a little, but only to make it more readable. This codebase gave me a migrane and almost made me lose my temper. (Seriously, it did.) I also know who wrote this. He was a senior developer, who had been programming at least as long as I. But as it turns out, in conversation, I never knew what he was talking about without questioning him in detail. Do communication skills reflect programming skills?

float _x = abs(x – deviceInfo->position.x) / scale;
int directionCode;
if (0 < _x && x != deviceInfo->position.x) {
if (0 > x – deviceInfo->position.x) {
directionCode = 0×04 /*left*/;
} else if (0 < x – deviceInfo->position.x) {
directionCode = 0×02 /*right*/;
}
}

This is equivalent to the following, more readable code. Except the following actually initializes directionCode in all cases. (The above code has a bug, which the following code fixes.)

static const int DIRECTIONCODE_RIGHT = 0x02;
static const int DIRECTIONCODE_LEFT = 0x04;
static const int DIRECTIONCODE_NONE = 0x00;

int oldX = deviceInfo->position.x;
int directionCode
= (x > oldX)? DIRECTIONCODE_RIGHT
: (x < oldX)? DIRECTIONCODE_LEFT
: DIRECTIONCODE_NONE;

Note that more comments does not mean more readable code. It didn’t in this example. The comments in the snippet above (if you even noticed them) only clutter the code even more. Sometimes fewer comments makes for more readable code. Especially if it forces you to use meaningful symbol names instead.

Therefore we can conclude that Comments can certainly never be replaced by code alone, however, the best approach seems to be the one wherein we ( as programmers) go back and refactor our code and then again, if the need be, add comments.

Do share your opinion on this and also your style of commenting.

Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.

Cheers
Vaibhav

Google Code University: Learn programming the Google way

Google Code University website contains courses on topics like Ajax, Distributed Systems, Web Security and languages like C++, Java and Python.

Google Logo

Google Code University website provides tutorials and sample course content. Using this content students and educators can learn more about current computing technologies. In particular, this content is Creative Commons licensed which makes it easy for Computer Science educators to use in their own classes.

There is also a section called CS Curriculum Search which lets a user find teaching materials which have been published to the web by the faculty from Computer Science departments around the world. The search can further be refined to display just the lectures, assignments or reference materials from a set of courses.

The Tools101 section contains tutorials about Databases, MySQL and also concepts like Software Configuration Management.

Go ahead and check it out by clicking here.

Also read:

Got 15 minutes? Give Ruby a shot right now!

What are JOINS in Database?

How-To: Create Basic Charts using Microsoft Excel

Top 5 Tutorials on Ruby on Rails

How not to get Phished,Learn from Phil the Fish

Do you store your passwords using Firefox?

Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.

Cheers

Vaibhav

Java: Lets revisit the past

Some Java posts which i wrote in the past which still attract lots of readers.

Java
  • Java: Lifecycle of a Java Program: This post talks about the Lifecycle of a Java program.It talks about the various stages a program goes through, right from the time its developed to the time its deployed.
  • Polymorphism in Java : Part 1: When i started understanding Polymorphism, one sentence that many people ( infact my college profs) told me was it refers to One Object, many forms. I could never understand this till i actually starting giving it a serious thought ( and that was some years later). Today, here at Technofriends blog, I would like to share my knowledge on Polymorphism and how it is implemented in Java.
  • Polymorphism in Java : Part 2: After having understood the basics of Polymorphism and what it actually refers to in my previous post, now lets get on and try understanding Method Overloading in a little more detailed fashion.

Updated Android SDK is now available

Android

Android Developers Blog author Jason Chen reports writes about the availability of the new Android SDK which is called m5-rc14. The new version will therefore be called as Android SDK m5-rc14.

Google Phone

Following are the changes to the m5-rc14 edition:

  • New user interface
  • Layout animations
  • Geo-coding
  • New media codecs
  • Updated Eclipse plug-in

Read on the entire story at the Android Developer’s blog here
Also read:

What is Google Android?

ARM may show Google phone prototype next week

Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.

Cheers

Vaibhav

From the Archives

This post is primarily an attempt to bring out 5 posts from the Archives. The posts listed here have been popular with the readers since the time they got published. Hope you will enjoy reading/ glancing through them again.

From the Archives
  • Microsoft Windows: More fun with the HOSTS file : In this post, i have tried to describe a few more ways of having fun with the Hosts file. The post talks about blocking websites using Hosts file and also about interchanging the websites getting loaded using Hosts file.
  • Microsoft Windows: How to Process Idle Tasks : This post describes a way to process idle tasks in Microsoft Windows. It kills the threads associated with the tasks already closed and therefore gives you a better performing PC.
  • Open DNS: A big DNS Cache : This post talks about OpenDNS which is a free, faster, secure and reliable DNS service. Read this post, to get a faster and safer internet experience.

Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.

Cheers

Vaibhav