0% found this document useful (0 votes)
240 views

Java Tutorial Online

The document discusses a Java code sample that converts temperatures between Celsius and Fahrenheit. It includes the full Java code to convert from Celsius to Fahrenheit, which takes a temperature in Celsius as input from the user and displays the equivalent in Fahrenheit. It also runs through an example execution of the code, showing the input of 102.87 Celsius and output of 217.166 Fahrenheit. The document is a post from a Java coding blog that provides various code samples and tutorials.

Uploaded by

Siva Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
240 views

Java Tutorial Online

The document discusses a Java code sample that converts temperatures between Celsius and Fahrenheit. It includes the full Java code to convert from Celsius to Fahrenheit, which takes a temperature in Celsius as input from the user and displays the equivalent in Fahrenheit. It also runs through an example execution of the code, showing the input of 102.87 Celsius and output of 217.166 Fahrenheit. The document is a post from a Java coding blog that provides various code samples and tutorials.

Uploaded by

Siva Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Java Tutorial Online

Showing newest posts with label Java Code. Show older posts
Showing newest posts with label Java Code. Show older posts

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
Posted by amitberiwal at 12:18 AM 0 comments Links to this post
Labels: Java Code, Java Example

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
Posted by amitberiwal at 10:45 PM 1 comments Links to this post
Labels: Java Code, Java Example

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
Posted by amitberiwal at 9:43 PM 0 comments Links to this post
Labels: Java Code, Java Example

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
Posted by amitberiwal at 9:08 PM 0 comments Links to this post
Labels: Java Code, Java Example

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.
Posted by amitberiwal at 1:39 AM 0 comments Links to this post
Labels: File, File Handling, Java Code, Java Program

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
Posted by amitberiwal at 9:41 PM 1 comments Links to this post
Labels: File, File Handling, Java Code, Java Program

Sunday, September 6, 2009


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
Posted by amitberiwal at 8:42 PM 0 comments Links to this post
Labels: Java Basics, Java Code, Java Interview Questions, Scanner, String

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
Posted by amitberiwal at 2:59 PM 0 comments Links to this post
Labels: Java Code, Java Example, Java Program, 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
Posted by amitberiwal at 9:47 PM 3 comments Links to this post
Labels: Java Code, Java Interview Questions, String In Java

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
Posted by amitberiwal at 1:53 AM 1 comments Links to this post
Labels: Armstrong Number, Java Code, Java Example, Java Program, Math, Scanner

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
Posted by amitberiwal at 12:00 AM 1 comments Links to this post
Labels: Addition, Java Basics, Java Code, Java Example, Java Program, Scanner
Tuesday, August 18, 2009
Factors of a number Java Program

Hi all of you. The following article at Java Code Online is going to discuss the code for finding
the factors of a number entered by the user. The Java Program starts by prompting the user to
enter a number, and then displays the all the factors of the number entered by the user.

The factors of a number are the numbers which divide the number entered by the user
completely.

The Java Example Code is given below:-

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

package developer;

import java.util.Scanner;

public class Factor {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Enter a number whose factors are desired: ");
Scanner scanNum = new Scanner(System.in);
int numFac = 0;
if(scanNum.hasNextInt())
{
numFac = scanNum.nextInt();
}

System.out.println("The Factors of the entered number are:-");

for(int i = 1; i <= numFac; i++)


{
if(numFac%i == 0)
{
System.out.print(i+" ");
}
}

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

The Java Code above finds all the factors of the number entered by the user. For more interesting
information on Java, keep checking Java Code Online.

Related links:-

Prime Factors Java Program


Factorial of a Number Java Program
Posted by amitberiwal at 8:39 PM 0 comments Links to this post
Labels: Factors, Java Code, Java Example, Java Program

Prime Factors Java Program

Hello all of you. Today at Java Code Online, I would be discussing the Java Code for finding all
the prime factors of an entered number.

Prime Factors are those numbers which are factors of the entered number, and also are Prime in
nature. For being a factor, the number needs to divide completely the entered number. For
example, f I say that the user entered 20, then the factors of this number are 1 2 4 5 10 and 20,
but when we say about Prime Factors then out of these only 2 and 5 are prime, so 2 and 5 are the
Prime factors of the number 20 which is entered by the user.

The complete Java code is given below:-

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

package developer;

import java.util.Scanner;

public class PrimeFactor {

static int primeCheck = 1;

public static void main(String[] args) {


System.out.println("Enter a number whose Prime factors are desired: ");
Scanner numS = new Scanner(System.in);
int numPriFac = 0;
if(numS.hasNextInt())
{
numPriFac = numS.nextInt();
}

System.out.println("All the Prime Factors of the entered number are:-");


for(int tap = 1; tap <= numPriFac; tap++)
{
if(numPriFac%tap == 0)
{
for(int primeTest = 2; primeTest < tap; primeTest++)
{
if(tap%primeTest == 0)
{
primeCheck = 1;
break;
}
else
{
primeCheck = 0;
}
}
if(primeCheck == 0 || tap == 2)
{
System.out.print(tap+ " ");
}
}
}
}
}

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

I hope the code was helpful to all of you. Java Code Online keeps on discussing various Java
codes, so keep checking for new updates.

Related Links:-
Prime Number program in Java
Largest Prime number Java Program
Smallest Prime Number Java Program
Prime Number Series Java Program
Posted by amitberiwal at 8:27 PM 0 comments Links to this post
Labels: Factors, Java Code, Java Example, Java Program, Prime Number

Monday, August 17, 2009


Prime Number Series Java Program

Hi friends, welcome back to Java Code Online. Today I will be discussing the Java Code to
generate a series of Prime Numbers. The series of Prime Numbers all the Prime numbers which
are less then the number provided by the user.
The Java Code starts by asking the user to enter a number, and then displays all the Prime
Numbers which are less then or equal to that number. This program generates all the prime
numbers less then a number, so it is a series of Prime Numbers.

The Java Code is provided below:-

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

package developer;

import java.util.Scanner;

public class PrimeNumberSeries {

public static void main(String[] args)


{
int numero = 0;
System.out.println("Enter a number:");
Scanner takeValue = new Scanner(System.in);
if(takeValue.hasNextInt())
{
numero = takeValue.nextInt();
}
System.out.println("All the Prime Numbers, which are less then or equal to the number entered
are:");
checkPrimeNumber(numero);
}

static void checkPrimeNumber(int val)


{
int tapper = 0;

for (int i=2; i < val; i++ ){


if(val%i == 0)
{
tapper = 0;
break;
}
else
{
tapper = 1;
}
}
if(tapper == 1 || val == 2)
{
System.out.print(val+" ");
if(val > 2)
checkPrimeNumber(val-1);
}
else
{
if(val > 2)
checkPrimeNumber(val-1);
else
System.out.println("Number out of range");
}
}
}

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

I hope the Java Code was helpful to you all. Keep buzzing Java Code Online, for more info on
Java.

Related Java Programs


Prime Number program in Java
Largest Prime number Java Program
Smallest Prime Number Java Program
Posted by amitberiwal at 9:05 PM 0 comments Links to this post
Labels: Java Code, Java Example, Java Program, Prime Number, Recursion

Sunday, August 16, 2009


Smallest Prime Number Java Program

Hi friends, today Java Code Online will be discussing the Java code for finding the smallest
Prime number, which is greater then the number provided by the user.

The Java code starts by asking the user to enter a number, and then it generates the smallest
Prime number which is greater then the user provided number.

The Java Code is given below:-

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

package developer;

import java.util.Scanner;

public class SmallestPrime {


public static void main(String[] args)
{
int num = 0;
System.out.println("Enter a number:");
//get the input from the console
Scanner scan = new Scanner(System.in);
if(scan.hasNextInt())
{
num = scan.nextInt();
}
checkPrime(num);
}

static void checkPrime(int num)


{
int check = 0;

for (int i=2; i < num; i++ ){


if(num%i == 0)
{
check = 0;
break;
}
else
{
check = 1;
}
}
if(check == 1 || num == 2)
{
System.out.println("The smallest prime number which is greater then or equal to the number
provided is: "+num);
}
else
{
if(num > 0)
checkPrime(num+1);//Recursion in use
else
System.out.println("Number out of range");
}
}
}
////////////////////////////////

Hope that the provided Java code was beneficial to you all. Keep checking Java Code Online for
more info on Java.
Related Programs
Prime Number program in Java
Largest Prime number Java Program
Posted by amitberiwal at 10:39 PM 0 comments Links to this post
Labels: Java Code, Java Example, Java Program, Prime Number, Recursion

Largest Prime Number Java Program

Hi friends, welcome back to Java Code Online. Today I will be discussing the Java Code, to find
the largest prime number, which is smaller then the number provided by the user.

A prime number is a positive integer which is divisible by 1 and itself only. The Java Code for
finding the largest Prime number which is lower then the number provided by the user is given
below:-

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

import java.util.Scanner;

public class LargestPrime {

public static void main(String[] args)


{
int num = 0;
System.out.println("Enter a number:");
Scanner scan = new Scanner(System.in);
if(scan.hasNextInt())
{
num = scan.nextInt();
}
checkPrime(num);
}

static void checkPrime(int num)


{
int check = 0;

for (int i=2; i < num; i++ ){


if(num%i == 0)
{
check = 0;
break;
}
else
{
check = 1;
}
}
if(check == 1 || num == 2)
{
System.out.println("The largest prime number which is less then or equal to the number provided
is: "+num);
}
else
{
if(num > 2)
checkPrime(num-1);
else
System.out.println("Number out of range");
}
}
}
//////////////////////////////

I hope the above Java code was helpful to you all. For more info on Java keep buzzing Java Code
Online.

Related Java Programs


Prime Number program in Java
Posted by amitberiwal at 10:28 PM 0 comments Links to this post
Labels: Java Code, Java Example, Java Program, Prime Number, Recursion

Floyd Triangle Program in Java

Welcome back again, today at Java Code Online, I would be discussing the Java code for
Floyd's Triangle.

The Floyd's triangle starts from 1, it is a right angled triangle, consisting of consecutive numbers.
If suppose four rows of the Floyd's Triangle need to be generated, then the output will be, the
first row contains 1, the second row contains 2 3, the third row contains 4 5 6, and the last row
contains 7 8 9 10. I hope that will clear your concept about the Floyd's Triangle. One more
intresting fact about this triangle is that all the last numbers of each row are Triangular numbers.

The Java Code provided, asks the user to enter the number of rows till which the Floyd's
Triangle is desired, and then generates it. The Java Program is given below:-

package developer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FloydTriangle {

static int counter = 0;


/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
System.out.println("Enter the number of rows for Floyd Triangle:");
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);

int num = Integer.parseInt(br.readLine());

for(int i = 1; i <= num; i++)


{
for(int j = 1; j <= i; j++)
{
counter = counter + 1;
System.out.print(counter);
System.out.print(" ");
}
System.out.println("");
}

}
}

I hope that this post was helpful to you all. Kindly leave your comments in case you liked the
above code. For more info on Java, keep buzzing Java Code Online.
Posted by amitberiwal at 2:34 AM 2 comments Links to this post
Labels: Floyd Triangle, Java Code, Java Example, Java Program, Triangular Number

Triangular Number Program in Java

Hi friends, today Java Code Online is going to discuss the Java Code for generating the
Triangular Numbers up to the entered number of times.

A Triangular Number is one which is the sum of all the numbers starting from 1 up to that
particular number. For example if I say the number is 3, then 1+2+3=6, so 6 is the third
Triangular Number.
The provided Java code asks the user, to enter the required number of Triangular Numbers, and
then generate that many Triangular Numbers starting from 1.

The Java Code is provided below:-

package developer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TriangularNumber {

/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
System.out.println("How many Triangular Numbers are required:");
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
int j = 1;
int num = Integer.parseInt(br.readLine());

for(int i = 1; i<= num; i++)


{
j = i * (i+1)/2;
System.out.print(j + " ");
}
}
}

I hope the above Java Code was helpful to you all. Keep buzzing Java Code Online for more
interesting Java information and programs.
Posted by amitberiwal at 2:23 AM 0 comments Links to this post
Labels: Floyd Triangle, Java Code, Java Example, Java Program, Triangular Number

Pascal Triangle in Java

Hi friends, today at Java Code Online, I am going to discuss a very


interesting yet basic Java program, that displays the Pascal Triangle for any
given integer value.

A Pascal Triangle is a triangle in which a triangle is formed of numbers, in


which 1 is displayed one time, 2 is displayed two times, 3 is displayed three
times, and so on, up to the entered value of the integer value. Each of these
different numbers are displayed on different lines, but the same number is
displayed on the same line. The whole structure is in the form of a triangle,
and it is called Pascal Triangle.

The Java Code is provided below, the code asks the user to enter a number,
and then prints the Pascal Triangle up to that many rows:-

 package developer;

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;

 public class Pascal {


    public static void main(String[] args) throws IOException {
        System.out.println("Enter the number of rows for which the Pascal
Triangle is requird: ");
        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader bf = new BufferedReader(is);
        int numRow = Integer.parseInt(bf.readLine());

        for (int i = 1; i <= numRow; i++) {


            // Prints the blank spaces
            for (int j = 1; j <= numRow - i; j++) {
                System.out.print(" ");
            }
            // Prints the value of the number
            for (int k = 1; k <= i; k++) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
 }

I hope the above code was helpful to you all. For more information on Java,
you know that Java Code Online is the place you need to be at.

Other Java Programs that might be of interest:-


Palindrome Program in Java
Factorial Program in Java
Fibonacci Series Program in Java
Prime Number Program in Java
String In Java
Posted by amitberiwal at 12:55 AM 1 comments Links to this post
Labels: Java Code, Java Example, Java Program, Pascal Triangle

Friday, August 14, 2009


Palindrome Java Program

Hi friends, welcome back to Java Code Online. Today I will be discussing the Java Program to
find out whether any entered String or number or any combination of them is a Palindrome or
not.

A Palindrome is a string or number, that is exactly the same when it is read in the reverse order.
That is for example "anna" is a palindrome, i.e. read the same either way.

The Java code for finding the Palindrome is given below:-

//////////////////////////////
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Palindrome {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
System.out.println("Enter a number or String to be checked for Palindrome");
InputStreamReader io = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(io);
String num = br.readLine();
StringBuffer num2 = new StringBuffer().append(num);
if(num.equals(num2.reverse().toString()))
{
System.out.println("It is a Palindrome");
}
else
{
System.out.println("It is not Palindrome");
}

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

I hope the Java code provided for finding the Palindrome was helpful to you all. For more info
on Java, keep checking Java Code Online.
Posted by amitberiwal at 10:58 PM 1 comments Links to this post
Labels: Java Code, Java Example, Java Program, Palindrome, String
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Java Specials
 String in Java
 Convert int to String in Java
 Convert String to int in Java

Blog Roll Blog Archive


 ►  2010 (9)
 o ►  December (7)
 Java Substring Compare Example
Improve  Substring Index Out of Range or
Spoken English StringIndexOutOfBo...
 Search and Replace a Substring in Java Example
 Java Substring Index
 Java Substring Examples
 Substring in Java
 String In Java
o ►  March (2)
 Java DataBase Connectivity JDBC
 Creating a database in Oracle using dmp file

 ▼  2009 (60)
o ►  October (1)
 Static Inner Class Example in Java
o ▼  September (14)
 Convert Celsius to Fahrenheit Java Code
 Convert Fahrenheit to Celsius Java Code
 Java Code to Convert Binary to Decimal
 Java Code to Convert Decimal to Binary
 Java Code to write to CSV File
 Check out the tutorial at the Sun site
 How to get Java
 Blogger Blogging on Blogspot
 Java Code to Delete a File
 Java Code to Create a File
 Java Code to Write to a File
 Java Code to Read a File
 Convert String to integer (int) in Java
 Convert int to String using Wrapper in Java
o ►  August (26)
 Convert int to String in Java Code
 Deadly Diamond of Death
 What are final methods in Java
 What is an Interface in Java
 Java Code for File Extension
 Remove Extension of File Java Code
 Anonymous Inner Class in Java
 Method Local Inner Class in Java
 Static Inner Nested Class in Java
 Regular Inner Class in Java
 Types of Inner Class in Java
 Armstrong Number Java Program
 Difference ArrayList and Array in Java
 Addition of two numbers Java Program
 Factors of a number Java Program
 Prime Factors Java Program
 Prime Number Series Java Program
 Sun Certified Java Programer (SCJP) Syllabus
 Smallest Prime Number Java Program
 Largest Prime Number Java Program
 Floyd Triangle Program in Java
 Triangular Number Program in Java
 Pascal Triangle in Java
 Palindrome Java Program
 Number of words in a String - Java Program
 Desending Sort - Java Program
o ►  July (9)
o ►  February (1)
o ►  January (9)

 ►  2008 (24)
o ►  December (24)
Followers

Labels
Java Basics (45) Java Interview Questions (36) Java Tutorial (33) Java Code (31) Java Example
(27) Java Program (24) OOPS Principles (9) String In Java (8) File (7) Inner Classes (6) String
(6) File Handling (5) Prime Number (5) Scanner (5) Recursion (4) java.io package (3)
Collections (2) Factors (2) Floyd Triangle (2) Interface (2) Java Certifications (2) Method (2)
SCJP (2) TreeSet (2) Triangular Number (2) Addition (1) Armstrong Number (1) ArrayList (1)
Circle (1) Factorial (1) Fibonacci Series (1) JDBC (1) Java Resources (1) Math (1) Oracle (1)
Palindrome (1) Pascal Triangle (1) Rectangle (1) SQL Developer (1) Sorting (1) final (1)

Popular Posts All time


 Pascal Triangle in Java

Hi friends, today at Java Code Online, I am going to discuss a very interesting yet basic
Java program, that displays the Pascal Triangle fo...

 Triangular Number Program in Java

Hi friends, today Java Code Online is going to discuss the Java Code for generating the
Triangular Numbers up to the entered number of times...

 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 Nu...

 Floyd Triangle Program in Java

Welcome back again, today at Java Code Online, I would be discussing the Java code for
Floyd's Triangle. The Floyd's triangle starts from 1...

 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...
 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 ...

 Java Program for Fibonacci Series, Fibonacci Series Example in Java

Welcome back to Java Code Online. Today I am going to give you the Java code for
generating Fibonacci Series up to a particular number. A Fi...

 Palindrome Java Program

Hi friends, welcome back to Java Code Online. Today I will be discussing the Java
Program to find out whether any entered String or number o...

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 ...

 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 di...

Popular Posts 30 days


 Pascal Triangle in Java

Hi friends, today at Java Code Online, I am going to discuss a very interesting yet basic
Java program, that displays the Pascal Triangle fo...

 Triangular Number Program in Java

Hi friends, today Java Code Online is going to discuss the Java Code for generating the
Triangular Numbers up to the entered number of times...

 Floyd Triangle Program in Java


Welcome back again, today at Java Code Online, I would be discussing the Java code for
Floyd's Triangle. The Floyd's triangle starts from 1...

 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...

 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 Nu...

 Prime Factors Java Program

Hello all of you. Today at Java Code Online, I would be discussing the Java Code for
finding all the prime factors of an entered number. Pr...

 Java Program for Fibonacci Series, Fibonacci Series Example in Java

Welcome back to Java Code Online. Today I am going to give you the Java code for
generating Fibonacci Series up to a particular number. A Fi...

 Java Program to find the Area and Circumference of Circle

Hi friends, welcome back to Java Code Online. Today I will give you a simple Java
Program to find the Area and Circumference of a Circle. T...

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 ...

 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 di...
Popular Posts 7 days
 Pascal Triangle in Java

Hi friends, today at Java Code Online, I am going to discuss a very interesting yet basic
Java program, that displays the Pascal Triangle fo...

 Triangular Number Program in Java

Hi friends, today Java Code Online is going to discuss the Java Code for generating the
Triangular Numbers up to the entered number of times...

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 ...

 Floyd Triangle Program in Java

Welcome back again, today at Java Code Online, I would be discussing the Java code for
Floyd's Triangle. The Floyd's triangle starts from 1...

 Prime Factors Java Program

Hello all of you. Today at Java Code Online, I would be discussing the Java Code for
finding all the prime factors of an entered number. Pr...

 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...

 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 Nu...

 Java Program for Fibonacci Series, Fibonacci Series Example in Java


Welcome back to Java Code Online. Today I am going to give you the Java code for
generating Fibonacci Series up to a particular number. A Fi...

 Java Program to find the Area and Circumference of Circle

Hi friends, welcome back to Java Code Online. Today I will give you a simple Java
Program to find the Area and Circumference of a Circle. T...

 Largest Prime Number Java Program

Hi friends, welcome back to Java Code Online. Today I will be discussing the Java Code,
to find the largest prime number, which is smaller t...

Simple template. Powered by Blogger.

You might also like