JAVA development

-

-

1 how to create package in java


first write package

package test.abc;
public class MainApplet
{
public int firstWidth()
{
return 5;
}
}

set path of package

write in CMD :=> set classpath=.;c:/mypack/

and then import in another class

//<applet code=”FirstApplet.class” width=”500″ height=”400″></applet>
import test.abc.MainApplet;
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet{
public void paint(Graphics g)
{
setBackground(Color.RED);
g.drawString(“Hello Applet”,25,65);
g.drawRect(45,23,52,63);
}

}
public class FirstWidthSize extends MainApplet
{
public static void main(String [] args)
{
MainApplet mw= new FirstWidthSize();
ws=mw.firstWidth();
Systems.out.println(ws);
}
}

2: How To Create Swing Class in java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SwingTest extends JFrame implements ActionListener
{
JTextField tf1, tf2, tf3;
JButton bSubmit, bClose;

public SwingTest()
{
super (“SwingTest”);
tf1=new JTextField(20);
tf2=new JTextField(20);
tf3=new JTextField(20);
bSubmit=new JButton(“Submit”);
bClose=new JButton(“Close”);

setLayout(new FlowLayout(FlowLayout.LEFT));
add(tf1);
add(tf2);
add(tf3);
add(bSubmit);
bSubmit.addActionListener(this);
add(bClose);
bClose.addActionListener(this);

setSize(600,600);
setVisible(true);
}
public void actionPerformed(ActionEvent a)
{
if(a.getSource()==bSubmit)
{
//tf1.setText(“Hello How are you?”);
//tf2.setText(tf1.getText());
//setTitle(tf1.getText());
String ar= tf1.getText();
String br= tf2.getText();
int a1=Integer.parseInt(ar);
int b1=Integer.parseInt(br);
int c=a1+b1;
tf3.setText(“”+c);

}
else{
//setVisible(false);
//dispose();

// OR
//
//OR
System.exit(0);
}
}
public static void main(String []args)
{
new SwingTest();
}
}

3: How to use buffer reader to get input in java

import java.io.*;
public class InputTest{
public static void main(String[]args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print(“Enter Your Name:”);
String name=br.readLine();

System.out.print(“Enter Your Address:”);
String address=br.readLine();

System.out.print(“Enter Your Age:”);
String ageStr=br.readLine();
//int age=Integer.parseInt(ageStr);
double age=Double.parseDouble(ageStr);

System.out.println(“\n\nYour name is:”+name+”\nAddress:”+address+”\nYour Age:”+Math.sqrt(age));
}
}

4:-How toValue Store in array

public class ArrayTest1
{
public static void main(String []args)
{
int []a=new int[5];
for(int i=0; i<a.length; i++)
{
a[i]=Integer.parseInt(args[i]);
}
for(int j=0; j<a.length;j++)
{
System.out.println(a[j]);
}
}
}

5)Input through Keyboard

the following program shows the keyboard input from the programmer which returns the corresponding value conditioned by by the if-statement in the method min(int, int)

import java.io.*;

public class KeyBoardInput {

public static int min( int a, int b) {

if (a <= b)
return a;
else
return b;
}

public static void main(String[] args) throws IOException {

int x;
int y;

String sb;
String ks;

BufferedReader bk = new BufferedReader (
new InputStreamReader(System.in));

System.out.println (“Enter x “);

sb = bk.readLine();
x = Integer.parseInt(sb);

System.out.println(“Enter y”);

ks = bk.readLine();
y = Integer.parseInt(ks);

bk.close();

System.out.print(“The returned value is =  “);
System.out.println(Math.min(x * 5, y + 20));
}
}

6)How To Upload a file and how to store it?

A quick and dirty Java Sockets API program:

// imports java.net.Socket, java.io.*

void uploadFile(String hostAddr, int port, String fileName) throws
FileNotFoundException, IOException {
byte[] buf = new byte[1000];
int len = -1;

// connect to host at hostAddr, port
Socket sock = new Socket(hostAddr, port);

FileInputStream in = new FileInputStream(fileName);
OutputStream out = sock.getOutputStream();

while ( ( len = in.read(buf) ) != -1 ) {
out.write(buf, 0, len);
out.flush(); // manually flush output stream for sockets
}
out.close();
sock.close();
in.close();
}
7)Simple Date Validation  through Java

This is a small program which provides for java validation

import java.util.Date;
import java.text.ParseException;
import java.text.DateFormat;

public class validateDate
{
public static void main(String args[])
{
String dt = “04/31/2005″;  //Invalid Date
//String dt = “02/29/2004″;  //Valid Date
try
{
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
df.setLenient(false);  // this is important!
Date dt2 = df.parse(dt);
System.out.println(“Date is ok = ” + dt2);
}
catch (ParseException e)
{
System.out.println(“Invalid date ” + dt);
}
catch (IllegalArgumentException e)
{
System.out.println(“Invalid date ” + dt);
}
}
}//End of validateDate

8) The example draw several moving wadges on a circle

/* The example draws several moving wadges on a circle. These wedges move with different speeds */
import java.applet.*;
import java.awt.*;
import java.util.*;

public class DrawMultWedges extends Applet {
Wedges t [] = new Wedges [6];
Graphics g;

public void init ()
{
g = getGraphics ();

for (int i = 0; i < t.length; i++)
{
if ( i < t.length / 2)
t [i] = new Wedges (g, 10, 10 + i * 100, 100, 100, 100 * (i + 1));
else
t [i] = new Wedges (g, 110, 10 + (i – 3) * 100, 100, 100, 100 * (i + 1));
t [i].start ();
}
}

public void paint (Graphics g)
{
}
}

class Wedges implements Runnable {
int x, y, width, height, interval;
Graphics g;
volatile boolean isSet = true;
Thread t;

public Wedges (Graphics g, int x, int y, int width, int height, int interval)
{
this.g = g;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.interval = interval;

t = new Thread (this);
}

public void start ()
{
t.start ();
}

public void run ()
{
int i = 0;

if (g == null)
{
System.out.println (“The reference to Graphics is ” + g);
return;
}
g.drawArc (x, y, width, height, 0, 360); // draw a circle
while (isSet)
{
g.setColor (Color.white);
g.fillArc (x, y, width, height, i – 45, 45); // erase a wedge
g.setColor (Color.black);
g.drawArc (x, y, width, height, i – 45, 45); // draw a circle sector
g.fillArc (x, y, width, height, i, 45); // draw a wedge
if (i != 315)
i += 45;
else
i = 0;
System.out.println (i);
try
{
Thread.sleep (interval);
} catch (InterruptedException ie)
{
System.out.println (ie.getMessage ());
}
}
g.dispose ();
}

}

9)How to read content of an url in java

import java.io.*;
import java.net.*;

/**
* Created on Feb 20, 2003
*/
public class ReadContentsOfURL{
public static void main(String[] args) throws Exception
{
// create a URL object and open a stream to it
URL httpUrl = new URL(“http://www.weather.com/weather/local/94539?lswe=94539″);
InputStream istream = httpUrl.openStream();
// convert stream to a BufferedReader
InputStreamReader ir = new InputStreamReader(istream);
BufferedReader reader = new BufferedReader( ir );
// then read the contents of the URL through a BufferedReader
StringBuffer buf = new StringBuffer();
int nextChar;
while( (nextChar = reader.read()) != -1 )
{
buf.append( (char)nextChar );
}
// close the reader
reader.close();
System.out.println( buf );
}
}

10)How to do ASCII code  printing

public class ASCII_code{
public static void main(String argv[]){  System.out.println(“Value\tChar\tValue\tChar\tValue\tChar\tValue\tChar\tValue\tChar\t”);
int c=1;
while (c < 256)
{
for (int col = 0; col <  5 && c < 256; col++, c++)
System.out.print(c + “\t” + (char)c + “\t”);
System.out.println();
}
}
}

11)How to get the domain name and IP of the machine through java code

/**
* Created on Feb 14, 2003
*/
import java.io.*;
import java.net.*;
public class Whoami
{
/**
* Tells you the domain name and IP of the machine
* you are running.
* Created on Dec 6, 2002 *
* @param args not used.
*/
public static void main (String[] args)
{
try
{
InetAddress localaddr = InetAddress.getLocalHost () ;
System.out.println ( “main Local IP Address : ” + localaddr.getHostAddress () );
System.out.println ( “main Local hostname : ” + localaddr.getHostName () );
System.out.println ( “main Domain name : ” + localaddr.getCanonicalHostName());
System.out.println () ;
InetAddress[] localaddrs = InetAddress.getAllByName ( “localhost” ) ;
for ( int i=0 ; i
{
if ( ! localaddrs[ i ].equals( localaddr ) )
{
System.out.println ( “alt Local IP Address : ” + localaddrs[ i].getHostAddress () );
System.out.println ( “alt Local hostname : ” + localaddrs[ i].getHostName () );
System.out.println () ;
}
}
}
catch ( UnknownHostException e )
{
System.err.println ( “Can’t detect localhost : ” + e) ;
}
}

12)How to do basic date formatting in java

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created on Feb 21, 2003
*/
public class BasicDateFormatting
{
public static void main(String[] args) throws Exception
{
// get today’s date
Date today = Calendar.getInstance().getTime();
// create a short version date formatter
DateFormat shortFormatter
= SimpleDateFormat.getDateInstance( SimpleDateFormat.SHORT );
// create a long version date formatter
DateFormat longFormatter
= SimpleDateFormat.getDateInstance( SimpleDateFormat.LONG );
// create date time formatter, medium for day, long for time
DateFormat mediumFormatter
= SimpleDateFormat.getDateTimeInstance( SimpleDateFormat.MEDIUM,
SimpleDateFormat.LONG );
// use the formatters to output the dates
System.out.println( shortFormatter.format( today ) );
System.out.println( longFormatter.format( today ) );
System.out.println( mediumFormatter.format( today ) );
// convert form date -> text, and text -> date
String dateAsText = shortFormatter.format( today );
Date textAsDate = shortFormatter.parse( dateAsText );
System.out.println( textAsDate );
}
}

13)How To create a serizable JButton

package com.dwave.gui;

import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.Action;
import java.awt.Font;
import com.javaworld.BrowserControl;

/**
*  A <code>Serializable JButton</code> which uses the Lucida Sans font by
*  default because fonts on linux are wierd
*/
public class DButton extends JButton implements java.io.Serializable {
private static final long serialVersionUID = -757087513022738653L;
/**
*  Construct a button
*/
public DButton() {
super();
if(!BrowserControl.isWindowsPlatform())
this.setFont(new java.awt.Font(“Lucida Sans”, 1, 10));
}

/**
*  Construct a button with an icon
*  @param icon an icon
*/
public DButton(Icon icon) {
super(icon);
if(!BrowserControl.isWindowsPlatform())
this.setFont(new java.awt.Font(“Lucida Sans”, 1, 10));
}
/**
*  Construct a button with text
*  @param text some text
*/
public DButton(String text) {
super(text);
if(!BrowserControl.isWindowsPlatform())
this.setFont(new java.awt.Font(“Lucida Sans”, 1, 10));
}
/**
*  Construct a button with an action.<p>
*
*  IMPORTANT: Only works with jdk1.3+
*  @param  a an action
*/
public DButton(Action a) {
super(a);
if(!BrowserControl.isWindowsPlatform())
this.setFont(new java.awt.Font(“Lucida Sans”, 1, 10));
}
/**
*  Construct a button with text and an icon
*  @param text some text
*  @param icon an icon
*/
public DButton(String text, Icon icon) {
super(text, icon);
if(!BrowserControl.isWindowsPlatform())
this.setFont(new java.awt.Font(“Lucida Sans”, 1, 10));
}
}

14)What are assertions and how to implement in java

Assertion facility is added in J2SE 1.4. In order to support this facility J2SE 1.4 added the keyword assert to the language, and AssertionError class. An assertion checks a boolean-typed expression that must be true during program runtime execution. The assertion facility can be enabled or disable at runtime.

Declaring Assertion

Assertion statements have two forms as given below

assert expression;

assert expression1 : expression2;

The first form is simple form of assertion, while second form takes another expression. In both of the form boolean expression represents condition that must be evaluate to true runtime.

If the condition evaluates to false and assertions are enabled, AssertionError will be thrown at runtime.

Some examples that use simple assertion form are as follows.

assert value > 5 ;

assert accontBalance > 0;

assert isStatusEnabled();

The expression that has to be asserted runtime must be boolean value. In third example isStatusEnabled() must return boolean value. If condition evaluates to true, execution continues normally, otherwise the AssertionError is thrown.

Following program uses simple form of assertion

//AssertionDemo.java

Class AssertionDemo{

Public static void main(String args[]){

System.out.println( withdrawMoney(1000,500) );

System.out.println( withdrawMoney(1000,2000) );

}

public double withdrawMoney(double balance , double amount){

assert balance >= amount;

return balance – amount;

}

}

In above given example, main method calls withdrawMoney method with balance and amount as arguments. The withdrawMoney method has a assert statement that checks whether the balance is grater than or equal to amount to be withdrawn. In first call the method will execute without any exception, but in second call it AssertionError is thrown if the assertion is enabled at runtime.

Enable/Disable Assertions

By default assertion are not enabled, but compiler complains if assert is used as an identifier or label. The following command will compile AssertionDemo with assertion enabled.

javac –source 1.4 AssertionDemo.java

The resulting AssertionDemo class file will contain assertion code.

By default assertion are disabled in Java runtime environment. The argument –eanbleassertion or –ea will enables assertion, while –disableassertion or –da will disable assertions at runtime.

The following command will run AssertionDemo with assertion enabled.

Java –ea AssertionDemo

or

Java –enableassertion AssertionDemo

Second form of Assertion

The second form of assertion takes another expression as an argument.

The syntax is,

assert expression1 : expression2;

where expression1 is the condition and must evaluate to true at runtime.

This statement is equivalent to

assert expression1 : throw new AssertionError(expression2);

Note: AssertionError is unchecked exception, because it is inherited from Error class.

Here, expression2 must evaluate to some value.

By default AssertionError doesn’t provide useful message so this form can be helpful to display some informative message to the user.

15)How to Access Parameter passed in url by decoding it in java

import java.util.*;
import java.applet.*;
public class SimpleApplet extends Applet
{
Hashtable searchparms;
public void init()
{
doit();
}
public void doit() {
int i;
String completeURL = getDocumentBase().toString();
System.out.println(“Complete URL: ” + completeURL);
i = completeURL.indexOf(“?”);
if (i > -1) {
String searchURL = completeURL.substring(completeURL.indexOf(“?”) + 1);
System.out.println(“Search URL: ” + searchURL);

StringTokenizer st =
new StringTokenizer(searchURL, “&”);
while(st.hasMoreTokens()){
String searchValue=st.nextToken();
System.out.println(“value :” + searchValue);
}
initHashtable(searchURL);
dumpHashtable();
}
}

public void initHashtable(String search) {
searchparms = new Hashtable();
StringTokenizer st1 =
new StringTokenizer(search, “&”);
while(st1.hasMoreTokens()){
StringTokenizer st2 =
new StringTokenizer(st1.nextToken(), “=”);
searchparms.put(st2.nextToken(), st2.nextToken());
}
}

public void dumpHashtable() {
Enumeration keys = searchparms.keys();
System.out.println(“——–”);
while( keys.hasMoreElements() ) {
String s = (String) keys.nextElement();
System.out.println(“key : ” + s + ” value : ” + searchparms.get(s));
}
System.out.println(“——–”);
}
}

16)How to Get your Ip address in Applet
You can use the following code snippet to get the IP address in an applet:
String ip = (new Socket(getDocumentBase().getHost(), getDocumentBase().getPort()))
.getLocalAddress().getHostAddress();

17)How to detect  the mouse Button When Clicked
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class d extends Applet
implements MouseListener {

public void init() {
this.addMouseListener(this);
}

public void paint(Graphics g) {
g.drawString(“Click here”, 10,10);
}

public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
switch(e.getModifiers()) {
case InputEvent.BUTTON1_MASK: {
System.out.println(“That’s the LEFT button”);
break;
}
case InputEvent.BUTTON2_MASK: {
System.out.println(“That’s the MIDDLE button”);
break;
}
case InputEvent.BUTTON3_MASK: {
System.out.println(“That’s the RIGHT button”);
break;
}
}
}
}

18)How to get programmatically limitation of primitive types

public class PrintLimits
{

public PrintLimits()
{
}

public static void main(String args[]) {

System.out.println(“Min byte value = ” + Byte.MIN_VALUE);
System.out.println(“Max byte value = ” + Byte.MAX_VALUE);
System.out.println(“Min short value = ” + Short.MIN_VALUE);
System.out.println(“Max short value = ” + Short.MAX_VALUE);
System.out.println(“Min int value = ” + Integer.MIN_VALUE);
System.out.println(“Max int value = ” + Integer.MAX_VALUE);
System.out.println(“Min float value = ” + Float.MIN_VALUE);
System.out.println(“Max float value = ” + Float.MAX_VALUE);
System.out.println(“Min double value = ” + Double.MIN_VALUE);
System.out.println(“Max double value = ” + Double.MAX_VALUE);
}
}

18)A java program to use and test the time class of java

// Program to test the Time class

import java.io.*;

public class TestTime

{
public static void main ( String args[]) throws IOException
{

int h, m, s; // variable for the time class to use
int menu; // for the switch
String answer; // for the do while loop
String x; // used for reading in values

// sets up in as the buffer reader
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
System.out.flush(); // clears the system ready for use

// start of the do while loop to allow the user to go around and around
do
{
System.out.println(“Please use the menu below to choose your input types”);
System.out.println(“Menu : “);
System.out.println(“Enter 0 if the default time is to be set”);
System.out.println(“Enter 1 if just the hours are to be set”);
System.out.println(“Enter 2 if the hours and minutes are to be set”);
System.out.println(“Enter 3 if the hours, minutes and seconds are to be set”);
System.out.flush();

x=in.readLine(); // reads the users input in
menu = Integer.parseInt(x);

switch(menu)
{
case 0: // default time
System.out.println(“No parameters were selected and the default time is selected”);
Time t1 = new Time(); // initialises a new instance of the Time class
System.out.println(“The default time is ” + t1.getTime() + ” or ” + t1.get24hrTime());
break;

case 1: // one parameter
System.out.println(“You have selected to enter one parameter”);
System.out.println(“Please enter the hour for the clock between 0 and 23 “); // prompts the user for the input
System.out.flush();
x=in.readLine(); // reads the users input in
h=Integer.parseInt(x); // converts the string to an integer
Time t2 = new Time(h); // initialises a new instance of the time class
System.out.println(“The time you have selected is ” + t2.getTime() + ” or ” + t2.get24hrTime());
System.out.println(“The Hours entered were ” + t2.getHour());
break;

case 2: // two parameters
System.out.println(“You have selected to enter two parameters.”);
System.out.println(“Please enter the hour for the clock “); // prompts the user for the first variable
System.out.println(“Enter a value between 0 and 23″);
System.out.flush();

x=in.readLine(); // reads the users input in
h=Integer.parseInt(x); // converts the string into an integer
System.out.flush();

System.out.println(“Please enter the minutes for the clock”); //prompts the user for the second variable
System.out.println(“Enter a value between 0 and 59″);
System.out.flush();

x=in.readLine(); // reads the users input in
m=Integer.parseInt(x); // converts the string to an integer

Time t3 = new Time(h,m); // Initialises a new instance of the time class
System.out.println(“The time you selected is ” + t3.getTime() + ” or ” + t3.get24hrTime());
System.out.println(“The Hours entered were ” + t3.getHour() + ” and the minutes were ” + t3.getMinute());
break;

case 3: // three parameters
System.out.println(“You have selected to enter 3 parameters”);
System.out.println(“Please enter the hour for the clock “); // prompts the user for the first variable
System.out.println(“Enter a value between 0 and 23″);
System.out.flush();

x=in.readLine(); // reads the users input in
h=Integer.parseInt(x); // converts the string into an Integer
System.out.flush();

System.out.println(“Please enter the minutes for the clock”); //prompts the user for the second variable
System.out.println(“Enter a value between 0 and 59″); // read the users input in
System.out.flush();

x=in.readLine(); // reads the users input in
m=Integer.parseInt(x); // converts the string to an integer

System.out.println(“Enter the seconds for the clock”); // prompts the user for the third variable
System.out.println(“Enter a value between 0 and 59″);
System.out.flush();

x=in.readLine();
s=Integer.parseInt(x); // converts the string to an integer

Time t4 = new Time(h,m,s); // initialises a new instance of the class time
System.out.println(“The time you have selected is ” + t4.getTime() + ” or ” + t4.get24hrTime());
System.out.println(“The Hours entered were ” + t4.getHour() + ” and the minutes were ” + t4.getMinute()+ ” and the seconds were ” + t4.getSecond());
break;

default:
System.out.println(“Please select a number between 0 and 3″);
break;
}

System.out.println(“Enter Y to continue or anything else to stop “);
System.out.flush();
answer=in.readLine(); // reads the users input in

} while(answer.equalsIgnoreCase(“Y”));

}// ends the main

}// ends the class

19)How to create a java applet with an animation of numbers moving across the  screen

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

class Star extends Thread{
private double x;
private double y;
private double prevX;
private double prevY;
private double headX;
private DrawArea dA;
private int napTime;
private int red;
private int green;
private int blue;
private int d;
private double m;
private static Image im;
private static Graphics buff;

public Star(DrawArea dA, Image im, Graphics buff){
napTime = 40;
this.dA = dA;
this.im = im;
this.buff = buff;
}
public void pickColor(){
do{
red = 1 + (int)(Math.random() * 256);
green = 1 + (int)(Math.random() * 256);
blue = 1 + (int)(Math.random() * 256);
} while(red < 25 || green < 25 || blue < 25);
}
public double getX(){
do{
x = (Math.random() * 600);
}while(x == 300.00);
return x;
}

public double getY(){
do{
y = (Math.random() * 380);
}while(y == 190.00);
return y;
}
public double getSlope(double x, double y){
return (double)(y – 190.00)/(double)(x – 300.00);
}

public void setNapTime(double x, double y){
d = (int)Math.sqrt(((300.00 – x)*(300.00 – x)) + ((190.00 – y)*(190.00 – y)));
napTime = (d/20)*2;
}

public double getHeadX(){
double headX = 1.00;
if(x < 300.00){
if(d < 100 && m < 4 && m > -4)
headX = 1.00;
else if(d < 100 && m >= 7)
headX = .10;
else{
headX = (300.00 – x)/30;
if(headX < 1.00)
headX = 1.00;
}
headX = -headX;
}
else if(x > 300.00){
if(d < 100 && m < 4 && m > -4)
headX = 1.00;
else if(d < 100 && m <= -7)
headX = .10;
else{
headX = (x – 300.00)/30;
if(headX < 1.00)
headX = 1.00;
}
}
return headX;
}

public void run(){
x = getX();
y = getY();
prevX = x;
prevY = y;
setNapTime(x, y);
headX = getHeadX();
m = getSlope(x, y);
pickColor();
while(true){
try{
Thread.sleep(90);
}
catch(Exception e){}

dA.repaint();

prevX = x;
prevY = y;

x += headX;
y = 190.00-m*(300.00 – (double)x);

if(x < 0.00 || x > 600.00 || y < 0.00 || y > 380.00){
x = getX();
y = getY();
prevX = x;
prevY = y;
setNapTime(x, y);
headX = getHeadX();
m = getSlope(x, y);
pickColor();
}
}
}

public void draw(){
buff.setColor(new Color(red, green, blue));
buff.drawString(“(” + (int)x + “, ” + (int)y + “)”, (int)x, (int) y);
if(red + 5 <= 256)
red += 5;
if(green + 5 <= 256)
green += 5;
if(blue + 5 <= 256)
blue += 5;
}
public static void load(Graphics g){
g.drawImage(im, 0, 0, null);
}
}

class DrawArea extends Panel{
private int i;
private Star sp[];
private int j;
private Image im;
private Graphics buff;
public DrawArea(Image im){
j = 90;
sp = new Star[j];
this.im = im;
buff = im.getGraphics();

for(int i = 0; i < j; i++){
sp[i] = new Star(this, im, buff);
sp[i].setPriority(Thread.MAX_PRIORITY);
}
for(int i = 0; i < j; i++){
sp[i].start();
}
setBackground(Color.black);
}
public void paint(Graphics g){
buff.setColor(Color.black);
buff.fillRect(0, 0, 600, 380);
for(int i = 0; i < j; i++){
sp[i].draw();
}
Star.load(g);
}
public void update(Graphics g){
paint(g);
}
}

public class Number extends Applet{
private static DrawArea dA;
public void init(){
dA = new DrawArea(createImage(600, 380));
setLayout(new BorderLayout());
add(dA, BorderLayout.CENTER);
}
public void stop(){
destroy();
}
}

20)Using Stored procedures in java

How to call procedure in Java?

Stored procedure are user-generated functions or procedures that, once created in the database, can be called by the client applications, such as Java application. In this example we’ll demonstrate how to use the JDBC java.sql.CallableStatement to call a stored procedure.

The store procedure in this example is just for inserting a record into table. Just like the PreparedStatement interface, in the CallableStatement we can pass the parameter to the procedure by calling the appropriate setXXX(index, value) method.

Example code:

package org.kodejava.example.sql;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class CallableStatementDemo {
private static String url = “jdbc:oracle:thin:@localhost:1521:xe”;
private static String username = “kodejava”;
private static String password = “welcome”;

public static void main(String[] args) throws Exception {
Connection conn = null;
try {
Class.forName(“oracle.jdbc.driver.OracleDriver”);
conn = DriverManager.getConnection(url, username, password);

//
// Create a CallableStatement to execute the CREATE_USERS procedure
//
CallableStatement stmt = conn.prepareCall(“{call CREATE_USERS (?, ?, ?, ?, ?, ?)}”);

//
// Defines all the required parameter values.
//
stmt.setString(1, “kodejava”);
stmt.setString(2, “welcome”);
stmt.setString(3, “Kode”);
stmt.setString(4, “Java”);
stmt.setString(5, “Denpasar – Bali”);
stmt.setString(6, “webmaster[at]kodejava[.]org”);
stmt.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
}

Below is the stored procedure that was executed in the code above.

CREATE OR REPLACE PROCEDURE CREATE_USERS (username IN VARCHAR2, password IN VARCHAR2, firstName IN VARCHAR2, lastName IN VARCHAR2, address IN VARCHAR2, email IN VARCHAR2) AS
BEGIN
INSERT INTO users (username, password, first_name, last_name, address, email) VALUES (username, password, firstName, lastName, address, email);
END CREATE_USERS;

21)How to Make a Java Class Immutable

Making a class immutable

Immutability must be familiar to every one when we talk about String & StringBuffer classes in java. Strings are considered immutable because the values contained in the reference variable cannot be changed. Whereas String Buffer is considered mutable because the value in a string buffer can be changed (i.e. mutable).

However I always thought how to make our user defined classes as immutable though I am unaware as to why any one would need this.

The reason perhaps might be clear once we have a look at the code.

Now in order to make a class immutable we must restrict changing the state of the class object by any means. This in turn means avoiding an assignment to a variable. We can achieve this through a final modifier. To further restrict the access we can use a private access modifier. Above do not provide any method where we modify the instance variables.

Still done? No. How if some body creates a sub class from our up till now immutable class? Yes here lies the problem. The new subclass can contain methods, which over ride our base class (immutable class) methods. Here he can change the variable values.

Hence make the methods in the class also final. Or a better approach. Make the immutable class itself final. Hence cannot make any sub classes, so no question of over ridding.

The following code gives a way to make the class immutable.

/*
Code Developed By Ashish Agarwal
This code demonstrates the way to make a class immutable
*/

// The immutable class which is made final
final class MyImmutableClass
{
// instance var are made private & final to restrict the access

private final int count;
private final double value;

// Constructor where we can provide the constant value
public MyImmutableClass(int paramCount,double paramValue)
{
count = paramCount;
value = paramValue;
}

// provide only methods which return the instance var
// & not change the values

public int getCount()
{
return count;
}

public double getValue()
{
return value;
}
}

// class TestImmutable
public class TestImmutable
{
public static void main(String[] args)
{
MyImmutableClass obj1 = new MyImmutableClass(3,5);

System.out.println(obj1.getCount());
System.out.println(obj1.getValue());

// there is no way to change the values of count & value-
// no method to call besides getXX, no subclassing, no public access to var -> Immutable
}
}

The possible use of immutable classes would be a class containing a price list represented for a set of products.
Otherwise also this represents a good design

22)How to create an image in java through coding

createasimpleimage.java

import java.awt.*;
import java.applet.*;
import javax.swing.*;

public class CreateImage extends Applet
{
private Image image;
//method called by the browser of applet viewer when an Applet is going to be executed

public void init()
{
image = getImage(getDocumentBase(),”Logo.gif”);
}

public void paint(Graphics g)
{
g.drawImage(image, 0,0,this);
}
}

Leave a Reply