Friday, September 9, 2011

Do While loop Example

    /*
      Do While loop Example
      This Java Example shows how to use do while loop to iterate in Java program.
    */
    
    public class DoWhileExample {
    
    public static void main(String[] args) {
    
    /*
      * Do while loop executes statment until certain condition become false.
      * Syntax of do while loop is
      *
      * do
      * <loop body>
      * while(<condition>);
      *
      * where <condition> is a boolean expression.
      *
      * Please not that the condition is evaluated after executing the loop body.
      * So loop will be executed at least once even if the condition is false.
      */
    
    int i =0;
    
    do
    {
    System.out.println("i is : " + i);
    i++;
    
    }while(i < 5);
    
    }
    }
    
    /*
    Output would be
    i is : 0
    i is : 1
    i is : 2
    i is : 3
    i is : 4
    */
»»  READMORE...

Do While Loop

Do while loop executes group of Java statements as long as the boolean condition evaluates to true. 

It is possible that the statement block associated with While loop never get executed because While loop tests the boolean condition before executing the block of statements associated with it. 

In Java programming, sometime it's necessary to execute the block of statements at least once before evaluating the boolean condition. Do while loop is similar to the While loop, but it evaluates the boolean condition after executing the block of the statement. 

Do While loop syntax
 Do{ 
 
<Block of statements> 
                }while(<boolean condition>);

Block of statements is any valid Java code. Boolean condition is any valid Java expression that evaluates to boolean value. Braces are options if there is only one statement to be executed.

»»  READMORE...

Threads (Set Thread Name )

    /*
    Set Thread Name Example
    This Java example shows how to set name of thread using setName method
    of Thread class.
    */
    
    public class SetThreadNameExample {
    
    public static void main(String[] args) {
    
    //get currently running thread object
    Thread currentThread = Thread.currentThread();
    System.out.println(currentThread);
    
    /*
    * To set name of thread, use
    * void setName(String threadName) method of
    * Thread class.
    */
    
    currentThread.setName("Set Thread Name Example");
    
    /*
    * To get the name of thread use,
    * String getName() method of Thread class.
    */
    System.out.println("Thread Name : "+ currentThread.getName());
    }
    }
    
    /*
    Output of the example would be
    Thread[main,5,main]
    Thread Name : Set Thread Name Example
    */
»»  READMORE...

Threads (Pause Thread Using Sleep Method)

    /*
      Pause Thread Using Sleep Method Example
      This Java example shows how to pause currently running thread using
      sleep method of Java Thread class.
    */
    
    public class PauseThreadUsingSleep {
    
    public static void main(String[] args) {
    
    /*
    * To pause execution of a thread, use
    * void sleep(int milliseconds) method of Thread class.
    *
    * This is a static method and causes the suspension of the thread
    * for specified period of time.
    *
    * Please note that, this method may throw InterruptedException.
    */
    
    System.out.println("Print number after pausing for 1000 milliseconds");
    try{
    
    for(int i=0; i< 5; i++){
    
    System.out.println(i);
    
    /*
    * This thread will pause for 1000 milliseconds after
    * printing each number.
    */
    Thread.sleep(1000);
    }
    }
    catch(InterruptedException ie){
    System.out.println("Thread interrupted !" + ie);
    }
    
    }
    }
    
    /*
    Output of this example would be
    
    Print number after pausing for 1000 milliseconds
    0
    1
    2
    3
    4
    */
»»  READMORE...

Threads (Get Current Thread)

    /*
    Get Current Thread Example
    This Java example shows how to get reference of current thread using
    currentThread method of Java Thread class.
    */
    
    public class GetCurrentThreadExample {
    
    public static void main(String[] args) {
    
    /*
    * To get the reference of currently running thread, use
    * Thread currentThread() method of Thread class.
    *
    * This is a static method.
    */
    
    Thread currentThread = Thread.currentThread();
    System.out.println(currentThread);
    
    }
    }
    
    /*
    Output of the example would be
    Thread[main,5,main]
    */
»»  READMORE...

Threads (Create New Thread Using Runnable )

    /*
    Create New Thread Using Runnable Example
    This Java example shows how to create a new thread by implementing
    Java Runnable interface.
    */
    
    /*
     * To create a thread using Runnable, a class must implement
     * Java Runnable interface.
     */
    public class CreateThreadRunnableExample implements Runnable{
    
    /*
    * A class must implement run method to implement Runnable
    * interface. Signature of the run method is,
    *
    * public void run()
    *
    * Code written inside run method will constite a new thread.
    * New thread will end when run method returns.
    */
    public void run(){
    
    for(int i=0; i < 5; i++){
    System.out.println("Child Thread : " + i);
    
    try{
    Thread.sleep(50);
    }
    catch(InterruptedException ie){
    System.out.println("Child thread interrupted! " + ie);
    }
    }
    
    System.out.println("Child thread finished!");
    }
    
    public static void main(String[] args) {
    
    /*
    * To create new thread, use
    * Thread(Runnable thread, String threadName)
    * constructor.
    *
    */
    
    Thread t = new Thread(new CreateThreadRunnableExample(), "My Thread");
    
    /*
    * To start a particular thread, use
    * void start() method of Thread class.
    *
    * Please note that, after creation of a thread it will not start
    * running until we call start method.
    */
    
    t.start();
    
    for(int i=0; i < 5; i++){
    
    System.out.println("Main thread : " + i);
    
    try{
    Thread.sleep(100);
    }
    catch(InterruptedException ie){
    System.out.println("Child thread interrupted! " + ie);
    }
    }
    System.out.println("Main thread finished!");
    }
    }
    
    /*
    Typical output of this thread example would be
    
    Main thread : 0
    Child Thread : 0
    Child Thread : 1
    Main thread : 1
    Main thread : 2
    Child Thread : 2
    Child Thread : 3
    Main thread : 3
    Main thread : 4
    Child Thread : 4
    Child thread finished!
    Main thread finished!
    
    */
»»  READMORE...

Sorting Algorithms (Java Bubble Sort Example)

    /*
    Java Bubble Sort Example
    This Java bubble sort example shows how to sort an array of int using bubble
    sort algorithm. Bubble sort is the simplest sorting algorithm.
    */
    
    public class BubbleSort {
    
    public static void main(String[] args) {
    
    //create an int array we want to sort using bubble sort algorithm
    int intArray[] = new int[]{5,90,35,45,150,3};
    
    //print array before sorting using bubble sort algorithm
    System.out.println("Array Before Bubble Sort");
    for(int i=0; i < intArray.length; i++){
    System.out.print(intArray[i] + " ");
    }
    
    //sort an array using bubble sort algorithm
    bubbleSort(intArray);
    
    System.out.println("");
    
    //print array after sorting using bubble sort algorithm
    System.out.println("Array After Bubble Sort");
    for(int i=0; i < intArray.length; i++){
    System.out.print(intArray[i] + " ");
    }
    
    }
    
    private static void bubbleSort(int[] intArray) {
    
    /*
    * In bubble sort, we basically traverse the array from first
    * to array_length - 1 position and compare the element with the next one.
    * Element is swapped with the next element if the next element is greater.
    *
    * Bubble sort steps are as follows.
    *
    * 1. Compare array[0] & array[1]
    * 2. If array[0] > array [1] swap it.
    * 3. Compare array[1] & array[2]
    * 4. If array[1] > array[2] swap it.
    * ...
    * 5. Compare array[n-1] & array[n]
    * 6. if [n-1] > array[n] then swap it.
    *
    * After this step we will have largest element at the last index.
    *
    * Repeat the same steps for array[1] to array[n-1]
    *
    */
    
    int n = intArray.length;
    int temp = 0;
    
    for(int i=0; i < n; i++){
    for(int j=1; j < (n-i); j++){
    
    if(intArray[j-1] > intArray[j]){
    //swap the elements!
    temp = intArray[j-1];
    intArray[j-1] = intArray[j];
    intArray[j] = temp;
    }
    
    }
    }
    
    }
    }
    
    /*
    Output of the Bubble Sort Example would be
    
    Array Before Bubble Sort

    5 90 35 45 150 3
    Array After Bubble Sort
    3 5 35 45 90 150
    
    */
»»  READMORE...

Sorting Algorithms (Java Bubble Sort Descending Order )

    /*
    Java Bubble Sort Descending Order Example
    This Java bubble sort example shows how to sort an array of int in descending
    order using bubble sort algorithm.
    */
    
    public class BubbleSortDescendingOrder {
    
    public static void main(String[] args) {
    
    //create an int array we want to sort using bubble sort algorithm
    int intArray[] = new int[]{5,90,35,45,150,3};
    
    //print array before sorting using bubble sort algorithm
    System.out.println("Array Before Bubble Sort");
    for(int i=0; i < intArray.length; i++){
    System.out.print(intArray[i] + " ");
    }
    
    //sort an array in descending order using bubble sort algorithm
    bubbleSort(intArray);
    
    System.out.println("");
    
    //print array after sorting using bubble sort algorithm
    System.out.println("Array After Bubble Sort");
    for(int i=0; i < intArray.length; i++){
    System.out.print(intArray[i] + " ");
    }
    
    }
    
    private static void bubbleSort(int[] intArray) {
    
    /*
    * In bubble sort, we basically traverse the array from first
    * to array_length - 1 position and compare the element with the next one.
    * Element is swapped with the next element if the next element is smaller.
    *
    * Bubble sort steps are as follows.
    *
    * 1. Compare array[0] & array[1]
    * 2. If array[0] < array [1] swap it.
    * 3. Compare array[1] & array[2]
    * 4. If array[1] < array[2] swap it.
    * ...
    * 5. Compare array[n-1] & array[n]
    * 6. if [n-1] < array[n] then swap it.
    *
    * After this step we will have smallest element at the last index.
    *
    * Repeat the same steps for array[1] to array[n-1]
    *
    */
    
    int n = intArray.length;
    int temp = 0;
    
    for(int i=0; i < n; i++){
    for(int j=1; j < (n-i); j++){
    
    if(intArray[j-1] < intArray[j]){
    //swap the elements!
    temp = intArray[j-1];
    intArray[j-1] = intArray[j];
    intArray[j] = temp;
    }
    
    }
    }
    
    }
    }
    
    /*
    Output of the Bubble Sort Descending Order Example would be
    
    Array Before Bubble Sort
    5 90 35 45 150 3
    Array After Bubble Sort
    150 90 45 35 5 3
    
    */
»»  READMORE...

For Loop (List Odd Numbers Java )

     /*
    List Odd Numbers Java Example
    This List Odd Numbers Java Example shows how to find and list odd
    numbers between 1 and any given number.
    */
     
    public class ListOddNumbers {
     
    public static void main(String[] args) {
     
    //define the limit
    int limit = 50;
     
    System.out.println("Printing Odd numbers between 1 and " + limit);
     
    for(int i=1; i <= limit; i++){
     
    //if the number is not divisible by 2 then it is odd
    if( i % 2 != 0){
    System.out.print(i + " ");
    }
    }
    }
    }
   
    /*
    Output of List Odd Numbers Java Example would be
    Printing Odd numbers between 1 and 50

    1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
    */
»»  READMORE...

For Loop (Simple For loop )

    /*
      Simple For loop Example
      This Java Example shows how to use for loop to iterate in Java program.
    */
    
    public class SimpleForLoopExample {
    
    public static void main(String[] args) {
    
    /* Syntax of for loop is
      *
      * for(<initialization> ; <condition> ; <expression> )
      * <loop body>
      *
      * where initialization usually declares a loop variable, condition is a
      * boolean expression such that if the condition is true, loop body will be
      * executed and after each iteration of loop body, expression is executed which
      * usually increase or decrease loop variable.
      *
      * Initialization is executed only once.
      */
    
    for(int index = 0; index < 5 ; index++)
    System.out.println("Index is : " + index);
    
    /*
      * Loop body may contains more than one statement. In that case they should
      * be in the block.
      */
    
    for(int index=0; index < 5 ; index++)
    {
    System.out.println("Index is : " + index);
    index++;
    }
    
    /*
      * Please note that in above loop, index is a local variable whose scope
      * is limited to the loop. It can not be referenced from outside the loop.
      */
    }
    }
    
    /*
    Output would be
    Index is : 0
    Index is : 1
    Index is : 2
    Index is : 3
    Index is : 4
    Index is : 0
    Index is : 2
    Index is : 4
    */
»»  READMORE...

For Loop (Read Number from Console and Check if it is a Palindrome Number)

    /*
      Read Number from Console and Check if it is a Palindrome Number
      This Java example shows how to input the number from console and
      check if the number is a palindrome number or not.
     */
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class InputPalindromeNumberExample {
    
    public static void main(String[] args) {
    
    System.out.println("Enter the number to check..");
    int number = 0;
    
    try
    {
    //take input from console
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    //parse the line into int
    number = Integer.parseInt(br.readLine());
    
    }
    catch(NumberFormatException ne)
    {
    System.out.println("Invalid input: " + ne);
    System.exit(0);
    }
    catch(IOException ioe)
    {
    System.out.println("I/O Error: " + ioe);
    System.exit(0);
    }
    
    System.out.println("Number is " + number);
    int n = number;
    int reversedNumber = 0;
    int temp=0;
    
    //reverse the number
    while(n > 0){
    temp = n % 10;
    n = n / 10;
    reversedNumber = reversedNumber * 10 + temp;
    }
    
    /*
    * if the number and it's reversed number are same, the number is a
    * palindrome number
    */
    if(number == reversedNumber)
    System.out.println(number + " is a palindrome number");
    else
    System.out.println(number + " is not a palindrome number");
    }
    
    }
    
    /*
    Output of the program would be
    Enter the number to check..

    121
    Number is 121
    121 is a palindrome number
    */
»»  READMORE...

For Loop (Prime Numbers Java)

    /*
      Prime Numbers Java Example
      This Prime Numbers Java example shows how to generate prime numbers
      between 1 and given number using for loop.
     */
    
    public class GeneratePrimeNumbersExample {
    
    public static void main(String[] args) {
    
    //define limit
    int limit = 100;
    
    System.out.println("Prime numbers between 1 and " + limit);
    
    //loop through the numbers one by one
    for(int i=1; i < 100; i++){
    
    boolean isPrime = true;
    
    //check to see if the number is prime
    for(int j=2; j < i ; j++){
    
    if(i % j == 0){
    isPrime = false;
    break;
    }
    }
    // print the number
    if(isPrime)
    System.out.print(i + " ");
    }
    }
    }
    
    /*
    Output of Prime Numbers example would be
    Prime numbers between 1 and 100

    1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
    */
»»  READMORE...

For Loop (List Even Numbers Java)

    /*
    List Even Numbers Java Example
    This List Even Numbers Java Example shows how to find and list even
    numbers between 1 and any given number.
    */
    
    public class ListEvenNumbers {
    
    public static void main(String[] args) {
    
    //define limit
    int limit = 50;
    
    System.out.println("Printing Even numbers between 1 and " + limit);
    
    for(int i=1; i <= limit; i++){
    
    // if the number is divisible by 2 then it is even
    if( i % 2 == 0){
    System.out.print(i + " ");
    }
    }
    }
    }
    
    /*
    Output of List Even Numbers Java Example would be
    Printing Even numbers between 1 and 50
    2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
    */
»»  READMORE...

For Loop (Java Palindrome Number )

    /*
    Java Palindrome Number Example
    This Java Palindrome Number Example shows how to find if the given
    number is palindrome number or not.
    */
    
    
    public class JavaPalindromeNumberExample {
    
    public static void main(String[] args) {
    
    //array of numbers to be checked
    int numbers[] = new int[]{121,13,34,11,22,54};
    
    //iterate through the numbers
    for(int i=0; i < numbers.length; i++){
    
    int number = numbers[i];
    int reversedNumber = 0;
    int temp=0;
    
    /*
    * If the number is equal to it's reversed number, then
    * the given number is a palindrome number.
    *
    * For example, 121 is a palindrome number while 12 is not.
    */
    
    //reverse the number
    while(number > 0){
    temp = number % 10;
    number = number / 10;
    reversedNumber = reversedNumber * 10 + temp;
    }
    
    if(numbers[i] == reversedNumber)
    System.out.println(numbers[i] + " is a palindrome number");
    else
    System.out.println(numbers[i] + " is not a palindrome number");
    }
    
    }
    }
    
    /*
    Output of Java Palindrome Number Example would be
    121 is a palindrome number
    13 is not a palindrome number
    34 is not a palindrome number
    11 is a palindrome number
    22 is a palindrome number
    54 is not a palindrome number
    */
»»  READMORE...

For Loop (Infinite For loop Example)

    /*
      Infinite For loop Example
      This Java Example shows how to create a for loop that runs infinite times
      in Java program. It happens when the loop condition is always evaluated as true.
    */
    
    public class InfiniteForLoop {
    
    public static void main(String[] args) {
    
    /*
      * Its perfectely legal to skip any of the 3 parts of the for loop.
      * Below given for loop will run infinite times.
      */
    for(;;)
    System.out.println("Hello");
    
    /*
      * To terminate this program press ctrl + c in the console.
      */
    }
    }
    
    /*
    Output would be
    Hello
    Hello
    Hello
    Hello
    ..
    ..
    */
»»  READMORE...

For Loop (Fibonacci Series Java Example)

    /*
    Fibonacci Series Java Example
    This Fibonacci Series Java Example shows how to create and print
    Fibonacci Series using Java.
    */
    
    public class JavaFibonacciSeriesExample {
    
    public static void main(String[] args) {
    
    //number of elements to generate in a series
    int limit = 20;
    
    long[] series = new long[limit];
    
    //create first 2 series elements
    series[0] = 0;
    series[1] = 1;
    
    //create the Fibonacci series and store it in an array
    for(int i=2; i < limit; i++){
    series[i] = series[i-1] + series[i-2];
    }
    
    //print the Fibonacci series numbers
    
    System.out.println("Fibonacci Series upto " + limit);
    for(int i=0; i< limit; i++){
    System.out.print(series[i] + " ");
    }
    }
    }
    
    /*
    Output of the Fibonacci Series Java Example would be
    Fibonacci Series up to 20
    0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
    */
»»  READMORE...

For Loop

For loop executes group of Java statements as long as the boolean condition evaluates to true.

For loop combines three elements which we generally use: initialization statement, boolean expression and increment or decrement statement.

For loop syntax

    for( <initialization> ; <condition> ; <statement> ){
    
    <Block of statements>;
    
    }

The initialization statement is executed before the loop starts. It is generally used to initialize the loop variable.

Condition statement is evaluated before each time the block of statements are executed. Block of statements are executed only if the boolean condition evaluates to true.

Statement is executed after the loop body is done. Generally it is being used to increment or decrement the loop variable.

Following example shows use of simple for loop.

     for(int i=0 ; i < 5 ; i++)
    {
    System.out.println(“i is : “ + i);
    }

It is possible to initialize multiple variable in the initialization block of the for loop by separating it by comma as given in the below example.

for(int i=0, j =5 ; i < 5 ; i++)

It is also possible to have more than one increment or decrement section as well as given below.

for(int i=0; i < 5 ; i++, j--)

However it is not possible to include declaration and initialization in the initialization block of the for loop. 

Also, having multiple conditions separated by comma also generates the compiler error. However, we can include multiple condition with && and || logical operators.

For Loop Examples

Java Pyramid  Example

     /*
    Java Pyramid 1 Example
    This Java Pyramid example shows how to generate pyramid or triangle like
    given below using for loop.
     
    *
    **
    ***
    ****
    *****
    */
   
    public class JavaPyramid1 {
     
    public static void main(String[] args) {
     
    for(int i=1; i<= 5 ;i++){
     
    for(int j=0; j < i; j++){
    System.out.print("*");
    }
     
    //generate a new line
    System.out.println("");
    }
    }
    }
   
    /*
    Output of the above program would be
    *
    **
    ***
    ****
    *****
    */

 Source : www.java-examples.com



»»  READMORE...

Data types (Java short )

    /*
    Java short Example
    This Java Example shows how to declare and use Java primitive short variable
    inside a java class.
    */
    
    public class JavaShortExample {
    
    public static void main(String[] args) {
    
    /*
    * short is 16 bit signed type ranges from –32,768 to 32,767.
    *
    * Declare short varibale as below
    *
    * short <variable name> = <default value>;
    *
    * here assigning default value is optional.
    */
    
    short s1 = 50;
    short s2 = 42;
    
    System.out.println("Value of short variable b1 is :" + s1);
    System.out.println("Value of short variable b1 is :" + s2);
    }
    }
    
    /*
    Output would be
    Value of short variable b1 is :50
    Value of short variable b1 is :42
    */
»»  READMORE...

Data types (Java long)

    /*
    Java long Example
    This Java Example shows how to declare and use Java primitive long variable
    inside a java class.
    */
    
    import java.util.*;
    
    public class JavaLongExample {
    
    public static void main(String[] args) {
    
    /*
    * long is 64 bit signed type and used when int is not large
    * enough to hold the value.
    *
    * Declare long varibale as below
    *
    * long <variable name> = <default value>;
    *
    * here assigning default value is optional.
    */
    
    long timeInMilliseconds = new Date().getTime();
    System.out.println("Time in milliseconds is : " + timeInMilliseconds);
    }
    }
    
    /*
    Output would be
    Time in milliseconds is : 1226836372234
    */
»»  READMORE...

Data types (Java int )

    /*
    Java int Example
    This Java Example shows how to declare and use Java primitive int variable
    inside a java class.
    */
    
    public class JavaIntExamples {
    
    public static void main(String[] args) {
    
    /*
    * int is 32 bit signed type ranges from –2,147,483,648
    * to 2,147,483,647. int is also most commonly used integer
    * type in Java.
    * Declare int varibale as below
    *
    * int <variable name> = <default value>;
    *
    * here assigning default value is optional.
    */
    
    int i = 0;
    int j = 100;
    
    System.out.println("Value of int variable i is :" + i);
    System.out.println("Value of int variable j is :" + j);
    }
    }
    
    /*
    Output would be
    Value of int variable i is :0
    Value of int variable j is :100
    */
»»  READMORE...

Data types (Java float)

    /*
    Java float Example
    This Java Example shows how to declare and use Java primitive float variable
    inside a java class.
    */
    
    import java.util.*;
    
    public class JavaFloatExample {
    
    public static void main(String[] args) {
    
    /*
    * float is 32 bit single precision type and used when fractional precision
    * calculation is required.
    *
    * Declare float varibale as below
    *
    * float <variable name> = <default value>;
    *
    * here assigning default value is optional.
    */
    
    float f = 10.4f;
    System.out.println("Value of float variable f is :" + f);
    }
    }
    
    /*
    Output would be

    Value of float variable f is :10.4
    */
»»  READMORE...

Data types (Java double)

    /*
    Java double Example
    This Java Example shows how to declare and use Java primitive double variable
    inside a java class.
    */
    
    public class JavaDoubleExample {
    
    public static void main(String[] args) {
    
    /*
    * double is 64 bit double precision type and used when fractional precision
    * calculation is required.
    *
    * Declare double varibale as below
    *
    * double <variable name> = <default value>;
    *
    * here assigning default value is optional.
    */
    
    double d = 1232.44;
    System.out.println("Value of double variable d is :" + d);
    }
    }
    
    /*
    Output would be
    Value of double variable f is :1232.44
    */
»»  READMORE...

Data types (Java char )

    /*
    Java char Example
    This Java Example shows how to declare and use Java primitive char variable
    inside a java class.
    */
    
    public class JavaCharExample {
    
    public static void main(String[] args) {
    
    /*
    * char is 16 bit type and used to represent Unicode characters.
    * Range of char is 0 to 65,536.
    *
    * Declare char varibale as below
    *
    * char <variable name> = <default value>;
    *
    * here assigning default value is optional.
    */
    
    char ch1 = 'a';
    char ch2 = 65; /* ASCII code of 'A'*/
    
    System.out.println("Value of char variable ch1 is :" + ch1);
    System.out.println("Value of char variable ch2 is :" + ch2);
    }
    }
    
    /*
    Output would be
    Value of char variable ch1 is :a
    Value of char variable ch2 is :A
    */
»»  READMORE...

Data types (Java byte)

    /*
    Java byte Example
    This Java Example shows how to declare and use Java primitive byte variable
    inside a java class.
    */
    
    public class JavaByteExample {
    
    public static void main(String[] args) {
    
    /*
    * byte is smallest Java integer type.
    * byte is 8 bit signed type ranges from –128 to 127.
    * byte is mostly used when dealing with raw data like reading a
    * binary file.
    *
    * Declare byte varibale as below
    *
    * byte <variable name> = <default value>;
    *
    * here assigning default value is optional.
    */
    
    byte b1 = 100;
    byte b2 = 20;
    
    System.out.println("Value of byte variable b1 is :" + b1);
    System.out.println("Value of byte variable b1 is :" + b2);
    }
    }
    
    /*
    Output would be
    Value of byte variable b1 is :100
    Value of byte variable b1 is :20
    */
»»  READMORE...

Data types (Java boolean)

    /*
    Java boolean Example
    This Java Example shows how to declare and use Java primitive boolean variable
    inside a java class.
    */
    
    public class JavaBooleanExample {
    
    public static void main(String[] args) {
    
    /*
    * boolean is simple Java type which can have only of two values; true or false.
    * All rational expressions retrun this type of value.
    *
    * Declare boolean varibale as below
    *
    * boolean <variable name> = <default value>;
    *
    * here assigning default value is optional.
    */
    
    boolean b1 = true;
    boolean b2 = false;
    boolean b3 = (10 > 2)? true:false;
    
    System.out.println("Value of boolean variable b1 is :" + b1);
    System.out.println("Value of boolean variable b2 is :" + b2);
    System.out.println("Value of boolean variable b3 is :" + b3);
    }
    }
    
    /*
    Output would be
    Value of boolean variable b1 is :true
    Value of boolean variable b2 is :false
    Value of boolean variable b3 is :true
    */
»»  READMORE...

Thursday, September 8, 2011

How do I get a notification when session attribute was changed?

Implementing the HttpSessionAttributeListener will make the servlet container inform you about session attribute changes. The notification is in a form of HttpSessionBindingEvent object. The getName() on this object tell the name of the attribute while the getValue() method tell about the value that was added, replaced or removed.

package org.kodejava.example.servlet;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class SessionAttributeListener implements HttpSessionAttributeListener {

    public void attributeAdded(HttpSessionBindingEvent event) {
        //
        // This method is called when an attribute is added to a session.
        // The line below display session attribute name and its value.
        //
        System.out.println("Session attribute added: ["
                + event.getName() + "] = [" + event.getValue() + "]");
    }

    public void attributeRemoved(HttpSessionBindingEvent event) {
        //
        //  This method is called when an attribute is removed from a session.
        //
        System.out.println("Session attribute removed: ["
                + event.getName() + "] = [" + event.getValue() + "]");
    }

    public void attributeReplaced(HttpSessionBindingEvent event) {
        //
        // This method is invoked when an attibute is replaced in a session.
        //
        System.out.println("Session attribute replaced: ["
                + event.getName() + "] = [" + event.getValue() + "]");
    }
}
 
After your listener is ready don't forget to configure it in the web application deployment descriptor, the web.xml file.

Source : kodejava.org
»»  READMORE...