Retouch Print facility in Java



In this article you can get a great idea about how to use the various output statements in Java. While you print a statement, there resides several transaction between the Program and the JVM(Java Virtual Machine).In Java , all are byte based streams for reading input and showing result as output.In order to understand Java I/0 , you have to know how java deals with various integers, characters,bytes and other primitive data types. Most important thing is that to analyze  transformation of data types from one to another 

// Comment
package allinalljava;

/**
 *
 * @author Sabari Raja
 */
public class SamplePrintf {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.print("Welcome to Java Again");
        System.out.write(10);
        System.out.printf("%d%c",100,'%');
        System.out.write(9);
        System.out.print("pure coffee");
        System.out.println("\ntaste me again");
    }
}


In the above program, I have shown various possible ways of printing output streams. Here print(“ “) is normal operation like printing a sample text. While write(int) is some thing different. Its converts numeric value to byte. Usually write(9) is similar to using ‘\t’. Printf(“%d”,value) this method of printing is similar to printf in C. From release of Jdk 5.0, we have this facility of using printf. Println is for printing the statement with end of line. Main use to start newline.


Output
Welcome to Java Again
100%     pure coffee
taste me again
raja P Web Developer

Amazing Ancii Code using Java



// Comment
package com.sabari;javascript:void(0);

publicclass AnciiCode {
	publicstaticvoid main(String[] args) {
		System.out.println("Ancii Code Using Java");
		for (int i = 32; i < 127; i++) {
		System.out.write(i);
		/*Line Break after each Character display
		 * Each tab space for until 8 character
		 * 
		 */
		if (i % 8 == 7) System.out.write('\n');
		else System.out.write('\t');
		}
		System.out.write('\n');
		}
}



The write() method sends a specific bit pattern to a specific output stream. The write() method usually writes a single unsigned byte of data whose value should be between 255. Suppose when we use number larger than 255 or smaller than zero, it's reduced modulo 256 before being written.

// Comment

package com.sabari;

publicclass AnciiCode {
	publicstaticvoid main(String[] args) {
		System.out.println("Ancii Code Using Java");
		for (int i = 32; i < 127; i++) {
		System.out.write(i);
		/*Line Break after each Character display
		 * Each tab space for until 8 character
		 * 
		 */
		if (i % 8 == 7) System.out.write(10);
		else System.out.write(9);
		}
		System.out.write('\n');
		}
}

Both program produce the same output because while compiling your program the compiler converts the literals ‘\t’ and ‘\n’ in to numeric value 9 and 10.when it come to console for printing .The Console converts 9 and 10 to ‘\t’ and ‘\n’ respectively.
Output
Ancii Code Using Java
      !     "     #     $     %     &     '
(     )     *     +     ,     -     .     /
0     1     2     3     4     5     6     7
8     9     :     ;     <     =     >     ?
@     A     B     C     D     E     F     G
H     I     J     K     L     M     N     O
P     Q     R     S     T     U     V     W
X     Y     Z     [     \     ]     ^     _
`     a     b     c     d     e     f     g
h     i     j     k     l     m     n     o
p     q     r     s     t     u     v     w
x     y     z     {     |     }     ~     
raja P Web Developer

Example for using Image View in Android 4


In the following example program we can understand how to apply image to image view control of android .Here by i demonstrate a sample program in order to provoke a bit concept of android.In android all the widget can obtain image by means of invoking its source image.By means of it our application user view will be more perfect and attractive.


// Comment
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="start">

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="@drawable/bg_layout"/>

</RelativeLayout>



In the above program i have used relative layout.Usually due to relative layout we can easily make component positioned based on our decision.we can take full control over it.Background property used here in ImageView component helps us to laod the media data in the widget.

Sample Output

 

raja P Web Developer

Apply bloom effect using JavaFx 2.0


In following program you get an idea how to apply bloom effect for our created GUI object in JavaFx2.1 .

// Comment 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javafxblendingmode;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.Bloom;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 *
 * @author allinalljava.blogspot.com
 */
public class JavaFXBloomEffect extends Application {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Bloom Effect");
        Bloom bloom =new Bloom();
        bloom.setThreshold(0.5);      

Text t = new Text();
t.setText("Bloom!");
t.setFill(Color.YELLOW);
t.setFont(Font.font("null", FontWeight.BOLD, 36));
t.setX(25);
t.setY(65);
Circle c = new Circle();
c.setFill(Color.BLACK);
c.setCenterX(590);
c.setCenterY(50);
c.setRadius(70);

        StackPane root = new StackPane();

        root.setEffect(bloom);
         root.getChildren().add(c);
       root.getChildren().add(t);

        primaryStage.setScene(new Scene(root, 300, 250,Color.CADETBLUE));
        primaryStage.show();
    }
}



Output

raja P Web Developer

To Integrate JavaFx2 with JavaScript



In order to make a call back in a JavaFX2 application from JavaScript, the first step we need to do is to get  reference to aJavaScript object representing the JavaFX2 application. In Following example show how to execute JavaScript code in JavaFX2 application
// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagejavafxusingjavascript;

importjavafx.application.Application;
importjavafx.application.HostServices;
importjavafx.event.ActionEvent;
importjavafx.event.EventHandler;
importjavafx.scene.Scene;
importjavafx.scene.control.Button;
importjavafx.scene.layout.StackPane;
importjavafx.stage.Stage;
importnetscape.javascript.JSObject;

/**
 *
 * @author allinalljava.blogspot.com
 */
public class JavaFxusingJavascript extends Application {
finalHostServices services = getHostServices();
    /**
     * @paramargs the command line arguments
     */
public static void main(String[] args) {
launch(args);
    }

    @Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
        Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler() {

            @Override
public void handle(ActionEvent event) {
              //  System.out.println("Hello World!");
JSObjectjs = services.getWebContext();
js.eval("window.alert('Hello from JavaFX')");
            }
        });

StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
    }
}


OUTPUT VIEW

From above program its shows how to interact webpage with JavaFx 2.0 Program.Here we have use JSObject a class which is responsible for invoking the all JavaScript related function call from java program itself.You can use this class even in your normal applet,servlet program.For using this particular class you should need jdk6.0 and other latest jdk

raja P Web Developer

Display various methods and Field in a class using Reflection in Java


Reflection (java.lang.reflect) is mainly used to get entire information about the class and their related information declared in a class can be obtained .Here i have explained a sample program to demonstrate how the reflection will work.
// Comment


import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.util.Date;

/**
 *
 * @author allinalljava.blogspot.com
 */
public class samplereflect {
    
    /**
     * List various methods in a class using Reflection in Java .
     */
    public void listMethodsUsingReflection() {

        //Obtain the Class instance
        Class employeeClass = Employee.class;
        
        //Get the Declared methods in employeeClass
        Method[] methodsList = employeeClass.getDeclaredMethods();
        System.out.println("This are the methods that have been declared in Employee Class");
        //Loop through the methodsLists and print out their names
        for (Method methodInstance : methodsList) {
            System.out.println(methodInstance.getName());
        }
        //Get the Declared FieldLists in employeeClass
        Field[] fieldList = employeeClass.getDeclaredFields();
        //Loop through the fieldLists and print out their names
        System.out.println("This are the Fields that have been declared in Employee Class");
        for (Field fieldInstance : fieldList) {
            System.out.println(fieldInstance.getName());
        }
        
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new samplereflect().listMethodsUsingReflection();
    }
    
    
    class Employee {
        
        private String empName;
        private String empAddress;
        private String empAge;
        private Date empDob;
        
  public void setEmpName(String empName) {
   this.empName = empName;
  }
  public String getEmpName() {
   return empName;
  }
  public void setEmpAddress(String empAddress) {
   this.empAddress = empAddress;
  }
  public String getEmpAddress() {
   return empAddress;
  }
  public void setEmpAge(String empAge) {
   this.empAge = empAge;
  }
  public String getEmpAge() {
   return empAge;
  }
  public void setEmpDob(Date empDob) {
   this.empDob = empDob;
  }
  public Date getEmpDob() {
   return empDob;
  }

    
    }
}
Output
This are the methods that have been declared in Employee Class
setEmpName
getEmpName
setEmpAddress
getEmpAddress
setEmpAge
getEmpAge
setEmpDob
getEmpDob
This are the Fields that have been declared in Employee Class
empName
empAddress
empAge
empDob
raja P Web Developer

To set Background Image in Android application



In android you can set background image by means of properties or by xml file.At first you have to include the image file in drawable-mdpi folder. The format of image should be .png format. Then in main activity xml file just add following code.

// Comment
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/a_wallpare">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity"/>



</RelativeLayout>



Output Mobile View

raja P Web Developer

Easy Debugging in Android 4 using LogCat



LogCat  tool is responsible for emit log messages using android.util.Log .Even though there is System.out.println and the corresponding output is displayed in LogCat window we have to use android.util.log class. This class mainly focus on Famililiarinformational ,warnigs and error methods.

Log.v("string TAG", "This is my sample log");
It’s best to use the appropriate call level for the message  logs that we needed, and note that logging uses memory and takes CPU resources. Benefit of LogCat is that we can view log messages while
runningour application in the emulator, 


raja P Web Developer

Indefinite progress bar Using Swing


This example creates a window which contains an indefinite progress bar. While launch the program, you see a tiny rectangle bouncing back and forth within the progress bar's bounds, The result is much better on Mac OS X because it uses the native Look and Feel automatically 
// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagecom.allinalljava;
importjavax.swing.*; 
/**
 *
 * @author allinalljava
 */
public class ProgressJava {


public static void main(String[] args) {
JFrame f = new JFrame("Progress");
JProgressBar p = new JProgressBar( );
p.setIndeterminate(true);
f.getContentPane( ).add(p);
f.pack( );
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
  } 
}

Output

raja P Web Developer

Using ArrayDeque For constructing Stack in java .


following program show how to create simple stack in java.While executing this program you can feel real word of Stack FILO concept in real time
// Comment

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagecom.allinalljava;
importjava.util.*;
/**
 *
 * @author allinalljava
 */
public class JavaArrayDeque {


public static void main(String args[]) {
// Create a tree set.
ArrayDequeadq = new ArrayDeque();
// Use an ArrayDeque like a stack.
adq.push("A");
adq.push("B");
adq.push("D");
adq.push("E");
adq.push("F");
System.out.print("Popping the stack: ");
while(adq.peek() != null)
System.out.print(adq.pop() + " ");
System.out.println();
}
}

OutPut
Popping the stack: F E D B A
raja P Web Developer

Converting HashSet in to TreeSet using java



In following program you can easily analyze the difference between TreeSet  andHashSet.  
// Comment

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagecom.allinalljava;
importjava.util.*;
/**
 *
 * @author allinalljava
 */
public class JavaHashSettoTreeSet {
    // Demonstrate HashSet.


public static void main(String args[]) {
// Create a hash set.
HashSethashSet = new HashSet();
// Add elements to the hash set.
hashSet.add("B");
hashSet.add("A");
hashSet.add("D");
hashSet.add("E");
hashSet.add("C");
hashSet.add("F");
System.out.println(" HashSet Elements "+hashSet);
TreeSetts =new TreeSet(hashSet);
System.out.println("TreeSet Elements "+ts);

}
}


OUTPUT 
HashSet Elements [D, E, F, A, B, C] TreeSet Elements [A, B, C, D, E, F]
raja P Web Developer

Using Tree Set in Java



TreeSet has the following constructors:
TreeSet( ) --constructs an empty tree set  sorted in ascending order
TreeSet(Collection<? extends E> c)--builds a tree set that contains the elements of c
TreeSet(Comparator<? super E> comp)--constructs an empty tree set that will be sorted according to the comparator specified by comp.
TreeSet(SortedSet<E>ss)--a tree set that contains the elements of ss

In TreeSet elements are arranged automatically in sorted order.
// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagecom.allinalljava;
importjava.util.*;
/**
 *
 * @author allinalljava
 */
public class JavaTreeSet {
    // Demonstrate TreeSet.


public static void main(String args[]) {
// Create a tree set.
TreeSettreeSet = new TreeSet();
// Add elements to the tree set.
treeSet.add("C");
treeSet.add("A");
treeSet.add("B");
treeSet.add("E");
treeSet.add("F");
treeSet.add("D");
System.out.println("TreeSetContail Elements"+treeSet);
}
}


Output 
 TreeSetContailElements[A, B, C, D, E, F]
raja P Web Developer

Program to use HashSet in java



The following constructors are defined:

HashSet( ) ----constructs a default hash set
HashSet(Collection<? extends E>c)---initializes the hash set by using the elements of c.
HashSet(intcapacity) --initializes the capacity of the hash set to capacity
HashSet(intcapacity, float fillRatio)---initializes both the capacity and the fill ratio  The fill ratio must be between 0.0 and 1.0thenumber of elements is greater than the capacity of the hash set multiplied by its fill ratio,the hash set is expanded

the elements of hash set are not stored in sorted order
// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagecom.allinalljava;
importjava.util.*;
/**
 *
 * @author allinalljava
 */
public class JavaHashSet {
    // Demonstrate HashSet.


public static void main(String args[]) {
// Create a hash set.
HashSethashSet = new HashSet();
// Add elements to the hash set.
hashSet.add("B");
hashSet.add("A");
hashSet.add("D");
hashSet.add("E");
hashSet.add("C");
hashSet.add("F");
System.out.println("OutPut of HashSet Elements "+hashSet);
}
}


Output 
OutPut of HashSet Elements [D, E, F, A, B, C]
raja P Web Developer

Way To use Linked List in Java



The LinkedListclass extends AbstractSequentialListand implements the List, Deque, and
Queue interfaces.At  begin of a list you can use addFirst( ) orofferFirst( )  to add first element .
To add elements to the end of the list, use addLast( ) or offerLast( ).In order to obtain the first element, we can use  getFirst( ) or peekFirst( ).For obtaining last element, use   getLast( ) or peekLast( ). In the way to remove the first element, use removeFirst( ) or pollFirst( ). To remove the last element, use removeLast( ) or pollLast( ).
// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagecom.allinalljava;
importjava.util.*;
/**
 *
 * @author allinalljava
 */
public class JavaLinkedList {

public static void main(String args[]) {
// Create a linked list.
LinkedListlinkedList= new LinkedList();
// Add elements to the linked list.
linkedList.add("A");
linkedList.add("L");
linkedList.add("L");
linkedList.add("I");
linkedList.add("N");
linkedList.addLast("A");
linkedList.addFirst("L");
linkedList.add(1, "L");
System.out.println("Original contents of ll: " + linkedList);
// Remove elements from the linked list.
linkedList.remove("N");
linkedList.remove(3);
System.out.println("Contents of ll after deletion: "
+ linkedList);
// Remove first and last elements.
linkedList.removeFirst();
linkedList.removeLast();
System.out.println("ll after deleting first and last: "
+ linkedList);
// Get and set a value.

String val = linkedList.get(2);
linkedList.set(2, val + " Changed");
System.out.println("ll after change: " + linkedList);
}
}

Output 
Original contents of ll: [L, L, A, L, L, I, N, A] 
Contents of ll after deletion: [L, L, A, L, I, A] 
ll after deleting first and last: [L, A, L, I]
 ll after change: [L, A, L Changed, I]
raja P Web Developer

Convert an ArrayList into an Array


In following program you can   easily convert ArrayList  in to an array. The program starts by means of creating a collection of integers. Then, toArray( ) is called and it Collects an array of Integers. Next the contents of that array are summed by use of a for-each style for loop.The capacity of arraylist grows automatically as elements are added .
// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagecom.allinalljava;
// Convert an ArrayList into an array.
importjava.util.*;
classArrayListToArray {

public static void main(String args[]) {
// Create an array list.
ArrayListarrayList = new ArrayList();
// Add elements to the array list.
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);

System.out.println(" The Data in Array List is" + arrayList);
// Get the array.
Integer array[] = new Integer[arrayList.size()];
array = arrayList.toArray(array);
int sum = 0;
// Sum the array.
for(int i : array) sum += i;
System.out.println("Sum is: " + sum);
}
}


OutPut
The Data in Array List is[1, 2, 3, 4] Sum is: 10
raja P Web Developer

Related Posts Plugin for WordPress, Blogger...