Showing posts with label java simple programs. Show all posts
Showing posts with label java simple programs. Show all posts

Sunday, 3 April 2016

for Loop Variations in Java

Variations of for loop in Java


               In order to increase the applicability of the for loop, it supports number of variations. for loop can be used without initialization statement, condition statement and iteration statement. They can kept empty.

for loop Variations

Variation 1: No initialization and iteration statement


               In the below program, we have intentionally kept the initialization and iteration part empty. Here we initialized the variable before the for loop and kept the increment statement inside the for loop. 

Program:


public class ForLoopVariationType1
{
    public static void main(String[] args)
    {
        int i=8;
        for(;i<12 i="">
        {
            System.out.println("i="+i);
            i++;
        }        
    }
}

Output:


i=8
i=9
i=10
i=11

Variation 2: No Condition Statement


               Here, we use the condition and exit statement inside the for loop. This is done by using the break statement inside the for loop body. when the value of i becomes 10 , the break statement terminates the for loop.


Program:


public class ForLoopVariationType2
{
    public static void main(String[] args)
    {
        int i=8;
        for(;;)
        {
            System.out.println("i="+i);
            i++;
            if (i==10)
                break;
        }      
    }
}

Output:


i=8
i=9
i=10
i=11

Variation 3: Infinite Loop


               Here is one more for loop variation. You can intentionally create an infinite loop (a loop that never terminates) if you leave all three parts of the for empty.

Program:


public class ForLoopVariationType3
{
    public static void main(String[] args)
    {      
        for(;;)
        {
            System.out.println("Infinite Loop");
        }
    }
}

Output:


Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop


Note: The same Infinite Loop Message Continues as it is an infinite condition-less loop.

Friday, 1 April 2016

Swap Numbers Without Using Third Variable Java Example

Java program to Swap Numbers Without Using Third Variable

Program:


public class SwapElement {  

    public static void main(String[] args) {
        
        int num1 = 10;
        int num2 = 20;
        
        System.out.println("Before Swapping");
        System.out.println("Value of num1 is :" + num1);
        System.out.println("Value of num2 is :" +num2);
        
        num1 = num1 + num2;
        num2 = num1 - num2;
        num1 = num1 - num2;
        
        System.out.println("Before Swapping");
        System.out.println("Value of num1 is :" + num1);
        System.out.println("Value of num2 is :" +num2);
    }  
}

Output: 


Before Swapping
Value of num1 is :10
Value of num2 is :20
Before Swapping
Value of num1 is :20

Value of num2 is :10

Monday, 22 February 2016

drawString() method of Graphics Class in Java

Details about the drawString() method in Java


               drawString is one of the most used method from teh Graphics class to generate text out in a Swing Window. The drawString() method can be used with abstract and void modifiers. 

General Syntax


i) drawString(String str, int x, int y)
ii) drawString(AttributedCharacterIterator iterator, int x, int y)

i) drawString(String str, int x, int y)


          String str is the string that can be displayed on the screen. Integer type x and y are the variables hold the x and y position on the graphical window. 

ii) drawString(AttributedCharacterIterator iterator, int x, int y)


         Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class. An AttributedCharacterIterator allows iteration through both text and related attribute information. An attribute is a key/value pair, identified by the key. No two attributes on a given character can have the same key. The values for an attribute are immutable, or must not be mutated by clients or storage. They are always passed by reference, and not cloned.

Example Program to Demonstrate drawString() method:


// drawString example program
import java.awt.*;
import java.applet.*;

public class HelloWorldApplet extends Applet{
    public void paint(Graphics g) {    

    g.drawString("Hello World", 100, 100);    

    }
}

Output:



Wednesday, 27 January 2016

Largest and Smallest Number in an Array

Java Program to Find the Largest and Smallest Number in an Array


                The below Java code finds the Smallest and Largest number from an array and print the output.

Program:


//Largest and Smallest Number in an Array

public class ArraySmallestLargest {
    public static void main(String args[]){      

      int x[]={56, 34, 43, 66, 78, 23};
      int largest=0;
      int smallest=0;
      for (int i = 0; i < x.length; i++){

          if(x[i] > largest)
              largest=x[i];
          else if(x[i] < smallest)
              smallest = x[i];        
      }

      System.out.println("Largest Number: " + largest);
      System.out.println("Smallest Number: " + smallest);

   }
}

Output:


Largest Number: 78
Smallest Number: 23

Saturday, 9 January 2016

JAVA Program to check whether a number is Palindrome

Palindrome number check USING JAVA

A program to accept a number from keyboard and check whether it is Palindrome.


//A small java program to check the given number is Palindrome or not.

import java.util.Scanner;

public class PalindromeExample {
  public static void main(String args[]){  
  int r,sum=0,temp;
  System.out.println("Enter a number to check whether it is Palindrome");
  Scanner in = new Scanner(System.in);  
  int n=in.nextInt();     //It is the number variable to be checked for palindrome
  int finalPrint = n;
  temp=n;    
  while(n>0){    
      r=n%10;  //getting remainder  
      sum=(sum*10)+r;    
      n=n/10;    
  }    
  if(temp==sum)    
      System.out.println(finalPrint +" is a palindrome number.");    
  else    
      System.out.println(finalPrint +" is not a palindrome number.");    
}  
}

Output:


Enter a number to check whether it is Palindrome
4554
4554 is a palindrome number.

Tuesday, 22 December 2015

Program to accept a number and display corresponding Month from an array

Java Program to print the Month Name


Demonstrate array operation using Month Name display program in Java


Program

public class MonthNameDisplay
{
    static String months[] =
    {
        null , "January" , "February" , "March" , "April", "May",
        "June", "July", "August", "September", "October",
        "November", "December"
    };
    public static void main( String[] args )
    {
        int m = Integer.parseInt( args[0] );
        System.out.println( months[ m ] );
    }
}

Output


java MonthNameDisplay 2
February

Thursday, 19 February 2015

Java Program to check whether a Number is Amstrong or Not

Find Armstrong Number using Java

Java Code to Display the Given Number is Armstrong


                    An Armstrong number is N digit number, Which is equal to the sum of the Nth powers of its digits.The Java programme will accept a number keyboard and the whether it is Armstrong.

Program:


import java.util.Scanner;

public class Armstrong {

   public static boolean isArmstrong(int input) {
       String inputAsString = input + "";
       int numberOfDigits = inputAsString.length();
       int copyOfInput = input;
       int sum = 0;
       while (copyOfInput != 0) {
           int lastDigit = copyOfInput % 10;
           sum = sum + (int) Math.pow(lastDigit, numberOfDigits);
           copyOfInput = copyOfInput / 10;
       }
           if (sum == input) {
           return true;
       } else {
           return false;
       }
   }

   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       System.out.print("Enter a number: ");
       int inputNumber = scanner.nextInt();
       boolean result = isArmstrong(inputNumber);
       if (result) {
           System.out.println(inputNumber + " is an armstrong ");
       } else {
           System.out.println(inputNumber + " is not an armstrong ");
       }
   }
}


Output:


Enter a number: 1634
1634 is an armstrong 

Java Program To Find Fibonacci Sequence

Fibonacci Series Of a Number Using Java

A program to print Fibonacci series of a given number


               The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...The next number is found by adding up the two numbers before it. Below example shows how to create Fibonacci series.

Program


import java.util.Scanner;
public class FibonacciJavaProgram{
public static void main(String a[]){
     
         System.out.print("Enter number up to which Fibonacci series to print: ");
         int febCount = new Scanner(System.in).nextInt(); 
         int[] feb = new int[febCount];
         feb[0] = 0;
         feb[1] = 1;
         
         for(int i=2; i < febCount; i++){
                   feb[i] = feb[i-1] + feb[i-2];            
         }
 
         for(int i=0; i< febCount; i++){
                 System.out.print(feb[i] + " ");
         }
    }
}  

Output


Enter number up to which Fibonacci series to print: 10
0 1 1 2 3 5 8 13 21 34                                                                                                               

Decimal to Binary Conversion

Conversion Of Decimal to Binary Using Java

 Java Code to Convert Decimal to Binary
                    
                        This program helps to convert the given Decimal number to Binary

Program:


import java.util.Scanner;

public class DecimalToBinary {

    public void printBinaryFormat(int number){
       
        int binary[] = new int[number];
        int index = 0;
       
        while(number > 0){
            binary[index++] = number%2;
            number = number/2;
        }
       
        for(int i = index-1;i >= 0;i--){
            System.out.print(binary[i]);
        }
    }
   
    public static void main(String a[]){
       
        int n;
        System.out.println("Enter a number to print decimal to binary");
        Scanner in = new Scanner(System.in);
        n = in.nextInt();

        DecimalToBinary dtb = new DecimalToBinary();
        dtb.printBinaryFormat(n);
    }
}



Output:


Enter a number to print decimal to binary
5
101

Monday, 16 February 2015

Java Program to Demonstrate the Compound Assignment Operators

Compound Assignment Operator Example Program in Java

A Program to show the use of Compound Assignment Operator


               The program shows a few compound assignment operators and how it can be used in programs to write program intelligently. This helps to reduce a few lines while writing a program. It is also efficient than normal coding.

Program:


// Demonstrate compound assignment operators.

public class CompoundAssignemntOperators {
    
    public static void main(String[] args) {
        
        int x = 1;
        int y = 3;
        int z = 5;
        
        x += 2;                    //Equals to x=x+2; Now x=3;
        y *= 4;                    //Equals to y=y*4; Now y=12;
        z += x * y;              // z= z+(x*y); Now z=41 i.e z=5+(3*12)
        z %= 6;                  // z= z%6; Now z=5; i.e z=41%6
        
        System.out.println("x = " + x);
        System.out.println("y = " + y);
        System.out.println("z = " + z);
    }
    
}

Output:


x = 3
y = 12
z = 5

Compound Assignment Operators Example Program

Monday, 24 November 2014

Char Data Type in Java

Unicode Character Representation In Java

A brief note about the way char Data Type used in Java Language.


                        Java uses Unicode to represent characters. Unicode provides a unique number for every character. char is a 16 bit data type and it ranges from 0 to 65536. Unicode standardization makes portability easier regardless of platform, program, and language.
Unicode
                    Unicode Character Set includes the characters from most of the known languages such as Latin, Greek, Arabic, Indonesia, Hindi, Sanskrit, French, German, Finnish, Irish, Italian, Malay, Chinese, Korean, Hebrew, Japanese etc..

                    Popular Leader in the Industry such as Apple, HP, IBM, Microsoft, SAP, Sybase, Unisys and many more adopted Unicode Standard.

A program which shows all Characters in Unicode Standard


// A simple Java Program to print all Unicode Characters

public class CharactersInJava {  

    public static void main(String[] args) {

        char ch1=0;
        //16 bit Unicode ranges from 0-65536
        for (int i = 0; i < 65536; i++) {          

            System.out.print(ch1);
            ch1++;
            if ( (i % 100) == 0)

               System.out.println();              
        }      
    }
}

Sunday, 5 October 2014

JAVA Program to Dispay Current Time in AM PM Method

Time Display USING JAVA

A program to show the current time using SimpleDateFormat Method.


//A small java program to print the time on the screen
import java.util.Date;
import java.text.SimpleDateFormat;

public class DateFormat {
   
    public static void main(String[] args) {

            Date date = new Date();
            String strDateFormat = "HH:mm:ss a";
            SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
            System.out.println(sdf.format(date));
    }
    
}

Output:


00:15:13 AM

Saturday, 4 October 2014

Java Code to Find the Perimeter

Perimeter of a Circle Using Java

A Java program to accept the radius of a Circle from user and calculate the Perimeter.


//A small java program to calculate the Perimeter of a circle

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

public class CirclePerimeter {

        public static void main(String[] args) {
               
                int radius = 0;
                System.out.println("Please enter radius of a circle");
               
                try
                {
                        //get the radius from console
                        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                        radius = Integer.parseInt(br.readLine());
                }
                //if invalid value was entered
                catch(NumberFormatException ne)
                {
                        System.out.println("Invalid radius value" + ne);
                        System.exit(0);
                }
                catch(IOException ioe)
                {
                        System.out.println("IO Error :" + ioe);
                        System.exit(0);
                }
               
                /*
                 * Perimeter of a circle is
                 * 2 * pi * r
                 * where r is a radius of a circle.
                 */
               
                //NOTE : use Math.PI constant to get value of pi
                double perimeter = 2 * Math.PI * radius;
               
                System.out.println("Perimeter of a circle is " + perimeter);
        }
}

Output:


Please enter radius of a circle
12
Perimeter of a circle is 75.39822368615503

Saturday, 17 May 2014

JAVA Program to Find the Factorial of a Number

Factorial of a number USING JAVA

A program to accept a number from keyboard and print the Factorial.


//A small java program to calculate the Factorial
import java.util.Scanner;
public class Factorial
{
public static void main(String[] args)
{           final int fact;
             System.out.println("Enter a number to find the Factorial");
             Scanner in = new Scanner(System.in);
             fact=in.nextInt();
             System.out.println( "Factorial of " + fact + " is " + factorial(fact));
}

public static int factorial(int n)
{ 
             int result = 1;
for(int i = 2; i <= n; i++)
result *= i;
return result;
}

}

Output:


Enter a number to find the Factorial
5
Factorial of 5 is 120

Saturday, 2 February 2013

if and if-else control statements in java

The most common Control Statements in Java

Control Statement if and if.. else

The if Statement:


In Java if statement is most widely used. The if statement is control statement which helps programmers in decision making. The if statement uses boolean expression in making decision whether a particular statement would execute or not. This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed. 

Thursday, 24 January 2013

Java Program to convert Lower Case Letter in to Uppper Case

Conversion of Lower Case letter to UpperCase in JAVA

toUpperCase(char ch) and toLowerCase(char ch) functions in Java


Syntax: public static char toUpperCase(char ch)


Converts the character argument to uppercase using case mapping information from the UnicodeData file. Note that Character.isUpperCase (Character.toUpperCase(ch)) does not always return true for some ranges of characters, particularly those that are symbols or

Monday, 21 January 2013

Code Comments in Java Program

Commenting Methods used in Java Program

Code comments in JAVA Source Code

Code comments are placed in source files to describe what is happening in the code to someone who might be reading the file, to comment-out lines of code to isolate the source of a problem for debugging purposes, or to generate API documentation. To these ends, the Java language supports three kinds of comments: double slashes, C-style, and doc comments.

Double Slashes

Double slashes (//) are used in the C++ programming language, and tell the compiler to treat everything from the slashes to the end of the line as text.

//A Very Simple Example

class ExampleProgram {
          public static void main(String[] args){
          System.out.println("I'm a Simple Program");
          }
}

C-Style Comments

Instead of double slashes, you can use C-style comments (/* */) to enclose one or more lines of code to be treated as text.

/* These are C-style comments */
class ExampleProgram {
         public static void main(String[] args){
         System.out.println("I'm a Simple Program");
         }
}

Doc Comments

To generate documentation for your program, use the doc comments (/** */) to enclose lines of text for the javadoc tool to find. The javadoc tool locates the doc comments embedded in source files and uses those comments to generate API documentation.

/** This class displays a text string at 
* the console.
*/
class ExampleProgram {
          public static void main(String[] args){
          System.out.println("I'm a Simple Program");
          }
}

Thursday, 17 January 2013

Addition of Two Numbers Java Programming Code

Java program to add two numbers

Simple Program to Add two numbers in Java



//A Simple Program to Add Two Numbers in Java Program.



class AddTwoNumbers        //Class Declaration
{
   public static void main(String args[]) //Main Function
   {
      int x, y, z;      // Variable Declaration
      x = 10;           //Assigning 10 to the variable x.
      y = 20;           //Assigning 20 to the variable y.
      z = x + y;        //Expression to Add two variables x, y and save the result to z
      System.out.println("Sum of x and y = "+z); //This line output the value of z on the Screen
   }
}


Output:

Sum of x and y =30