Wednesday, September 23, 2009

Convert Celsius to Fahrenheit Java Code

The Java Code discussed today at Java Code Online deals with conversion of temperature from Celsius or Centigrade to Fahrenheit. The temperature conversions are required normally many times in our daily purposes. Like the body temperature in degree Fahrenheit and degree Celsius.

The only meeting point of these two temperature scales is -40 degree. At this temperature both the Celsius and the Fahrenheit scales are equal.

The Java code for this temperature conversion from Celsius to Fahrenheit is given below. The code requests the user to enter a temperature value in Celsius, and then displays the equivalent Fahrenheit Temperature.

/////////////////////////////////
package developer;

import java.util.Scanner;

public class CelsiusToFahrenheit {

    public static void main(String[] args) {

        System.out.println("Enter a temperature in Celsius: ");
        Scanner scanCelsius = new Scanner(System.in);
        double Fahrenheit = 0;

        if (scanCelsius.hasNextDouble())
        {
            Fahrenheit = (scanCelsius.nextDouble()*9) / 5 + 32;
        }
        System.out.println("The temperature in Fahrenheit is: " + Fahrenheit);
    }
}
/////////////////////////////////

When this Java Code was executed on my JVM, then the output was as shown below.

/////////////////////////////////
Enter a temperature in Celsius:
102.87
The temperature in Fahrenheit is: 217.166
/////////////////////////////////

Hope that the Java code provide for conversion from Celsius to Fahrenheit was beneficial to all. Keep checking Java Code Online for more Java updates and codes.

Related Java Code
Java Code to convert Fahrenheit to Celsius

Tuesday, September 22, 2009

Convert Fahrenheit to Celsius Java Code

Java Code Online has come up with a new Java Program, and that is for converting a temperature from Fahrenheit to Celsius or Centigrade. Fahrenheit and Celsius are the two main scales used for temperature measurement. The temperature of the normal human body is 98.4 degree Fahrenheit or 36.88 degree Celsius.

So temperature conversion is used normally in daily life. The only place where Fahrenheit and Celsius scales meet is at the temperature of -40 degree. That is to say that -40 degree Fahrenheit is equal to -40 degree Celsius.

The Java code for this temperature conversion from Fahrenheit to Celsius is given below. the code starts by asking the user to enter a temperature in Fahrenheit scale and then displays the equivalent Celsius Temperature.

/////////////////////////////////
package developer;

import java.util.Scanner;

public class FahrenheitToCelsius {

    public static void main(String[] args) {
        System.out.println("Enter a temperature in Fahrenheit: ");
        Scanner scanFaren = new Scanner(System.in);
        double Celsius = 0;
      
        if(scanFaren.hasNextDouble())
        {
            Celsius = (scanFaren.nextDouble() - 32)*5/9;
        }
        System.out.println("The temperature in Celsius is: "+Celsius);
      
    }
}
/////////////////////////////////

When this Java Code was executed on my JVM, then the output was as shown below.

/////////////////////////////////
Enter a temperature in Fahrenheit:
56
The temperature in Celsius is: 13.333333333333334
/////////////////////////////////

Hope that the Java code provide for conversion from Fahrenheit to Celsius was useful to you all. Java Code Online will soon be back with another important Java Code.

Related Java Code:-
Java Code to convert Celsius to Fahrenheit

Java Code to Convert Binary to Decimal

Java has deal with many different situations. So Java Code Online is going to discuss a case when a number entered as binary is to be converted to a decimal number. A binary number which consists of only 1 and 0, while a decimal number is a number which consists of numbers between 0-9.

We normally use decimal numbers in our daily purposes. Binary numbers on the other hand are very important and used for computers data transfer.

The Java code for converting a binary number to a decimal number, starts by asking the user to enter a binary number. The result is a decimal number which is displayed to the user. In case the number entered is not a binary number, i.e. it contains numbers other then 0 and 1. In that a NumberFormatException will be thrown. I have catch this exception, so that the developer can use there custom message in that place.

The Java Code is displayed below:-

/////////////////////////////////////

package developer;

import java.util.Scanner;

public class BinaryToDecimal {

    public static void main(String[] args) {
      
        System.out.println("Enter a binary number: ");
        Scanner scanStr = new Scanner(System.in);
              
        int decimalNum = 0;      
              
        if(scanStr.hasNext())
        {   
            try
            {
                decimalNum = Integer.parseInt(scanStr.next(),2);
                System.out.println("Binary number in decimal is: "+decimalNum);  
            }
            catch(NumberFormatException nfe)
            {
                System.out.println("The number is not a binary number.");
            }
        }  
    }
}


/////////////////////////////////////

When this code is executed on my system, the output is as shown below.
/////////////////////////////////////

Enter a binary number:
10100011
The binary number in decimal is: 163

/////////////////////////////////////

In case the number entered is not a binary number, then the output is as shown below:-

/////////////////////////////////////

Enter a binary number:
123456
The number is not a binary number.

/////////////////////////////////////

Hope that I was able to make my point clear. If you liked the article then do post a comment. Kepp checking Java Code Online for more Java Codes.

Related Java Codes
Java Code to Convert Decimal to Binary

Java Code to Convert Decimal to Binary

The Java Code Online is today going to discuss the Java code for converting a decimal number to binary number. A decimal number is known to all of us. It is number whose base value is 10. All the numbers we use in normal practice are usually decimal numbers. It implies that decimal numbers can consist of numbers from 0-9.

A binary number is a number whose base value is 2. It means that a binary number system consists of only 0 and 1. In computers all the data is transferred in the form of binary numbers.

The Java Code presented today, asks the user to enter a decimal number, and displays the binary equivalent of that number.

The Java code is displayed below:-

/////////////////////////////////////////////

package developer;

import java.util.Scanner;

public class DecimalToBinary {

    public static void main(String[] args) {
  
        System.out.println("Enter a decimal number: ");
        Scanner scanStr = new Scanner(System.in);
              
        String num = null;      
      
        //Check for an integer number entered by the user
        if(scanStr.hasNextInt())
        {
            //Convert the decimal number to binary String
            num = Integer.toBinaryString(scanStr.nextInt());
        }          
      
        System.out.println("The decimal number in binary is: "+num);          
    }
}

/////////////////////////////////////////////

When the code is executed, the output is as shown below:-

/////////////////////////////////////////////

Enter a decimal number:
23
The decimal number in binary is: 10111

/////////////////////////////////////////////

Hope that the code was useful to all of you. Keep buzzing Java Code Online.

Related Java Codes
Java Code to Convert Binary to Decimal

Monday, September 21, 2009

Java Code to write to CSV File


Hello guys, Java Code Online is back again with an important code. The code for today is for making a CSV (Comma Separated File) file. The operation to make a CSV file in Java is similar to the Java Code to write to a file. The difference between these two is that a comma is inserted within the text, where ever we want the columns in MS EXCEL to change to new column.

The beauty of the .csv file is that, when this file is opened in MS Excel, then all the values which are separated by comma, are displayed in a new column. This is required many times, if we want to send data to different columns. Even there is an option to switch rows while writing.

The Java Code displayed today, makes a .csv file at a particular location on your hard disk. You need to change the path, according to your requirements. The code writes some data to the .csv file. It generates 3 columns and 2 rows. You can modify it, according to your own requirements.

The Java Code is provided below:-

/////////////////////////////////////

/** The below Java Code writes
 * some data to a file in CSV
 * (Comma Separated Value) File
 */

package developer;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class MakeCSVFile {

    public static void main(String[] args) throws IOException {

        //Note the "\\" used in the path of the file
        //instead of "\", this is required to read
        //the path in the String format.
        FileWriter fw = new FileWriter("D:\\JavaCodeFile\\WriteTest.csv");
        PrintWriter pw = new PrintWriter(fw);
       
        //Write to file for the first row
        pw.print("Hello guys");
        pw.print(",");
        pw.print("Java Code Online is maing");
        pw.print(",");
        pw.println("a csv file and now a new line is going to come");
       
        //Write to file for the second row
        pw.print("Hey");
        pw.print(",");
        pw.print("It's a");
        pw.print(",");
        pw.print("New Line");
       
        //Flush the output to the file
        pw.flush();
       
        //Close the Print Writer
        pw.close();
       
        //Close the File Writer
        fw.close();       
    }
}

/////////////////////////////////////

The code when run on my system a produces a file called WriteTest.csv, when opened with MS EXCEL, the output is shown below:-




I hoe that the code was useful to all of you. Java Code Online is going to be back soon.

Check out the tutorial at the Sun site

 Java is everywhere. Of the most  authenticate sources, that could be used for learning Java, I trust sun the most. The tutorial provided by java.sun.com normally called as the Java Tutorial at java.sun.com/docs/books/tutorial , is a very good one. I have scanned the tutorial many times earlier also, and every-time found it to be the most updated and authentic resource on the net.

The Java technology always keep coming up with new changes and features. Therefore the need to continuously update the link and site is very important. Sun is the provider of Java, and so they have to maintain the most updated links and material. The best part I found with this site was that the tutorial was concise and up to the point.

The site does not go in unnecessary examples or extra elaboration. It sticks to the basics and explains them well. The section for Trail Covering the basics, consists of many great Java technology articles. It does not deal only with basic Java, but the tutorial for Java Collections and Swing is also provided. This is an extra bonus for all those who are interested in getting to the roots of Java.

The section of specialized trails and lessons consists of many advanced Java related tutorials and articles. To name a few, the trail consists of articles and tutorials on Networking, Generics, JavaBeans, JDBC, JMX, JNDI, RMI, Reflection, Java Security, Graphics, Socket Programming in Java, etc.

All these are very important fields of Java for an advanced programmer. Like JDBC which is used for Database connection establishment, and retrieval and updation of records. The process involves many commands and is a separate field altogether.

JNDI and RMI, are used for Remote Method Invocation. This is a very large field in itself. The part of RMI is important for a distributed architecture. Like your server is at a particular place, and the application is running at a different place. There need to be interaction between this application and the server. RMI along with JNDI are used here.

Like this there are many fields from which the person can choose depending upon his or her intrest. It is vast ocean of resources for Java. Go ahead and give it a look, Hope that you will also find something very interesting and useful from this site.

That's it for now. Keep buzzing Java Code Online.

Saturday, September 19, 2009

How to get Java

Some of my readers have raised a concern on how to install java on their computers. So Java Code Online has come up with this simple yet important article on downloading Java to your system. It might be that the computer does not contain Java, or it is also possible, that the version of Java installed is an old one. This hampers many of the different features of your computer.

Getting Java on your computer is very easy. Just go to www.java.com/en. Click on the "Free Java Download" button. It will verify, that whether your computer has Java installed on it or not. and if Java is installed already, then whether the version is an old one or a new one. If you have the latest version of Java installed, then you will get the message
"Verifying Java Version
Congratulations!
You have the recommended Java installed (Version x Update xx).

If the computer does not have Java, or the latest version of Java, then it will allow the computer to download the latest version form there. The best part is that it is free, so need to worry about paying to anyone.

Java is a must for almost all of the applications that work on your computer, and is also required by many sites that you visit. So don't hesitate in getting the latest version of Java. The only exclusion from this are the programmers who are working on an earlier version of Java, and do not want to switch to a new version. Remember that with every new version, some of the old features are deprecated. The depricated features are the one, which should no longer be used by any programmer.

Friday, September 11, 2009

Blogger Blogging on Blogspot

Hi and welcome back to Java Code Online. Today I will not be discussing any Java topic. I have been blogging for some time now, and wish to take it to the next level. The thought that crawled through my mind, was regarding various Gadgets that various blogs use. They definitely make the blog look more attractive, handy and useful. It increase your traffic, as the viewer loves to come back to your blog. Moreover it is a feeling of self satisfaction, that yes I have made a beautiful thing.

The aim of this post is to invite all Bloggers who use Blogger.com for blogging, to discuss about the various gadgets that they use. This will help all the bloggers to be aware of various widgets provide by Blogger and third parties to improve their blog. Some blogs which I checked have really great templates, it would be a pleasure if all of you come up with your resources. It would be a great help to all the bloggers, and especially to beginners who are just preparing to start their blog.

The gadgets I am using are for Google Friend Connect for tracking the followers of this blog, and the RSS feed for subscribing to the postings. Apart from that there is Google Adsense for monetization. I have used the labels and archives tab to make the blog look more handy and comfortable to all the viewers. I suppose that all of us will be using similar kind of tools, but there are many more and the shared information could be beneficial to all of us.

As a programmer, i feel to enhance my blog using the technology on which I am working. I have been working on Java for a long time, and my current application areas include JSP, Servlets, Struts, J2EE , JavaScript etc. Though the list is a long one, I am not able to apply anything apart from some JavaScript and HTML on my blog.

Recently I was checking the site code.google.com/apis/blogger/docs/2.0/developers_guide_java.html, for support on Blogger. And in fact I came to know that, I can do much more with Java. Java can help in posting, deleting, publishing, retrieving, saving as draft etc. of articles to your blog. There is complete library waiting to be explored. It can open a new perspective that how we integrate our blogs with the technology. I am posting the information I have, and encourage to all of you to come with various ideas to improve the way we blog.

Java Code Online hopes that this article will definitely help in improving the way we blog, and definitely makes our blog look much better. It's the technology that will drive it, and I love Java for that.

Thursday, September 10, 2009

Java Code to Delete a File

Hello and welcome back to Java Code Online. The topic for today's discussion is to delete a File in Java, though a very simple process, it is very important. It is one of the most basic aspects of File Handling. So this Java Blog has decided to pick this topic in this tutorial.

The Java Code discussed today, starts by taking the path for the file, and checks for its existence. If the file exists, then the delete() command is fired on it. After deletion of the file, the presence of the file is checked. This step is to ensure that the deletion activity of the file is properly achieved or not.

The Java code is provided below:-

/////////////////////////////////

package developer;

import java.io.File;

public class DeleteFile {

public static void main(String[] args) {

File fileTest = new File("D:\\JavaCodeFile\\WriteTest.txt");

//Check for the existence of the file before deletion of it
System.out.println("Is the file present in the current location before deletion? ");
System.out.println(fileTest.exists());

if(fileTest.exists())
{
//Delete the file
fileTest.delete();
}

//Check for the existence of the file after deletion of it
System.out.println("Is the file present in the current location after deletion? ");
System.out.println(fileTest.exists());
}
}

/////////////////////////////////

This Java Code when executed on my JVM, resulted in the following output.

/////////////////////////////////

Is the file present in the current location before deletion?
true
Is the file present in the current location after deletion?
false

/////////////////////////////////

Simple isn't it. yes the process of deletion of a file is very simple, and now you know it too. Keep checking Java Code Online for more Java articles.

Related articles that might be of interest:-
Java Code to Read a File
Java Code to Write to a File
Java Code to Create to a File
Java Code for File Extension
Java Code for Removing File Extension

Wednesday, September 9, 2009

Java Code to Create a File

This Java Blog is today picking the topic of how to create File in Java. Java Code Online hopes that the article will be helpful to you all. In Java there are various possibilities for File Manipulation and handling. I suppose the simplest of them is regarding creation of a File. There are cases when we need to create a File for backing up some data, or write some important data, or might be some other reason. For all of the above we need to know first of all, how to create a File.

Creating a file is a simple process, and it uses just two methods of the File Class which is in the java.io package. They are:-

1. exists()
2. createNewFile()

The exists() method checks that whether the file exists or not. The createNewFile() method creates new File. Though creation of the File can be easily done by the createNewFile() method, it is a good practice to check that the file exists prior to creation or not. This case is important in scenarios where we need to create a File in case it does not exists, if it exists, then we need to modify it. So here the exists() method is very important, as it checks beforehand that the File exists or not.

The Java Code discussed today starts by declaring a new File at a particular path. You need to configure the path according to your application. I suppose that this is the only change apart from the package name, that you may need to do in this program, so as to compile and run it successfully.

The File is then tested for its existence using the method exists(), and if the file is found to be non existent, then a new File is created using createNewFile() method.

The Java Code is provide below for your reference:-

/////////////////////////////////////////

package developer;

import java.io.File;
import java.io.IOException;

public class CreateFile {

public static void main(String[] args) throws IOException {

File fileTest = new File("D:\\JavaCodeFile\\CreateTest.txt");

//Check for the existence of the file
System.out.println("Does the file exists before execution of the code? ");
System.out.println(fileTest.exists());

if(!fileTest.exists())
{
//Create a new file at the specified path
fileTest.createNewFile();
}

//Check again for the existence of the file
System.out.println("Does the file exists after execution of the code? ");
System.out.println(fileTest.exists());
}
}

/////////////////////////////////////////

The output on my console after compiling the application using the Java compiler and running this program on my JVM was as below:-

/////////////////////////////////////////

Does the file exists before execution of the code?
false
Does the file exists after execution of the code?
true

/////////////////////////////////////////

Hope that now you can easily create a file in Java. Do post comments if you have issues or if you liked the article. Java Code Online is working on new articles for Java lovers.

Related articles that might be of interest:-
Java Code to Read a File
Java Code to Write to a File
Java Code for File Extension
Java Code for Removing File Extension

Monday, September 7, 2009

Java Code to Write to a File

Welcome back to Java Code Online. The article for today is for writing some text to a file in Java. There are often various cases when we need to write or save some data in an external file. Java provides a very powerful set of libraries for handling this operation.

First for writing to a file you need to have write permission on it, So first we need to check that whether we can write on it or not. If the file is writable, then we use the FileWriter class provided by Java to perform this operation. This file is part of the java.io package, which includes many powerful classes for handling the Java input output operations.

The writing to a file operation is used in many cases like when we need to save some content in a file, which could be read or used afterward. this file may also be sent to some other application for some other operations required on it.

The Java Code for writing to a file is provided below. We assumed a path as per our local machine. You need to set the path according to your folder structure. This code writes the content in a file. If the file is not present, then it creates one and then write to it. So anyhow your writing operation will be successful.

The Java Code is:-

////////////////////////

package developer;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class WriteToFile {


public static void main(String[] args) throws IOException {
//Note the "\\" used in the path of the file instead of "\",
//this is required to read the path in the String format.
FileWriter fw = new FileWriter("D:\\JavaCodeFile\\WriteTest.txt");
PrintWriter pw = new PrintWriter(fw);

//Write to file line by line
pw.println("Hello guys");
pw.println("Java Code Online is testing");
pw.println("writing to a file operation");

//Flush the output to the file
pw.flush();

//Close the Print Writer
pw.close();

//Close the File Writer
fw.close();
}
}


////////////////////////

The beauty of the code lies in its compactness and simplicity of use. Note the use of flush on the PrintWriter Class Object. This helps in writing any buffered output to the file. This ensures that all the content is written to the file, before the writer is closed.

I hope the code for writing to a file was useful to all. Keep posting comments, because that's the way we can be in touch. Keep checking Java Code Online for more Java articles.

Related Java articles:-
Java Code to Read a File

Sunday, September 6, 2009

Java Code to Read a File

Today Java Code Online is going to pick a very important topic, and that is regarding File Reading in Java. There are often various scenarios when the data required is to be read from a particular file that is not part of the application.

The external file may be a .txt, .xml, .csv etc. type of file. The thing that matters is that we need to read it in the Java application. The code discussed here is applicable for a .txt file. Though the processing will differ a bit for the other type of files.

I have taken an example, where a file is read from a particular folder. Replace the path with the path of your file, and you are all set to go. I have added extra comments for each line of code, so as to make there purpose clear in the Java Program.

The Java code is provided below:-

///////////////////////////////////////


package developer;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

public static void main(String[] args) throws IOException {

String fileStore = null;

//Note the "\\" used in the path of the file instead of "\",
//this is required to read the path in the String format.
FileReader fr = new FileReader("D:\\JavaCodeFile\\Test.txt");

BufferedReader br = new BufferedReader(fr);

//save the line of the file in a String variable and compare it with null, and continue till null (End of File) is not achieved
while(null != (fileStore = br.readLine()))
{
//Print the file line by line
System.out.println(fileStore);
}

//close the Buffered Reader
br.close();

//Close the File Reader
fr.close();
}
}


///////////////////////////////////////

When the code is executed, it will display the content of the file line by line on the console. for my case the output was as given below. Your output may differ based on the file content.

///////////////////////////////////////


Hello
Welcome to Java Code Online
This is a test file


///////////////////////////////////////

It should be enough to clear all your doubts for how to read a file in Java. If you liked the article then do leave a comment. Java Code Online will be coming up with more articles on file handling soon.

Convert String to integer (int) in Java

Java Code Online will discuss the Java Code to convert a String to an int. There is a feature provided in Java, which helps to perform this operation. The conversion is done with the help of a method called parseInt().

Actually any String which could be converted to a primitive can be converted to it, by using the parseXxx() method, where Xxx will replace the type in which it is to be converted, like int, float, etc.

I have provided a sample Java Code which asks the user to enter a number, which is taken as a String by the application. Later it is converted to an integer by using the parseInt() method. Go through the code for a clear understanding on how it is to be used.

  package developer;

  import java.util.Scanner;

  public class StringToInt {

  public static void main(String[] args) {

        System.out.println("Enter a number which would be taken as a String by the application");
        Scanner scanStr = new Scanner(System.in);
        String numStore = null;
        int numConvert = 0;

        // Takes the input as a String
        if (scanStr.hasNext()) {
            numStore = scanStr.next();
        }

        // Convert the String to int by using the Integer.parseInt() method
        numConvert = Integer.parseInt(numStore);

        System.out.println("The number entered by you is: " + numConvert);

     }
  }

The output is something like as shown below.


  Enter a number which would be taken as a String by the application
  22
  The number entered by you is: 22


Some observation points are:-
The String which is to be converted to a number must be a number in the String format. This is required so that the Java parser can parse the String successfully into an int.

If the value entered is not a number, suppose that you entered a String in words in place of a number in String format, then the output is shown below:-

 Enter a number which would be taken as a String by the application
 Conversion from String to int
 Exception in thread "main" java.lang.NumberFormatException: For input string: "Conversion"
     at java.lang.NumberFormatException.forInputString(Unknown Source)
     at java.lang.Integer.parseInt(Unknown Source)
     at java.lang.Integer.parseInt(Unknown Source)
     at developer.StringToInt .main(StringToInt .java:20)

So we see that if a String is entered to be parsed as an int, then the Java Compiler gives a big fat "NumberFormatException".

I hope the Java Code provide to convert an a String to an int was helpful. Do leave a comment if you liked the article. Java Code Online will soon be back with another interesting Java article.

Related Java Codes:-
Convert int to String in Java
Convert int to String in Java using Wrapper Classes

Convert int to String using Wrapper in Java

Hello and welcome back to Java Code Online. I have seen a few comments from some of my readers, it was regarding an alternative way to convert an integer to String. This method uses the Wrapper Objects to convert an int to an Integer Object. Or you can say that, the process is:-

1. Convert a primitive to an Object using the Wrapper Classes.
2. Then convert the Wrapper Object in to a String.

Though it is a lengthier process, and is therefore rarely used for converting an ant to String. The best process is the one which I discussed in the previous article to convert an int to String. It is the most easiest and fastest way for making the conversion. Anyhow I will give you the alternative way also which I have discussed write now.

The Java Code starts by asking the user to enter an integer number. This number is then converted to an Integer Wrapper Object, which is later converted to a String, by using the toString() method on it.

The Java Code for a sample program on it is given below.

///////////////////////////////////////

/*
* This class converts an int number to an Integer Wrapper Object and then transforms that Object in to a String
*/

package developer;

import java.util.Scanner;

public class IntToStringUsingWrapper {


public static void main(String[] args) {

int number = 0;
System.out.println("Enter a number which would be taken as an Integer by the application");

Scanner scanInt = new Scanner(System.in);

//Execute if the number entered is an integer
if(scanInt.hasNextInt())
{
number = scanInt.nextInt();
}

//Wrap the number in the Integer Wrapper Object
Integer num = new Integer(number);

//The num is converted to a String
String strNum = num.toString();

//Use the toString() method to convert the object in to String
System.out.println("The number entered is: "+strNum);


}

}

///////////////////////////////////////

The output is something like shown below:-

///////////////////////////////////////

Enter a number which would be taken as an Integer by the application
33
The number entered is: 33

///////////////////////////////////////


hope that this article was helpful to resolve the issue of an alternative way to convert an int to a String. If you find the article useful, then do leave a comment. Keep checking Java Code Online for more Java topics.

Related articles:-
Convert int to String in Java
Java Code for Number of Words in a String