Sunday, October 11, 2009

Static Inner Class Example in Java

Hello and welcome back to Java Code Online, there has been a request from many of my users to come up with an example for static inner class. So the topic of today is to to illustrate Static Inner Class in action.

You may any time check my previous article on Static Inner Class in Java for an illustration of what it is and what are the details for the other type of Inner classes in Java. today I will straight move to the example for it.

------------------------------------
class Cover
{
         static class InnerCover
             {
              void go()
                  {
                       System.out.println("I am the first Static Inner Class");
                  }
            }
 }

class Broom
{
         static class InnerBroom
        {
                  void go1()
                   {
                         System.out.println("I am second Static Inner Class");
                    }
         }

         public static void main(String[] args) {
         // You have to use the names of both the classes
         Cover.InnerCover demo = new Cover.InnerCover();
         demo.go();
        // Here we are accessing the enclosed class
        InnerBroom innerBroom = new InnerBroom ();
        innerBroom .go1();
 }
}
------------------------------------

When the above code is executed, the output is something like as displayed below:-
------------------------------------
 I am the first Static Inner Class
 I am second Static Inner Class
------------------------------------

We know that a Static inner class is just a class which is a static  member of the main class. So the same concept is applied here. Here we have two outer classes, one is called Cover, and the second is called Broom. Both of these outer classes have one static class within them.

The method of accessing both the inner classes is shown in the main method of the Broom class. I hope the example will be helpful to all of you. Do post a comment if you have any query or if you liked the article. Java Code Online will soon be back with yet another informative article.

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

Wednesday, August 26, 2009

Convert int to String in Java Code

Java Code Online is going to discuss the way to convert an int into a String in Java. It is often required in Java programming, to convert an integer into a String value, and operate on it assuming it to be String.

Converting an integer into a String, provides many powerful features and methods which are inherent to Strings, but not to primitives like integer. That make the operating on the value much more easier when the value is used as a String.

I will discuss the most commonly used, and in fact the most easiest and effective method of converting an int into a String.

Use the + operator to convert int to String

1. Use the "+" operator, for converting an int into a String.

Simple isn't it. The logic is that the "+" operator is overloaded in Java. It performs many functions. When used with two integers, it produces the sum. But when a string is used with an int and the "+" operator in between, the the result is a String. For example:-

The issue with + operator for int
Using the + operator with ints result in their addition. The example demonstrates this:-


   package JavaTest1;

    class TestIntToString {

        public static void main(String[] args)

        {
            int i = 2;
            int j = 3;
          
            System.out.println(i + j);
        }
    }


The above code will result in printing 5. This is not what we wanted, so the solution is to use a string in between.

Solution for converting int to String in Java
If we change the above code such that the variable "j" is a String with some String assigned to it. Then the output will be a String. For example:-

    package JavaTest1;

    class TestIntToString {

        public static void main(String[] args)
        {
            int i = 2;
            String j = "";
            int k = 3;

            System.out.println(i + j + k);
        }
    }

When the above code is executed, the the output is:-
    23

So we see that this time the two numbers do not get added, but they resulted in concatenating to each other. This is because they are converted to String. That's really cool. Now this String can use all the methods which are available to Strings. So making it really powerful.

So you can see that by using the "+" operator, you can easily convert an int into a String. I hope the post was helpful to you all. Keep buzzing Java Code Online for more info on Java.

Other Links of interest:-
Convert int to String using Wrapper in Java
Reverse a String
Length of String
Number of words in String
Palindrome Java program

Deadly Diamond of Death

Hearty welcome from Java Code Online. Today's topic is DDD, that is Deadly Diamond of Death. As promised in my earlier post, and as asked by some of my friends in their comments, I will pick this topic to clarify all the myths and doubts. Though the name is Deadly, the topic is not so Deadly, since it is avoided in Java. Java as we all know is a very powerful language. It has all the good features, and avoids all the bad features including the one which will be discussed today.

Java does not support multiple Inheritance. Though it is supported in C++, Java avoids it. The reason for avoiding multiple Inheritance is the Deadly Diamond of Death. Actually the class diagram that is formed in this scenario, is that of a diamond, and it is like a no solution output, so the code gets locked, so it is called Deadly Diamond of death. Thus the Java language do support multiple implementations, but not multiple Inheritance. So a class can implement many Interfaces, but can not extend more than one class.

I will explain the issue by taking an example. Suppose that Java supports multiple inheritance (though it does not, but still we will assume it to understand the current concept). Just go through the following points for a clearer understanding:-

1. Suppose that we have an abstract super class, with an abstract method in it.

2. Now two concrete class extend this abstract super class, and provides the implementation of the abstract method in the super class, in two different ways.

3. Now a fourth class comes into picture which extends the above two concrete classes. So now by the principle of inheritance it inherits all the methods of the parent class, but we have a common method in the two concrete classes but with different implementations, so which implementation will be used for the last child class which inherits both these classes?

Actually no one has got the answer to the above question, and so to avoid this sort of critical issue, Java banned multiple inheritance. The class diagram which is formed above is like that of a diamond, but with no solution or outcome, and so it is called Deadly Diamond of Death.

I will try to make it more clear, by taking an example. Take this:-

// This is our top most abstract class.
class AbstractSuperClass{
abstract void do();
}

// These are the two concrete sub classes which extend the above super class
class ConcreteOne extends AbstractSuperClass{
void do(){
System.out.println("I am going to test multiple Inheritance");
}
}

class ConcreteTwo extends AbstractSuperClass{
void do(){
System.out.println("I will cause the Deadly Diamond of Death");
}
}

// This is our last class which extends both of the above concrete classes
class DiamondEffect extends ConcreteOne, ConcreteTwo{
//Some methods of this class
}




Now what do you think will happen, when an Object of class DiamondEffect is made, and the do method is called?

Since the DiamondEffect class extends both the ConcreteOne and ConcreteTwo classes, it inherits the "do" method from both of them, but the DiamondEffect class does not know which one to use when the method is called on it. The structure of class diagram here is like a diamond. This is the Deadly Diamond of Death.

I hope I was able to make my point clear. If you have any doubts or issues, then do write a comment for me, and I will try my best to answer you. You may leave a comment if you like the article. Java Code Online will see you later in the next post.

Tuesday, August 25, 2009

What are final methods in Java

Hello guys, Java Code Online welcomes you back again, and is going to discuss about the final methods in the Java Programming Language. The Java language provides its users with many resources and tools. There are many features in the Java language that makes it very powerful. Final access modifier is one of those features, that makes Java really solid.

If a method is marked as final, then it implies that it cannot be overridden. So any class that extends the class containing the final methods, cannot override the methods marked final. If any attempt is done to override a final method in a sub class, leads to Java Compiler error.

An example of a final method in a class is:-

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

class TestFinal{

public final void finalTested(){
//Working of this method
}

//Some other methods

}

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

The above Java code depicts the use of final when applied to methods.

You may be thinking that what is the advantage of making a method final, though it defies the basic principle of OOPS, that is the final methods are non supportive of inheritance, as they cannot be overridden. It implies that they cannot be extended, and so also makes Polymorphism not feasible for it.

Hmmm... it implies that there are many drawbacks of the final method, but still Java provides it. So there must be some advantage of it also... Lets check them out.

Think of a scenario, that you have made a class, and you want a particular method to be implemented in exactly a particular way, and one should be never allowed to change this implementation. There are many possibilities for it. Like there are many methods in the Java API, which are guaranteed to work in a fixed way, and there is no way we can change them. This scenario calls for marking the method of the class as final. Later I will tell you about the Template Design Pattern which is based on this concept.

I hope you got my point. Whenever you want the methods to be locked, and should not be allowed to be modified, then final is the keyword to be used. The class can still be inherited since it is not marked final, and so the concept of Inheritance and Polymorphism can easily work here, but only for methods which are not marked as final in the super class.

Hope that the article was helpful to you all in understanding the final methods in Java. Keep ticking Java Code Online for more details on Java.

Saturday, August 22, 2009

What is an Interface in Java

Bingo, so we are going to discuss a very important topic today at Java Code Online. Interfaces has been he heart of most of the Java fundamentals and coding, mostly because there existence support Polymorphism, which is one of the four Principle of OOPS apart from Abstraction, Encapsulation and Inheritance.

Interface as the name suggests is a "Contract". Yes you read it right. It is contract between the interface provider and the interface implementer that the methods mentioned in the Interface will be implemented. Mostly Interfaces are used vis a vis Inheritance, and there is much research done before choosing one.

An Interface is like a pure abstract class, with the difference that the all the methods of the interface are abstract, so any class that implements this interface has to implement all the methods mentioned in this interface. That's the law. So actually the interface tells that which methods are to be implemented, but not that how we are going to implement. It is left for the subclasses to decide how to implement this.

One important part of Java is that it supports multiple Implementations, but not multiple Inheritance. So a subclass can implement multiple Interfaces, but cannot extend multiple classes. I will detail on this in a later post where I will tell you that if multiple Inheritance is allowed, then how it may lead to the Deadly Diamond of death. Anyhow that's a bit deviating from the main topic. Our primary concern are the Interfaces.

An example of an Interface is shown below:-

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

Interface JavaTest{
public static final int val = 3;

public abstract doTest();
public abstract takeResult();
}

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

Here in this Interface declaration file, the keywords public and abstract are not required for the methods as they are implicit. Moreover the keywords for the variable declared in the Interface are also not required as they are also implicit.

So any variable declared in an Interface is practically a constant, and all the methods which are declared in the interface have to be implemented by the first concrete subclass that implements this interface.

There is one key point regarding the Interfaces, and that is you cannot declare the methods of the Interface to be final. Remember that final methods cannot be overridden, and an abstract method is useless if we do not override it. That is the main reason that abstract and final are never used together for any method.

I hope the article was helpful in understanding the Interface in Java. Do post a comment if you liked the article. For more Java info Java Code Online is the key.

Java Code for File Extension

Hi friends, Java Code Online welcomes you back again. The last post I have made was for getting the file name without the extension of the file. But there are many scenarios when we desire the extension of the file, and not the name of the file.

The Java code here asks the user to enter a valid file name, and then remove the file name but keep the extension of it. So the user enters a file name and gets the extension of it.

The Java Code is provided below:-

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

import java.util.Scanner;

public class FileExtension {

/**
* @param args
*/
public static void main(String[] args) {

String fileExt = null;

System.out.println("Enter a valid file name whose extension is desired:");

Scanner scan = new Scanner(System.in);

if(scan.hasNext())
{
fileExt = getFileExtension(scan.next());
}

if(null != fileExt)
{
System.out.println("The extension of the file is: "+fileExt);
}
else
{
System.out.println("Not a valid file name");
}

}

//get the file extension of the file entered
public static String getFileExtension(String filePath)
{
String extension = null;
if(null != filePath && filePath.contains("."))
{
extension = filePath.substring(filePath.lastIndexOf("."), filePath.length());
}
return extension;
}

}

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

When this code is executed, the output is something like as given below:-

//////////////////////////////////////////
Output

Enter a valid file name whose extension is desired:
javadeveloper.java
The extension of the file is: .java
/////////////////////////////////////////

I hope the article was helpful, and my efforts did not went in vain. Keep ticking Java Code Online for more Java details.

Other article of interest:-
Remove the extension from the filename

Remove Extension of File Java Code

Hello friends, welcome once again at Java Code Online. The topic of the day is the Java code that helps in removing the extension of a file name that is entered by the user.

The operation is a simple one and is crucial in case of file handling. Though mostly we need to remove the file extension before processing the file, there may be other requirements that ask for this requirement.

Anyhow the Java Code is provided below:-

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

package developer;

import java.util.Scanner;

public class RemoveFileExtension {

public static void main(String[] args) {

String fileRemExt = null;

System.out.println("Enter a valid file name whose extension is to be removed:");

Scanner rem = new Scanner(System.in);

if(rem.hasNext())
{
fileRemExt = removeFileExtension(rem.next());
}

if(null != fileRemExt)
{
System.out.println("The file name without extension is: "+fileRemExt);
}
else
{
System.out.println("Not a valid file name");
}

}

//remove the file extension of the file entered
public static String removeFileExtension(String fileName)
{
if(null != fileName && fileName.contains("."))
{
return fileName.substring(0, fileName.lastIndexOf("."));
}
return null;
}

}
////////////////////////////////////

Once this code is executed, the output is something like:-

////////////////////////////////////
Output

Enter a valid file name whose extension is to be removed:
test.java
The file name without extension is: test
////////////////////////////////////

I hope the article was helpful to most of you. In case you liked the article then do leave a comment at Java Code Online.

Thursday, August 20, 2009

Anonymous Inner Class in Java

Hi everybody, Java Code Online is going to discuss the Anonymous Inner Class in Java today. This class as the name specifies is not named. It means that this class has a body but no name. And so it is anonymous.

It is one of the most bizarre type of Inner class. It is always invoked from outside the Outer class. When the invocation is done, then this class is placed after the brackets of the method invocation. The key to understand this is that, actually the Anonymous inner class always extend or implement, but not both at the same time.

When the Outer class is invoked, then the syntax is something like:-

OuterClass oc = new OuterClass();

But when the anonymous inner class comes into picture the code is something like:-

OuterClass oc = new OuterClass(){
//some inherited method
};

The syntax though very much strange is the correct one. Here the curly braces after the instantiation call infact causes an anonymous inner class to be formed which either inherits or implements the method of the instantiated class. So the only methods available here are the one by inheritance or implements. Note the semicolon at the end of the curly braces, strange but true. Here the main concept is of Polymorphism as the name of the super class is used to refer the sub class, which is our anonymous inner class in this case.

For reference,
Types of Inner Class
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

Hope that the article helped solved your issues with this type of class. Remember Java Code Online is the key to a vast pool of Java. That's it for now. See you later.

Method Local Inner Class in Java

Hello and welcome back to Java Code Online. Today I will be discussing about the Method Local Inner Class in Java. It is one of the four subtypes of Inner Classes.

The Method Local Inner class, as the name specifies is local to a method. It implies that the method local Inner class is defined inside a method of a class. As the class is defined inside a method, it needs to be instantiated from with in the same method, but after the class definition is finished. As a mater of fact this inner class cannot use the variables of the same method, unless they are declared final.

If you did not instantiate the class within the same method and after the class definition is finished, then that inner class though valid will be useless, as there is no other way to instantiate it. Moreover the Instantiation must be after the class definition or else the Java Compiler will not be able to see it.

Hoping that this article was helpful to you all. Do post a comment if you liked this article.

For reference,
Types of Inner Class
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

Keep buzzing Java Code Online for more Java Information.

Static Inner Nested Class in Java

Hi friends, welcome back to Java Code Online. This article is in continuation to the previous article on Regular Inner Class, here I will discuss the second type of Inner Class called Static Inner Nested Class.

The static Inner Nested Classes are nothing else, but are like Regular Inner class, but are marked static. So the behavior of these classes is static in nature. This explains most of the behavior of the static inner class. Like it behaves like a class level variable. I mean to say that, you need not instantiate the outer class for creating an instance of the static inner class, and that the static inner class can be directly instantiated.

Moreover as the behavior of a static member is, the static inner class cannot access the non static members of the class, this is in sync with the basic properties of a static variable or member of a class. For instantiating a Static Inner Class, you need to use the name of both the Outer class and Inner class. For example:-

OuterClass.InnerClass ocic = new OuterClass.InnerClass();

I hope the article was helpful. In case it was, the do leave a comment.

For reference,
Types of Inner Class
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

Keep checking Java Code Online for more Java info.

You might be interested in these too:-
Static Inner Class Example in Java

Regular Inner Class in Java

Hi friends, welcome back to Java Code Online. Today's article discuss the regular inner class in Java. Though the inner classes could be classified in 4 sub types, regular inner classes is the most commonly used sub type.

The regular inner class is a full fledged member of the outer class, so it shares all the features of a member of a class. Like an Inner class has access to all the variable of the outer class including the private variables. There is a special way to instantiate an Inner class. For instantiating a regular Inner Class, you need to instantiate the Outer class first.

If you are invoking the regular inner class from inside the Outer class, then it could be instantiated like a regular class, like:-

InnerClass ic = new InnerClass();

But if the Inner class needs to be instantiated from outside the Outer class, then first you need to get a reference of the Outer class Object, and then create an Object of the Inner class from that. The syntax is something like given below:-

OuterClass oc = new Outer Class();
OuterClass.InnerClass ic = oc.new InnerClass();

I hope that this article was helpful in clearing all your doubts about Regular Inner Classes.

For reference,
Types of Inner Class
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

For more information on Java, keep buzzing Java Code Online.

Types of Inner Class in Java

Hi friends, Java Code Online welcomes you back again. Today's article discuss the Inner classes in Java. An Inner class is like a class but it is defined inside another class. So the behavior is like of a class but is internal to a class.

The Inner Classes can be classified in four types. They are:-
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

All the types of inner classes are defined in their respective articles. The Inner classes though not much commonly used in Java, still find some important place in some programs. Though it is a bit too odd to see a class being placed inside another class, the behavior is more or less like a local method of the outer class. There is different functionality for all the different types of Inner classes. You may find the details in the individual articles for each type of Inner class.

I hope the article was able to clear your myth and doubts about the Inner classes in Java. If you liked the article then do leave a comment. Keep buzzing Java Code Online for more Java articles.

Wednesday, August 19, 2009

Armstrong Number Java Program

Hello, welcome back to Java Code Online. Today I would be discussing an important mathematical Java Code. This Java Code is for Armstrong Number. The code asks the user to enter a number, and then checks that whether it is Armstrong Number or not.

An Armstrong Number is one in which the sum of the individual numbers raised to the power of the number of words in that number is equal to that particular number itself. For example 1 raised to the power 1 is equal to 1, so it is an Armstrong Number. Again 153, implies 1 raised to the power 3, 5 raised to the power 3, and then 3 raised to the power 3 are added, then it gives 153 again, so it is also an Armstrong Number.

The Java Code is given below:-

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

package developer;

import java.util.Scanner;

public class ArmstrongNumber {

static double finalValue = 0;

public static void main(String[] args) {

int valueTaker = 0;

System.out.println("Enter a number to be checked for Armstrong Number: ");

Scanner armstScan = new Scanner(System.in);

if(armstScan.hasNextInt())
{
valueTaker = armstScan.nextInt();
}

StringBuffer sb = new StringBuffer().append(valueTaker);

double lengthSBKeeper = sb.length();

for(int lengthKeeper = 0; lengthKeeper < sb.length(); lengthKeeper++)
{
double zxc = Integer.parseInt(sb.substring(lengthKeeper, lengthKeeper+1));

finalValue = Math.pow(zxc, lengthSBKeeper) + finalValue;

}

if(finalValue == valueTaker)
{
System.out.println("The entered number "+valueTaker+" is an Armstrong Number");
}
else
{
System.out.println("The entered number is not an Armstrong Number");
}
}
}

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

I hope the code above was helpful to all of you. Just copy the code in your IDE, and change the package name accordingly, and you are set to roll. Keep buzzing Java Code Online for more Java information.

Other Java Programs that might be of some interest:-
Factorial Program in Java
Palindrome Program in Java
Prime Number Program in Java
Fibonacci Series Program in Java

Difference ArrayList and Array in Java

Welcome back again on Java Code Online. Today I would be discussing the main difference between an ArrayList and an Array in Java.

In Java an Array is always of fixed size. The size has to be defined at the initializing time of the array. The number of the rows is a must for any array, though the number of columns may be specified later. By using Array, there is comparatively less flexibility, as the size need to be known before hand. And if you initialize an array that is too long, then it results in wastage of precious memory of the heap. The Garbage Collector then has a tough time maintaining the memory for other resources.

On the other hand, the ArrayList is dynamic in nature. It provides for automatic resizing of the List. Moreover you need not specify the size at the beginning of the initialization part. The ArrayList is therefore much more widely used as compared to an Array in Java. ArrayList is and extension of the List Interface. So it is a part of the Collections framework.

Talking about the drawbacks of ArrayList, then there is probably only one, and that is typecasting. When an Object is added to an ArrayList it goes inside as an Object, and so when it is retrieved back, then it needs to be typecast back into the original Object.

The Arrays have a positive point in this regard, that is an array is always of a particular type that is an array of ints, or an array of Strings, etc. So when data is retrieved back from an Array, then no typecasting is required.

More or less the advantages of an ArrayList makes it one of the most versatile and important tool in the Java coding, and arrays are left far behind in the race of fame.

Keep buzzing Java Code Online for more info on Java.

Addition of two numbers Java Program

Hello all of you. Welcome back to Java Code Online. Today I will be giving you a very simple and basic program of Java, that is the addition of two numbers. The code makes use of Scanner for getting the input from the console.

The code starts by asking the user to enter two numbers to be added. The user enters the first number, press enter, and then enters the second number and then press enter again. After this the code computes the addition of these two numbers.

The Java Code is provided below:-

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

package developer;

import java.util.Scanner;

public class AddTwoNumber {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Enter the first and second numbers");
//Get the first number
Scanner scanOne = new Scanner(System.in);
//Get the second number
Scanner scanTwo = new Scanner(System.in);

if(scanOne.hasNextInt() && scanTwo.hasNextInt())
{
System.out.print("The sum of the two numbers entered is: ");
System.out.println(scanOne.nextInt()+scanTwo.nextInt());
}

}

}

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

I hope that this basic code was beneficial for the beginners to Java Programming. For more information and programs on Java, keep buzzing Java Code Online.

Related Programs
Hello World Program in Java
Length of a String Java Program
Palindrome Program in Java