Tuesday, 23 June 2015

Event Monitoring in Message Broker

1. OVERVIEW:

1.1  INTRODUCTION :

Ø  Event monitoring is feature which lets you configure a message flow to emit monitoring events without any coding. As the configured events occur in the message flow, XML documents are generated and published as pre-defined topics by the broker on which the message flow is deployed.     

            1.2  PURPOSE OF EVENT MONITORING:

Ø  Message flows can be configured to emit events. The events can be read and used by other applications for transaction monitoring, transaction auditing, and business process monitoring.
Ø  An event is a message that a message flow publishes when something interesting or desired happens.
Ø  The message contains information about the source of the event, the time of the event, and the reason for the event. The event can include the message bit stream, and can also include selected elements from the message body. These fields can be used to  convey business data to a monitoring application.


              
2. SYSYTEM REQUIREMENTS:

COMPONENTS
VERSIONS
Websphere MQ Explorer
Websphere MQ Explorer V6.1 or later
Websphere Message Broker components
Websphere Message Broker V6.1.0.3 or later


3 PRE REQUISITES:
 
  3.1 CONCEPTS :

The concepts that we need to know
Ø  Publish/subscribe.
Ø  Monitoring Events:- A monitoring event is an XML document that conforms to the monitoring event schema. Each event contains source of the event ,name of the event ,sequence number and creation time ,correlation id for events emitted by the same transaction or unit of work ,application data extracted from the message .
Ø  Types of Events.
Ø  Transaction Events:Transaction events are emitted only from input nodes.
Ø  Transaction start :The event is emitted when the message is read from the transport.
Ø  Transaction end :The event is emitted when WebSphere Message Broker has completed all processing of the message.
Ø  Transaction rollback :The event is emitted instead of transaction end if the message flow throws an exception which is not caught and processed within the message flow.
Ø  Terminal Events:Terminal events are emitted from any terminal of any node, including input nodes(Failure,Catch,Out).


4.FUNCTIONALITY AND SCENARIO:

    4.1 ILLUSTRATION:

           4.1.1 CONFIGURING A MESSAGE FLOW TO GENERATE MONITORING EVENTS
Ø  We can configure monitoring events to emit without any coding as follows:
Ø  In the node properties we can find a property called monitoring, which needs to be set inorder to emit an event.
Ø  We need to select event source, event name and the event pay load .
Ø  Event Payload is where we will be writing an X-path expression , whose value needs to be extracted from the message.
Ø  As the event occurs an XML document is generated and published in a predefined topic by the broker in the flow is deployed.
       
            4.1.2 COMMAND FOR ACTIVATING THE EVENTS:
Ø   command to activate:
mqsichangeflowmonitoring brokername -e executaiongroupname -f flowname -c active
Ø  Use -c inactive to inactivate.
Ø  Status for monitoring:
mqsireportflowmonitoring brokername -e executaiongroupname -f flowname -a
 
           4.1.3 SUBSCRIBING AND RETRIVING THE MESSAGE:
Ø  As the event message is generated and published in the topic , we need to subscribe it to retrive the event message.
Ø  This subscription can be done by directly subscribing from the MQ or through a subscription flow.
         
          4.1.4 Topics:
Ø  The format of the topic string is
$SYS/Broker/<BrokerName>/Monitoring/<ExecutionGroupName>/<MessageFlowName>
Ø  Topic string for a specfic message flow and specific execution group is
$SYS/Broker/BRK1/Monitoring/default/MonitoringEvents_MF
Ø  Topic string for allmessage flow among all execution group is
$SYS/Broker/BRK1/Monitoring/#/#.
Where # is a wild card indicating all .

         4.1.5  FLOWS ACROSS DIFFERENT BROKERS:            
Ø  By using distribution queueing we can place the event messages of  all flows across different brokers.
Ø  For instance if we have two brokers say brk1 and brk2 .
Ø  We need to place all the event messages of all the flows from two brokers  in  a queue of brk1.
Ø  Hence queue's from different brokers queue manager will subscribe indvidually and then we need to create a distribution queueing between two queue managers.


4.2 EXECUTION:
  
     4.2.1 CONFIGURING A MESSAGE FLOW TO GENERATE MONITORING EVENTS:

Ø  selcet monitoring property and click on add.



Ø  select the basic tab ,set event source,event name, select event payload and click add to add an X-path expression .



Ø  Adding an X path expression in event payload

Ø   Different kinds of expressions.

  4.2.2 COMMAND FOR ACTIVATING THE EVENTS:
              
                     Command for activating :

Ø  "mqsichangeflowmonitoring brokername -e ExecutionGroupname -f Flowname -c active"

Command for status:
Ø  mqsireportflowmonitoring brokername -e executiongroupname -f flowname –a

Ø   





  4.2.3 SUBSCRIBING  THE TOPIC:
       
Ø   select the subscription object in the queue manager.






Ø  Select new and subscription


 


Ø  Now we give topic string and queue name to which needs to be subscribed .
Ø  Topic string for a specific flow and execution group.

Ø  Topic string for all flows across all execution group.







Ø  Event message :
      



Ø  Where the XML message consists of broker name, execution group name , flow name and the MsId which is extracted from the message.

Ø  This message is produced when then third property of the event pay load is ocured .



Ø  The value will be true when the condition is meet, else it will be false.






  Basic Java Programs


  • Java program to check palindrome

Java palindrome program: Java program to check if a string is a palindrome or not. Remember a string is a palindrome if it remains unchanged when reversed, for example "dad" is a palindrome as reverse of "dad" is "dad" whereas "program" is not a palindrome. Some other palindrome strings are "mom", "madam", "abcba".

Java programming source code

import java.util.*;
 
class Palindrome
{
   public static void main(String args[])
   {
      String original, reverse = "";
      Scanner in = new Scanner(System.in);
 
      System.out.println("Enter a string to check if it is a palindrome");
      original = in.nextLine();
 
      int length = original.length();
 
      for ( int i = length - 1; i >= 0; i-- )
         reverse = reverse + original.charAt(i);
 
      if (original.equals(reverse))
         System.out.println("Entered string is a palindrome.");
      else
         System.out.println("Entered string is not a palindrome.");
 
   }

}       




Another method to check palindrome:
import java.util.*;
 
class Palindrome
{
  public static void main(String args[])
  {
    String inputString;
    Scanner in = new Scanner(System.in);
 
    System.out.println("Input a string");
    inputString = in.nextLine();
 
    int length  = inputString.length();
    int i, begin, end, middle;
 
    begin  = 0;
    end    = length - 1;
    middle = (begin + end)/2;
 
    for (i = begin; i <= middle; i++) {
      if (inputString.charAt(begin) == inputString.charAt(end)) {
        begin++;
        end--;
      }
      else {
        break;
      }
    }
    if (i == middle + 1) {
      System.out.println("Palindrome");
    }
    else {
      System.out.println("Not a palindrome");
    }   
  }
}

  • Java if else program

Java if else program uses if else to execute statement(s) when a condition is fulfilled. Below is a simple program which explains the usage of if else in java programming language.

Java programming if else statement

// If else in Java code
import java.util.Scanner;
 
class IfElse {
  public static void main(String[] args) {
    int marksObtained, passingMarks;
 
    passingMarks = 40;
 
    Scanner input = new Scanner(System.in);
 
    System.out.println("Input marks scored by you");
 
    marksObtained = input.nextInt();
 
    if (marksObtained >= passingMarks) {
      System.out.println("You passed the exam.");
    }
    else {
      System.out.println("Unfortunately you failed to pass the exam.");
    }
  }
}
Output of program:




Above program ask the user to enter marks obtained in exam and the input marks are compared against minimum passing marks. Appropriate message is printed on screen based on whether user passed the exam or not. In the above code both if and else block contain only one statement but we can execute as many statements as required.

Nestd If Else statements

You can use nested if else which means that you can use if else statements in any if or else block.
import java.util.Scanner;
 
class NestedIfElse {
  public static void main(String[] args) {
    int marksObtained, passingMarks;
    char grade;
 
    passingMarks = 40;
 
    Scanner input = new Scanner(System.in);
 
    System.out.println("Input marks scored by you");
 
    marksObtained = input.nextInt();
 
    if (marksObtained >= passingMarks) {
 
      if (marksObtained > 90) 
        grade = 'A';
      else if (marksObtained > 75)
        grade = 'B';
      else if (marksObtained > 60)
        grade = 'C';
      else
        grade = 'D'; 
 
      System.out.println("You passed the exam and your grade is " + grade);
    }
    else {
      grade = 'F'; 
      System.out.println("You failed and your grade is " + grade);
    }
  }
}

Java for loop

Java for loop used to repeat execution of statement(s) until a certain condition holds true. for is a keyword in Java programming language.

Java for loop syntax

for (/* Initialization of variables */ ; /*Conditions to test*/ ; /* Increment(s) or decrement(s) of variables */) {
  // Statements to execute i.e. Body of for loop
}
You can initialize multiple variables, test many conditions and perform increments or decrements on many variables according to requirement. Please note that all three components of for loop are optional. For example following for loop prints "Java programmer" indefinitely.
// Infinite for loop
for (;;) {
  System.out.println("Java programmer");
}
You can terminate an infinite loop by pressing Ctrl+C.

Simple for loop example in Java

Example program below uses for loop to print first 10 natural numbers i.e. from 1 to 10.
//Java for loop program
class ForLoop {
  public static void main(String[] args) {
    int c;
 
    for (c = 1; c <= 10; c++) {
      System.out.println(c);
    }
  }
}

Java for loop example to print stars in console

Following star pattern is printed * ** *** **** *****
class Stars {
  public static void main(String[] args) {
    int row, numberOfStars;
 
    for (row = 1; row <= 10; row++) {
      for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) {
        System.out.print("*");
      }
      System.out.println(); // Go to next line
    }
  }
}
Above program uses nested for loops (for loop inside a for loop) to print stars. You can also use spaces to create another pattern, It is left for you as an exercise.

Java while loop

Java while loop is used to execute statement(s) until a condition holds true. In this tutorial we will learn looping using Java while loop examples. First of all lets discuss while loop syntax:
while (condition(s)) { // Body of loop }
1. If the condition holds true then the body of loop is executed, after execution of loop body condition is tested again and if the condition is true then body of loop is executed again and the process repeats until condition becomes false. Condition is always evaluated to true or false and if it is a constant, For example while (c) { …} where c is a constant then any non zero value of c is considered true and zero is considered false.
2. You can test multiple conditions such as
while ( a > b && c != 0) {
 // Loop body
}
Loop body is executed till value of a is greater than value of b and c is not equal to zero.
3. Body of loop can contain more than one statement. For multiple statements you need to place them in a block using {} and if body of loop contain only single statement you can optionally use {}. It is recommended to use braces always to make your program easily readable and understandable.

Java while loop example

Following program asks the user to input an integer and prints it until user enter 0 (zero).
import java.util.Scanner;
 
class WhileLoop {
  public static void main(String[] args) {
    int n;
 
    Scanner input = new Scanner(System.in);
    System.out.println("Input an integer"); 
 
    while ((n = input.nextInt()) != 0) {
      System.out.println("You entered " + n);
      System.out.println("Input an integer");
    }
 
    System.out.println("Out of loop");
  }
}
Above program can be written in a more compact way as follows:
// Java while loop user input 
import java.util.Scanner;
 
class WhileLoop {
  public static void main(String[] args) {
    int n;
 
    Scanner input = new Scanner(System.in);
    System.out.println("Input an integer"); 
 
    while ((n = input.nextInt()) != 0) {
      System.out.println("You entered " + n);
      System.out.println("Input an integer");
    }
  }
}

Java while loop break program

Here we write above program but uses break statement. The condition in while loop here is always true so we test the user input and if its is zero then we use break to exit or come out of the loop.
import java.util.Scanner;
 
class BreakWhileLoop {
  public static void main(String[] args) {
    int n;
 
    Scanner input = new Scanner(System.in);
 
    while (true) {
      System.out.println("Input an integer");
      n = input.nextInt();
 
      if (n == 0) {
        break;
      }
      System.out.println("You entered " + n);
    }
  }
}

Java while loop break continue program

import java.util.Scanner;
 
class BreakContinueWhileLoop {
  public static void main(String[] args) {
    int n;
 
    Scanner input = new Scanner(System.in);
 
    while (true) {
      System.out.println("Input an integer");
      n = input.nextInt();
 
      if (n != 0) {
        System.out.println("You entered " + n);
        continue;
      }
      else {
        break;
      }
    }
  }
}
Whatever you can do with while loop can be done with for and do while loop.

Java program to print alphabets

This program print alphabets on screen i.e a, b, c, ..., z. Here we print alphabets in lower case.

Java source code

class Alphabets
{
   public static void main(String args[])
   {
      char ch;
 
      for( ch = 'a' ; ch <= 'z' ; ch++ )
         System.out.println(ch);
   }
}

print multiplication table

This java program prints multiplication table of a number entered by the user using a for loop. You can modify it for while or do while loop for practice.

Java programming source code

import java.util.Scanner;
 
class MultiplicationTable
{
   public static void main(String args[])
   {
      int n, c;
      System.out.println("Enter an integer to print it's multiplication table");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();
      System.out.println("Multiplication table of "+n+" is :-");
 
      for ( c = 1 ; c <= 10 ; c++ )
         System.out.println(n+"*"+c+" = "+(n*c));
   }
}
Using nested loops we can print tables of number between a given range say a to b, For example if the input numbers are 3 and 6 then tables of 3, 4, 5 and 6 will be printed. Code:
import java.util.Scanner;
 
class Tables
{
  public static void main(String args[])
  {
    int a, b, c, d;
 
    System.out.println("Enter range of numbers to print their multiplication table");
    Scanner in = new Scanner(System.in);
 
    a = in.nextInt();
    b = in.nextInt();
 
    for (c = a; c <= b; c++) {
      System.out.println("Multiplication table of "+c);
 
      for (d = 1; d <= 10; d++) {
         System.out.println(c+"*"+d+" = "+(c*d));
      }
    }
  }
}

How to get input from user in java

This program tells you how to get input from user in a java program. We are using Scanner class to get input from user. This program firstly asks the user to enter a string and then the string is printed, then an integer and entered integer is also printed and finally a float and it is also printed on the screen. Scanner class is present in java.util package so we import this package in our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement
 Scanner a = new Scanner(System.in);
Here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream. Following methods of Scanner class are used in the program below :- 1) nextInt to input an integer 2) nextFloat to input a float 3) nextLine to input a string

Java programming source code

import java.util.Scanner;
 
class GetInputFromUser
{
   public static void main(String args[])
   {
      int a;
      float b;
      String s;
 
      Scanner in = new Scanner(System.in);
 
      System.out.println("Enter a string");
      s = in.nextLine();
      System.out.println("You entered string "+s);
 
      System.out.println("Enter an integer");
      a = in.nextInt();
      System.out.println("You entered integer "+a);
 
      System.out.println("Enter a float");
      b = in.nextFloat();
      System.out.println("You entered float "+b);   
   }
}

Java program to add two numbers

Java program to add two numbers :- Given below is the code of java program that adds two numbers which are entered by the user.

Java programming source code

import java.util.Scanner;
 
class AddNumbers
{
   public static void main(String args[])
   {
      int x, y, z;
      System.out.println("Enter two integers to calculate their sum ");
      Scanner in = new Scanner(System.in);
      x = in.nextInt();
      y = in.nextInt();
      z = x + y;
      System.out.println("Sum of entered integers = "+z);
   }
}
Above code can add only numbers in range of integers(4 bytes), if you wish to add very large numbers then you can use BigInteger class. Code to add very large numbers:
import java.util.Scanner;
import java.math.BigInteger;
 
class AddingLargeNumbers {
  public static void main(String[] args) {
    String number1, number2;
    Scanner in = new Scanner(System.in);
 
    System.out.println("Enter first large number");
    number1 = in.nextLine();
 
    System.out.println("Enter second large number");
    number2 = in.nextLine();
 
    BigInteger first  = new BigInteger(number1);
    BigInteger second = new BigInteger(number2);
    BigInteger sum;
 
    sum = first.add(second);
 
    System.out.println("Result of addition = " + sum);
  }
}
In our code we create two objects of BigInteger class in java.math package. Input should be digit strings otherwise an exception will be raised, also you cannot simply use '+' operator to add objects of BigInteger class, you have to use add method for addition of two objects.
Output of program:
Enter first large number
11111111111111
Enter second large number
99999999999999
Result of addition = 111111111111110

Java program to find odd or even

This java program finds if a number is odd or even. If the number is divisible by 2 then it will be even, otherwise it is odd. We use modulus operator to find remainder in our program.

Java programming source code

import java.util.Scanner;
 
class OddOrEven
{
   public static void main(String args[])
   {
      int x;
      System.out.println("Enter an integer to check if it is odd or even ");
      Scanner in = new Scanner(System.in);
      x = in.nextInt();
 
      if ( x % 2 == 0 )
         System.out.println("You entered an even number.");
      else
         System.out.println("You entered an odd number.");
   }
}
Another method to check odd or even, for explanation see: c program to check odd or even. Code:
import java.util.Scanner;
 
class EvenOdd
{
  public static void main(String args[])
  {
    int c;
    System.out.println("Input an integer");
    Scanner in = new Scanner(System.in);
    c = in.nextInt();
 
    if ( (c/2)*2 == c )
      System.out.println("Even");
    else
      System.out.println("Odd");
  }
}
There are other methods for checking odd/even one such method is using bitwise operator.

Java program to convert Fahrenheit to Celsius

Java program to convert Fahrenheit to Celsius: This code does temperature conversion from Fahrenheit scale to Celsius scale.

Java programming code

import java.util.*;
 
class FahrenheitToCelsius {
  public static void main(String[] args) {
    float temperatue;
    Scanner in = new Scanner(System.in);      
 
    System.out.println("Enter temperatue in Fahrenheit");
    temperatue = in.nextInt();
 
    temperatue = ((temperatue - 32)*5)/9;
 
    System.out.println("Temperatue in Celsius = " + temperatue);
  }
}
For Celsius to Fahrenheit conversion use T = 9*T/5 + 32 where T is temperature on Celsius scale. Create and test Fahrenheit to Celsius program yourself for practice.

Java methods

Java methods tutorial: Java program consists of one or more classes and a class may contain method(s). A class can do very little without methods. In this tutorial we will learn about Java methods. Methods are known as functions in C and C++ programming languages. A method has a name and return type. Main method is a must in a Java program as execution begins from it.

Syntax of methods

"Access specifier" "Keyword(s)" "return type" methodName(List of arguments) { // Body of method }
Access specifier can be public or private which decides whether other classes can call a method. Kewords are used for some special methods such as static or synchronized. Return type indicate return value which method returns. Method name is a valid Java identifier name.
Access specifier, Keyword and arguments are optional.
Examples of methods declaration: public static void main(String[] args); void myMethod(); private int maximum(); public synchronized int search(java.lang.Object);

Java Method example program

class Methods {
 
  // Constructor method
 
  Methods() {
    System.out.println("Constructor method is called when an object of it's class is created");
  }
 
  // Main method where program execution begins
 
  public static void main(String[] args) {
    staticMethod();
    Methods object = new Methods();
    object.nonStaticMethod();
  }
 
  // Static method
 
  static void staticMethod() {
    System.out.println("Static method can be called without creating object");
  }
 
  // Non static method
 
  void nonStaticMethod() {
    System.out.println("Non static method must be called by creating an object");
  }
}

Java methods list

Java has a built in library of many useful classes and there are thousands of methods which can be used in your programs. Just call a method and get your work done :) . You can find list of methods in a class by typing following command on command prompt:
javap package.classname
For example javap java.lang.String // list all methods and constants of String class. javap java.math.BigInteger // list constants and methods of BigInteger class in java.math package

Java String methods

String class contains methods which are useful for performing operations on String(s). Below program illustrate how to use inbuilt methods of String class.

Java string class program

class StringMethods
{
  public static void main(String args[])
  {
    int n;
    String s = "Java programming", t = "", u = "";
 
    System.out.println(s);
 
    // Find length of string
 
    n = s.length();
    System.out.println("Number of characters = " + n);
 
    // Replace characters in string
 
    t = s.replace("Java", "C++");
    System.out.println(s);
    System.out.println(t);
 
    // Concatenating string with another string
 
    u = s.concat(" is fun");
    System.out.println(s);
    System.out.println(u);
  }
}

Java static block program

Java programming language offers a block known as static which is executed before main method executes. Below is the simplest example to understand functioning of static block later we see a practical use of static block.

Java static block program

class StaticBlock {
  public static void main(String[] args) {
    System.out.println("Main method is executed.");
  }
 
  static {
    System.out.println("Static block is executed before main method.");
  }
}
Static block can be used to check conditions before execution of main begin, Suppose we have developed an application which runs only on Windows operating system then we need to check what operating system is installed on user machine. In our java code we check what operating system user is using if user is using operating system other than "Windows" then the program terminates.
class StaticBlock {
  public static void main(String[] args) {
    System.out.println("You are using Windows_NT operating system.");
  }
 
  static {
    String os = System.getenv("OS");
    if (os.equals("Windows_NT") != true) {
      System.exit(1);
    }
  }
}
We are using getenv method of System class which returns value of environment variable name of which is passed an as argument to it. Windows_NT is a family of operating systems which includes Windows XP, Vista, 7, 8 and others.

Java static method

Java static method program: static methods in Java can be called without creating an object of class. Have you noticed why we write static keyword when defining main it's because program execution begins from main and no object has been created yet. Consider the example below to improve your understanding of static methods.

Java static method example program

class Languages {
  public static void main(String[] args) {
    display();
  }
 
  static void display() {
    System.out.println("Java is my favorite programming language.");
  }
}

Java constructor tutorial with code examples

Constructor java tutorial: Java constructors are the methods which are used to initialize objects. Constructor method has the same name as that of class, they are called or invoked when an object of class is created and can't be called explicitly. Attributes of an object may be available when creating objects if no attribute is available then default constructor is called, also some of the attributes may be known initially. It is optional to write constructor method in a class but due to their utility they are used.

Java constructor example

class Programming {
  //constructor method
  Programming() {
    System.out.println("Constructor method called.");
  }
 
  public static void main(String[] args) {
    Programming object = new Programming(); //creating object
  }
}
This code is the simplest example of constructor, we create class Programming and create an object, constructor is called when object is created. As you can see in output "Constructor method called." is printed.

Java constructor overloading

Like other methods in java constructor can be overloaded i.e. we can create as many constructors in our class as desired. Number of constructors depends on the information about attributes of an object we have while creating objects. See constructor overloading example:
class Language {
  String name;
 
  Language() {
    System.out.println("Constructor method called.");
  }
 
  Language(String t) {
    name = t;
  }
 
  public static void main(String[] args) {
    Language cpp  = new Language();
    Language java = new Language("Java");
 
    cpp.setName("C++");
 
    java.getName();
    cpp.getName();
  }
 
  void setName(String t) {
    name = t;
  }
 
  void getName() {
    System.out.println("Language name: " + name);
  }
}

Java program to swap two numbers

This java program swaps two numbers using a temporary variable. To swap numbers without using extra variable see another code below.

Swapping using temporary or third variable

import java.util.Scanner;
 
class SwapNumbers
{
   public static void main(String args[])
   {
      int x, y, temp;
      System.out.println("Enter x and y");
      Scanner in = new Scanner(System.in);
 
      x = in.nextInt();
      y = in.nextInt();
 
      System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
 
      temp = x;
      x = y;
      y = temp;
 
      System.out.println("After Swapping\nx = "+x+"\ny = "+y);
   }
}

Swapping without temporary variable

import java.util.Scanner;
 
class SwapNumbers
{
   public static void main(String args[])
   {
      int x, y;
      System.out.println("Enter x and y");
      Scanner in = new Scanner(System.in);
 
      x = in.nextInt();
      y = in.nextInt();
 
      System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
 
      x = x + y;
      y = x - y;
      x = x - y;
 
      System.out.println("After Swapping\nx = "+x+"\ny = "+y);
   }
}
For other methods to swap: C programming code to swap using bitwise XOR. Swapping is frequently used in sorting techniques such as bubble sort, quick sort etc.

Java program to find largest of three numbers

This java program finds largest of three numbers and then prints it. If the entered numbers are unequal then "numbers are not distinct" is printed.

Java programming source code

import java.util.Scanner;
 
class LargestOfThreeNumbers
{
   public static void main(String args[])
   {
      int x, y, z;
      System.out.println("Enter three integers ");
      Scanner in = new Scanner(System.in);
 
      x = in.nextInt();
      y = in.nextInt();
      z = in.nextInt();
 
      if ( x > y && x > z )
         System.out.println("First number is largest.");
      else if ( y > x && y > z )
         System.out.println("Second number is largest.");
      else if ( z > x && z > y )
         System.out.println("Third number is largest.");
      else   
         System.out.println("Entered numbers are not distinct.");
   }
}

Java program to find factorial

This java program finds factorial of a number. Entered number is checked first if its negative then an error message is printed.

Java programming code

import java.util.Scanner;
 
class Factorial
{
   public static void main(String args[])
   {
      int n, c, fact = 1;
 
      System.out.println("Enter an integer to calculate it's factorial");
      Scanner in = new Scanner(System.in);
 
      n = in.nextInt();
 
      if ( n < 0 )
         System.out.println("Number should be non-negative.");
      else
      {
         for ( c = 1 ; c <= n ; c++ )
            fact = fact*c;
 
         System.out.println("Factorial of "+n+" is = "+fact);
      }
   }
}

Java program for calculating factorial of large numbers

Above program does not give correct result for calculating factorial of say 20. Because 20! is a large number and cant be stored in integer data type which is of 4 bytes. To calculate factorial of say hundred we use BigInteger class of java.math package.
import java.util.Scanner;
import java.math.BigInteger;
 
class BigFactorial
{
  public static void main(String args[])
  {
    int n, c;
    BigInteger inc = new BigInteger("1");
    BigInteger fact = new BigInteger("1");
 
    Scanner input = new Scanner(System.in);
 
    System.out.println("Input an integer");
    n = input.nextInt();
 
    for (c = 1; c <= n; c++) {
      fact = fact.multiply(inc);
      inc = inc.add(BigInteger.ONE);
    }
 
    System.out.println(n + "! = " + fact);
  }
}
Download Big Factorial class file.
We run the above java program to calculate 100 factorial and following output is obtained.
Input an integer
100
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Java program print prime numbers

This java program prints prime numbers, number of prime numbers required is asked from the user. Remember that smallest prime number is 2.

Java programming code

import java.util.*;
 
class PrimeNumbers
{
   public static void main(String args[])
   {
      int n, status = 1, num = 3;
 
      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of prime numbers you want");
      n = in.nextInt();
 
      if (n >= 1)
      {
         System.out.println("First "+n+" prime numbers are :-");
         System.out.println(2);
      }
 
      for ( int count = 2 ; count <=n ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            count++;
         }
         status = 1;
         num++;
      }         
   }
}

Java program to check armstrong number

This java program checks if a number is Armstrong or not. Armstrong number is a number which is equal to sum of digits raise to the power total number of digits in the number. Some Armstrong numbers are: 0, 1, 4, 5, 9, 153, 371, 407, 8208 etc.

Java programming code

import java.util.Scanner;
 
class ArmstrongNumber
{
   public static void main(String args[])
   {
      int n, sum = 0, temp, remainder, digits = 0;
 
      Scanner in = new Scanner(System.in);
      System.out.println("Input a number to check if it is an Armstrong number");      
      n = in.nextInt();
 
      temp = n;
 
      // Count number of digits
 
      while (temp != 0) {
         digits++;
         temp = temp/10;
      }
 
      temp = n;
 
      while (temp != 0) {
         remainder = temp%10;
         sum = sum + power(remainder, digits);
         temp = temp/10;
      }
 
      if (n == sum)
         System.out.println(n + " is an Armstrong number.");
      else
         System.out.println(n + " is not an Armstrong number.");         
   }
 
   static int power(int n, int r) {
      int c, p = 1;
 
      for (c = 1; c <= r; c++) 
         p = p*n;
 
      return p;   
   }
}

Java program to reverse a string

This java program reverses a string entered by the user. We use charAt method to extract characters from the string and append them in reverse order to reverse the entered string.

Java programming code

import java.util.*;
 
class ReverseString
{
   public static void main(String args[])
   {
      String original, reverse = "";
      Scanner in = new Scanner(System.in);
 
      System.out.println("Enter a string to reverse");
      original = in.nextLine();
 
      int length = original.length();
 
      for ( int i = length - 1 ; i >= 0 ; i-- )
         reverse = reverse + original.charAt(i);
 
      System.out.println("Reverse of entered string is: "+reverse);
   }
}

Reverse string using StringBuffer class

class InvertString
{
   public static void main(String args[])
   {
      StringBuffer a = new StringBuffer("Java programming is fun");
      System.out.println(a.reverse());
   }
}
StringBuffer class contains a method reverse which can be used to reverse or invert an object of this class.

Java program to check palindrome

Java palindrome program: Java program to check if a string is a palindrome or not. Remember a string is a palindrome if it remains unchanged when reversed, for example "dad" is a palindrome as reverse of "dad" is "dad" whereas "program" is not a palindrome. Some other palindrome strings are "mom", "madam", "abcba".

Java programming source code

import java.util.*;
 
class Palindrome
{
   public static void main(String args[])
   {
      String original, reverse = "";
      Scanner in = new Scanner(System.in);
 
      System.out.println("Enter a string to check if it is a palindrome");
      original = in.nextLine();
 
      int length = original.length();
 
      for ( int i = length - 1; i >= 0; i-- )
         reverse = reverse + original.charAt(i);
 
      if (original.equals(reverse))
         System.out.println("Entered string is a palindrome.");
      else
         System.out.println("Entered string is not a palindrome.");
 
   }
}       
Another method to check palindrome:
import java.util.*;
 
class Palindrome
{
  public static void main(String args[])
  {
    String inputString;
    Scanner in = new Scanner(System.in);
 
    System.out.println("Input a string");
    inputString = in.nextLine();
 
    int length  = inputString.length();
    int i, begin, end, middle;
 
    begin  = 0;
    end    = length - 1;
    middle = (begin + end)/2;
 
    for (i = begin; i <= middle; i++) {
      if (inputString.charAt(begin) == inputString.charAt(end)) {
        begin++;
        end--;
      }
      else {
        break;
      }
    }
    if (i == middle + 1) {
      System.out.println("Palindrome");
    }
    else {
      System.out.println("Not a palindrome");
    }   
  }
}
Both the above codes consider string as case sensitive, you can modify them so that they ignore the case of string. You can either convert both strings to lower or upper case for this. But do not modify original strings as they may be further required in program.

Java program to compare two strings

This program compare strings i.e test whether two strings are equal or not, compareTo method of String class is used to test equality of two String class objects. compareTo method is case sensitive i.e "java" and "Java" are two different strings if you use compareTo method. If you wish to compare strings but ignoring the case then use compareToIgnoreCase method.

Java programming code

import java.util.Scanner;
 
class CompareStrings
{
   public static void main(String args[])
   {
      String s1, s2;
      Scanner in = new Scanner(System.in);
 
      System.out.println("Enter the first string");
      s1 = in.nextLine();
 
      System.out.println("Enter the second string");
      s2 = in.nextLine();
 
      if ( s1.compareTo(s2) > 0 )
         System.out.println("First string is greater than second.");
      else if ( s1.compareTo(s2) < 0 )
         System.out.println("First string is smaller than second.");
      else   
         System.out.println("Both strings are equal.");
   }
}

Java program for linear search

Java program for linear search: Linear search is very simple, To check if an element is present in the given list we compare search element with every element in the list. If the number is found then success occurs otherwise the list doesn't contain the element we are searching.

Java programming code

 
import java.util.Scanner;
 
class LinearSearch 
{
  public static void main(String args[])
  {
    int c, n, search, array[];
 
    Scanner in = new Scanner(System.in);
    System.out.println("Enter number of elements");
    n = in.nextInt(); 
    array = new int[n];
 
    System.out.println("Enter " + n + " integers");
 
    for (c = 0; c < n; c++)
      array[c] = in.nextInt();
 
    System.out.println("Enter value to find");
    search = in.nextInt();
 
    for (c = 0; c < n; c++)
    {
      if (array[c] == search)     /* Searching element is present */
      {
         System.out.println(search + " is present at location " + (c + 1) + ".");
          break;
      }
   }
   if (c == n)  /* Searching element is absent */
      System.out.println(search + " is not present in array.");
  }
}

Java program for binary search

Java program for binary search: This code implements binary search algorithm. Please note input numbers must be in ascending order.

Java programming code

import java.util.Scanner;
 
class BinarySearch 
{
  public static void main(String args[])
  {
    int c, first, last, middle, n, search, array[];
 
    Scanner in = new Scanner(System.in);
    System.out.println("Enter number of elements");
    n = in.nextInt(); 
    array = new int[n];
 
    System.out.println("Enter " + n + " integers");
 
 
    for (c = 0; c < n; c++)
      array[c] = in.nextInt();
 
    System.out.println("Enter value to find");
    search = in.nextInt();
 
    first  = 0;
    last   = n - 1;
    middle = (first + last)/2;
 
    while( first <= last )
    {
      if ( array[middle] < search )
        first = middle + 1;    
      else if ( array[middle] == search ) 
      {
        System.out.println(search + " found at location " + (middle + 1) + ".");
        break;
      }
      else
         last = middle - 1;
 
      middle = (first + last)/2;
   }
   if ( first > last )
      System.out.println(search + " is not present in the list.\n");
  }
}

Java program to find all substrings of a string

Java program to find substrings of a string :- This program find all substrings of a string and the prints them. For example substrings of "fun" are :- "f", "fu", "fun", "u", "un" and "n". substring method of String class is used to find substring. Java code to print substrings of a string is given below.

Java programing code

import java.util.Scanner;
 
class SubstringsOfAString
{
   public static void main(String args[])
   {
      String string, sub;
      int i, c, length;
 
      Scanner in = new Scanner(System.in);
      System.out.println("Enter a string to print it's all substrings");
      string  = in.nextLine();
 
      length = string.length();   
 
      System.out.println("Substrings of \""+string+"\" are :-");
 
      for( c = 0 ; c < length ; c++ )
      {
         for( i = 1 ; i <= length - c ; i++ )
         {
            sub = string.substring(c, c+i);
            System.out.println(sub);
         }
      }
   }
}

Java program to display date and time, print date and time using java program

Java date and time program :- Java code to print or display current system date and time. This program prints current date and time. We are using GregorianCalendar class in our program. Java code to print date and time is given below :-

Java programming code

import java.util.*;
 
class GetCurrentDateAndTime
{
   public static void main(String args[])
   {
      int day, month, year;
      int second, minute, hour;
      GregorianCalendar date = new GregorianCalendar();
 
      day = date.get(Calendar.DAY_OF_MONTH);
      month = date.get(Calendar.MONTH);
      year = date.get(Calendar.YEAR);
 
      second = date.get(Calendar.SECOND);
      minute = date.get(Calendar.MINUTE);
      hour = date.get(Calendar.HOUR);
 
      System.out.println("Current date is  "+day+"/"+(month+1)+"/"+year);
      System.out.println("Current time is  "+hour+" : "+minute+" : "+second);
   }
}