Wednesday, June 10, 2009

Android API Rotaion 3d

Here the Example Extracted from API Demos

Rotation 3d

package com.dci;

import com.dci.R;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;

public class Transition3d extends Activity implements
AdapterView.OnItemClickListener, View.OnClickListener
{
private ListView mPhotosList;
private ViewGroup mContainer;
private ImageView mImageView;

// Names of the photos we show in the list
private static final String[] PHOTOS_NAMES = new String[]
{
"Lyon",
"Livermore",
"Tahoe Pier",
"Lake Tahoe",
"Grand Canyon",
"Bodie"
};

// Resource identifiers for the photos we want to display
private static final int[] PHOTOS_RESOURCES = new int[]
{
R.drawable.photo1,
R.drawable.photo2,
R.drawable.photo3,
R.drawable.photo4,
R.drawable.photo5,
R.drawable.photo6
};

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.animations_main_screen);

mPhotosList = (ListView) findViewById(android.R.id.list);
mImageView = (ImageView) findViewById(R.id.picture);
mContainer = (ViewGroup) findViewById(R.id.container);

// Prepare the ListView
final ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, PHOTOS_NAMES);

mPhotosList.setAdapter(adapter);
mPhotosList.setOnItemClickListener(this);

// Prepare the ImageView
mImageView.setClickable(true);
mImageView.setFocusable(true);
mImageView.setOnClickListener(this);

// Since we are caching large views, we want to keep their cache
// between each animation
mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
}

/**
* Setup a new 3D rotation on the container view.
*
* @param position the item that was clicked to show a picture, or -1 to show the list
* @param start the start angle at which the rotation must begin
* @param end the end angle of the rotation
*/
private void applyRotation(int position, float start, float end) {
// Find the center of the container
final float centerX = mContainer.getWidth() / 2.0f;
final float centerY = mContainer.getHeight() / 2.0f;

// Create a new 3D rotation with the supplied parameter
// The animation listener is used to trigger the next animation
final Rotate3dAnimation rotation =
new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
rotation.setDuration(500);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
rotation.setAnimationListener(new DisplayNextView(position));

mContainer.startAnimation(rotation);
}

public void onItemClick(AdapterView parent, View v, int position, long id) {
// Pre-load the image then start the animation
mImageView.setImageResource(PHOTOS_RESOURCES[position]);
applyRotation(position, 0, 90);
}

public void onClick(View v) {
applyRotation(-1, 180, 90);
}

/**
* This class listens for the end of the first half of the animation.
* It then posts a new action that effectively swaps the views when the container
* is rotated 90 degrees and thus invisible.
*/
private final class DisplayNextView implements Animation.AnimationListener {
private final int mPosition;

private DisplayNextView(int position) {
mPosition = position;
}

public void onAnimationStart(Animation animation) {
}

public void onAnimationEnd(Animation animation) {p
mContainer.post(new SwapViews(mPosition));
}

public void onAnimationRepeat(Animation animation) {
}
}

/**
* This class is responsible for swapping the views and start the second
* half of the animation.
*/
private final class SwapViews implements Runnable
{
private final int mPosition;

public SwapViews(int position)
{
mPosition = position;
}

public void run() {
final float centerX = mContainer.getWidth() / 2.0f;
final float centerY = mContainer.getHeight() / 2.0f;
Rotate3dAnimation rotation;

if (mPosition > -1) {
mPhotosList.setVisibility(View.GONE);
mImageView.setVisibility(View.VISIBLE);
mImageView.requestFocus();

rotation = new Rotate3dAnimation(90, 180, centerX, centerY, 310.0f, false);
} else {
mImageView.setVisibility(View.GONE);
mPhotosList.setVisibility(View.VISIBLE);
mPhotosList.requestFocus();

rotation = new Rotate3dAnimation(90, 0, centerX, centerY, 310.0f, false);
}

rotation.setDuration(500);
rotation.setFillAfter(true);
rotation.setInterpolator(new DecelerateInterpolator());

mContainer.startAnimation(rotation);
}
}

}


/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.dci;

import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.graphics.Camera;
import android.graphics.Matrix;

public class Rotate3dAnimation extends Animation
{
private final float mFromDegrees;
private final float mToDegrees;
private final float mCenterX;
private final float mCenterY;
private final float mDepthZ;
private final boolean mReverse;
private Camera mCamera;

/**
* Creates a new 3D rotation on the Y axis. The rotation is defined by its
* start angle and its end angle. Both angles are in degrees. The rotation
* is performed around a center point on the 2D space, definied by a pair
* of X and Y coordinates, called centerX and centerY. When the animation
* starts, a translation on the Z axis (depth) is performed. The length
* of the translation can be specified, as well as whether the translation
* should be reversed in time.
*
* @param fromDegrees the start angle of the 3D rotation
* @param toDegrees the end angle of the 3D rotation
* @param centerX the X center of the 3D rotation
* @param centerY the Y center of the 3D rotation
* @param reverse true if the translation should be reversed, false otherwise
*/
public Rotate3dAnimation(float fromDegrees, float toDegrees,
float centerX, float centerY, float depthZ, boolean reverse)
{
mFromDegrees = fromDegrees;
mToDegrees = toDegrees;
mCenterX = centerX;
mCenterY = centerY;
mDepthZ = depthZ;
mReverse = reverse;
}

@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
mCamera = new Camera();
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final float fromDegrees = mFromDegrees;
float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

final float centerX = mCenterX;
final float centerY = mCenterY;
final Camera camera = mCamera;

final Matrix matrix = t.getMatrix();

camera.save();
if (mReverse) {
camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
} else {
camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
}
camera.rotateY(degrees);
camera.getMatrix(matrix);
camera.restore();

matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
}



Create One Folder name anim
keep the two file on to that





and save it as layout_bottom_to_top_slide.xml

and one more file




save it as slide_right.xml











save it as a animations_main_screen.xml

onKeyEvent Object Moving in Android Graphics

on Key Event Object Moving example on android

package com.dci.object;

import com.dci.object.DemoGameView.GameThread;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;

public class DemoObjectMove extends Activity
{
private static final int MENU_PAUSE = Menu.FIRST;

private static final int MENU_RESUME = Menu.FIRST + 1;

private static final int MENU_START = Menu.FIRST + 2;

private static final int MENU_STOP = Menu.FIRST + 3;

private GameThread mGameThread;

private DemoGameView mGameView;


@Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);

menu.add(0, MENU_START, 0, R.string.menu_start);
menu.add(0, MENU_STOP, 0, R.string.menu_stop);
menu.add(0, MENU_PAUSE, 0, R.string.menu_pause);
menu.add(0, MENU_RESUME, 0, R.string.menu_resume);

return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case MENU_START:
mGameThread.doStart();
return true;
case MENU_STOP:
mGameThread.setState(GameThread.STATE_LOSE);
return true;
case MENU_PAUSE:
mGameThread.pause();
return true;
case MENU_RESUME:
mGameThread.unpause();
return true;
}

return false;
}

/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);


requestWindowFeature(Window.FEATURE_NO_TITLE);


setContentView(R.layout.main);

mGameView =(DemoGameView) findViewById(R.id.game);
mGameThread = mGameView.getThread();

mGameThread.setState(GameThread.STATE_READY);
}

@Override
protected void onPause()
{
super.onPause();

mGameView.getThread().pause();

}
}


View For the Above activity


package com.dci.object;

import com.dci.object.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class DemoGameView extends SurfaceView implements SurfaceHolder.Callback
{

class GameThread extends Thread
{
// States Used In Our Demo Game Object

public static final int STATE_LOSE = 1;
public static final int STATE_PAUSE = 2;
public static final int STATE_READY = 3;
public static final int STATE_RUNNING = 4;
public static final int STATE_WIN = 5;

private int mMode;
private boolean mRun = false;

// Co ordinates

private float x;
private float y;

// To control the Speed the Variable is craeted
private static final int SPEED = 100;

//Movements of the Object Variables
private boolean dRight;
private boolean dLeft;
private boolean dUp;
private boolean dDown;

// Canvas Specs.
private int mCanvasWidth;
private int mCanvasHeight;

private long mLastTime;

private Bitmap mDciObject;

private SurfaceHolder mSurfaceHolder;

//Constructor
public GameThread(SurfaceHolder surfaceHolder, Context context,
Handler handler)
{
mSurfaceHolder = surfaceHolder;
mContext = context;

x = 0;
y = 0;

mDciObject = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.snowflake);

}
//Start The Game
public void doStart()
{
synchronized (mSurfaceHolder)
{
// Initialize game here!

x = 0;
y = 50;

mLastTime = System.currentTimeMillis() + 100;
setState(STATE_RUNNING);
}
}
public void pause()
{
synchronized (mSurfaceHolder)
{
if (mMode == STATE_RUNNING)
setState(STATE_PAUSE);
}
}

@Override
public void run()
{
while (mRun)
{
Canvas c = null;
try
{
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder)
{
if (mMode == STATE_RUNNING)
updateGame();
doDraw(c);
}
}
finally
{
if (c != null)
{
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
public void setRunning(boolean b)
{
mRun = b;
}
public void setState(int mode)
{
synchronized (mSurfaceHolder)
{
setState(mode, null);
}
}
public void setState(int mode, CharSequence message)
{
synchronized (mSurfaceHolder)
{
mMode = mode;
}
}
public void setSurfaceSize(int width, int height)
{

synchronized (mSurfaceHolder)
{
mCanvasWidth = width;
mCanvasHeight = height;
}
}
public void unpause()
{
// Move the real time clock up to now
synchronized (mSurfaceHolder)
{
mLastTime = System.currentTimeMillis() + 100;
}
setState(STATE_RUNNING);
}

boolean doKeyDown(int keyCode, KeyEvent msg)
{
boolean handled = false;
synchronized (mSurfaceHolder)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
{
dRight = true;
handled = true;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT)
{
dLeft = true;
handled = true;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_UP)
{
dUp = true;
handled = true;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
{
dDown = true;
handled = true;
}
return handled;
}
}
boolean doKeyUp(int keyCode, KeyEvent msg)
{
boolean handled = false;
synchronized (mSurfaceHolder)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
{
dRight = false;
handled = true;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT)
{
dLeft = false;
handled = true;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_UP)
{
dUp = false;
handled = true;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
{
dDown = false;
handled = true;
}
return handled;
}
}
private void doDraw(Canvas canvas)
{
// empty canvas
canvas.drawARGB(255,0,0,40);

canvas.drawBitmap(mDciObject, x, y, new Paint());
}

private void updateGame()
{

long now = System.currentTimeMillis();

if (mLastTime > now)
return;
double elapsed = (now - mLastTime) / 1000.0;
mLastTime = now;


if (dUp)
y -= elapsed * SPEED;
if (dDown)
y += elapsed * SPEED;
if (y < 0)
y = 0;
else if (y >= mCanvasHeight - mDciObject.getHeight())
y = mCanvasHeight - mDciObject.getHeight();
if (dLeft)
x -= elapsed * SPEED;
if (dRight)
x += elapsed * SPEED;
if (x < 0)
x = 0;
else if (x >= mCanvasWidth - mDciObject.getWidth())
x = mCanvasWidth - mDciObject.getWidth();
}
}
private Context mContext;

private GameThread thread;

public DemoGameView(Context context,AttributeSet atts)
{
super(context,atts);

SurfaceHolder holder = getHolder();
holder.addCallback(this);

thread = new GameThread(holder, context, new Handler()
{
@Override
public void handleMessage(Message m)
{
// Use for pushing back messages.
}
});

setFocusable(true);

}
public GameThread getThread()
{
return thread;
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent msg)
{
return thread.doKeyDown(keyCode, msg);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent msg)
{
return thread.doKeyUp(keyCode, msg);
}

@Override
public void onWindowFocusChanged(boolean hasWindowFocus)
{
if (!hasWindowFocus)
thread.pause();
}


public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
thread.setSurfaceSize(width, height);
}


public void surfaceCreated(SurfaceHolder holder)
{

thread.setRunning(true);
thread.start();
}
public void surfaceDestroyed(SurfaceHolder holder)
{

boolean retry = true;
thread.setRunning(false);
while (retry)
{
try
{
thread.join();
retry = false;
}
catch (InterruptedException e)
{
}
}
}

}

Android Graphics Tutorial

How To draw a circle in android?

Follow the Steps U will get how to a draw a circle .........

These is the NewCircle Activity Class

package com.android;

import android.app.Activity;
import android.os.Bundle;

public class NewCircle extends Activity
{


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new CircleView(this, 25, 25, 20));

}
}



This is the Circle View Class


package com.android;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

public class CircleView extends View
{

// Variables
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

// Constructor
public CircleView(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}

/ canvas onDraw Method for drawing a circle

@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}

Thursday, February 12, 2009

Convertion

Question

How can I convert my Java classes to an executable .EXE file for Windows?

Answer

This is a very common question asked in the comp.lang.java newsgroup. Its often useful to have an executable application when deploying your applications to a specific platform, but remember to make your .class files available for users running Unix/Macintosh/other platforms.

Microsoft used to provide a free system development kit (SDK), for Java, which includes the jexegen tool.
This will convert class files into a .EXE form. The only disadvantage is that users need a Microsoft Java Virtual Machine (JVM) installed.
Microsoft no longer supports this however, and you should transition to a new Win 32 Java system.
See http://java.sun.com/ for the latest version of a Java interpreter for Winodws.

Though I've not used these tools personally, others have recommended Visual Age for Java, and
Duckware's Java to Windows EXE (Java2Exe) application available from http://www.duckware.com/java2exe/index.html

Jad FAQ .....

FAQ

Q1: Is the source code of Jad available?
A1: Currently I have no plans to release the Jad source code for any purposes including porting to other computer platforms.

Q2: What is the option -dead for?
A2: This option forces Jad to decompile the dead portions of bytecode. For example, non-optimizing compilation of the following code can produce the dead bytecode: if (false)
{
...
}
This option should be on by default, but the incorrect dead bytecode can crash Jad.

Q3: Why does Jad fail to generate the throws clause in the method declarations like the one in int divide(int a, int b) throws DivideByZero { ... } ?
A3: This throws clause is represented in the Java class files by the Exceptions attribute. The Java Virtual Machine itself doesn't use these attributes (well, at least, the common implementations of JVM), so they can be stripped out of the Java class files. Jad has no way of restoring this information in full if it's missing from the class file.

Q4: Why does Jad generate weird-looking static fields like class$java$lang$Float and static methods class$(String)?
A4: These fields/methods are the internal representation of the .class expression and automatically generated by compiler. For example, java.lang.Thread.class is translated into the following: ...
((class$java$lang$Thread == null) ?
(class$java$lang$Thread = class$("java.lang.Thread")) :
class$java$lang$Thread);
...
static Class class$(String s)
{
try
{
return Class.forName(s);
}
catch(ClassNotFoundException ex)
{
throw new NoClassDefFoundError(ex.getMessage());
}
}
static Class class$java$lang$Thread;
This is fixed in 1.5.8. The explanation for the previous versions: Jad doesn't convert all that back to the original expression, but apparently the Sun JDK 1.2 compiler is able to compile "the long format" successfully. JDK 1.3 compiler doesn't accept names containing class$, so in order to recompile the decomplied class you need to change all expressions similar to the conditional expression above to .class and remove static methods/fields whose names start with class$.

Q5: Jad refuses to decompile my class file saying "Class file version mismatch". What can I do?
A5: Use -debug option. Jad then complains about the version mismatch, but attempts to decompile the file anyway. Note that this works starting from the version 1.5.6e.

Q6: Jad fails to decompile my class file, it spits out a bunch of gotos and JVM instructions. Why is that?
A6: There could be several possible reasons: the class file has been obfuscated or it was produced by non-JDK Java compiler or some functions were inlined by Java compiler. Generally Jad works best with class files generated by Sun Java compilers. If you encounter such a behaviour, please send me a bug report with attached .class files.

Q7: How to decompile jar or zip archive with classes?
A7: "Unjar" (jar xvf ) or unzip (using unzip or WinZip) the archive into a directory on your hard drive. Then see the next answer.

Q8: How to decompile the whole class tree?
A8: Run jad -r [-d] [] **/*.class
On Unix the last argument should be in single quotes. For more information please read Readme.txt.

Q9: Why do I get "Class <>List not found" from the compiler?
A9: There are two List classes: java.awt.List and java.util.List. If Jad generates two import directives: import java.awt.*;
import java.util.*;
and your class actually uses the List class, the compiler will complain. Prior version 1.5.7d use the command-line option -pi to prevent Jad from combining the import directives.

Q10: How to make the command-line options -ff -nonlb -space -t to be on by default?
A10: Use the environment variable JAD_OPTIONS to permanently override the default settings. The example for Windows: set JAD_OPTIONS=-ff+ -nonlb+ -t+ -space+

Q11: How to extract Java classes from an executable file (.exe)?
A11: Use the Java-Split utility written by the Decafe Pro team. Download it from http://decafe.hypermart.net/javasplit.htm. Or use J++Extract from http://www.multimania.com/dolmen/productions.

Q12: What does the error message "JavaClassFileParseException: Invalid tag value 0x0" mean exactly?
A12: It means that your file is not a valid Java class and Jad was unable to parse it successfully. Either the file was broken (for example, during download) or the package this class belongs to contains a custom Java class loader that modifies (or decrypts) Java classes after reading them into the memory. In both cases Jad cannot decompile this file as it is.

.class to .java File Conversion

Jad:--

Jad, the fast JAva Decompiler, is a program that reads one or more Java class files and converts them into Java source files which can be compiled again.
Jad is a 100% pure C++ program and it generally works several times faster than decompilers written in Java. Jad doesn't use the Java runtime for its functioning, therefore no special setup is required (like changes to the CLASSPATH variable).

Jad is not open source but it is free to use.

Make sure to download the GUI interface, FrontEnd Plus .

On Windows, a file association with the .class extension is made so if you click on a class file then the decompiled is shown in FrontEnd Plus right away.

JadJad, the fast JAva Decompiler, is a program that reads one or more Java class files and converts them into Java source files which can be compiled again.
Jad is a 100% pure C++ program and it generally works several times faster than decompilers written in Java. Jad doesn't use the Java runtime for its functioning, therefore no special setup is required (like changes to the CLASSPATH variable).
Jad is not open source but it is free to use.
Make sure to download the GUI interface, FrontEnd Plus .
On Windows, a file association with the .class extension is made so if you click on a class file then the decompiled is shown in FrontEnd Plus right away.


Installation

Unzip jad.zip file into any appropriate directory on your hard drive. This will create two files:
- an executable file named 'jad.exe' (Windows 9x/NT/2000) or 'jad' (UNIX)
- README file 'Readme.txt', which contains the short user's manual
For UNIX users: make 'jad' executable: chmod a+x jad
No further setup is required.

Wednesday, February 11, 2009

Mobile Technology Ecosystem

To learn more about J2ME follow our setup guide and build your hello world application. Then look over the examples included with the J4ME distribution to see more complex examples.

Mobile Technology Ecosystem

When do I use J2ME?
What is the best technology for me?
These are good questions because J2ME is not the best solution for all types of applications.
Like with desktop applications your first decision is whether a web or desktop application is best. "Web 2.0" features have made traditional web applications very sophisticated, however, the same can not be said about the Mobile Web. Still this is the way to go for data driven applications because they are much easier to develop and work on all phones. If you need fancy UIs, to perform computations, or access to peripherals like Bluetooth, than your choice is J2ME or one its peers.
Web browsing on your phone is typically done through WAP (Wireless Application Protocol). WAP is similar to HTML but is very basic. Over time phones will adopt regular HTML in favor of WAP. The iPhone already does this and Google's Android will continue this trend.
Mobile applications must be written in the environment supported by the phone. J2ME is the most widely supported platform, but it is not on every phone. Where you don't find J2ME you'll find BREW. There are some other options such as Symbian and Windows Mobile.
BREW is found on about 1/3 of phones in the U.S.; notably it is Verizon's platform of choice. For all intents and purposes BREW is a C++ solution. It has some advantages over J2ME but most consider it to be a closed platform. As such the vast majority of phone applications are written in J2ME and some are occasionally ported to BREW.
Symbian is a phone operating system found on Nokias and other phones. Unlike BREW, however, it is not mutually exclusive with J2ME. For example AT&T's Nokia phones also run J2ME. Symbian applications are written in C++ and give more access to the phone than J2ME does. However, they are harder to write and run in fewer places.
Windows Mobile is a stripped down version of Windows that Microsoft releases for phones. As you might have guessed programming it can be done using stripped down versions of the languages used on Windows. For example C++ with MFC or ATL, .NET, and even J2ME.
Further complicating things are smartphones. No matter the carrier they run the platform that is best for them. For example BlackBerry phones use J2ME (and proprietary Java classes). While the iPhone does not officially support any language.
Hopefully this chart simplifies things. An "X" means it is fully supported and a "/" means it is supported on some phones. The columns for phones mean that phone supports a technology no matter the carrier.

AT&T Verizon Sprint T-Mobile BlackBerry Windows iMobile iPhone

WAP x x x x x x x
J2ME x x x x x x
BREW x
Symbian
Windows Mobile x

JDBC Java DataBase Connectivity

JDBC - Java Database Connectivity

What is JDBC?
Java Database Connectivity (JDBC) is a programming framework for Java developers writing programs that access information stored in databases, spreadsheets, and flat files. JDBC is commonly used to connect a user program to a "behind the scenes" database, regardless of what database management software is used to control the database. In this way, JDBC is cross-platform [ 1]. This article will provide an introduction and sample code that demonstrates database access from Java programs that use the classes of the JDBC API, which is available for free download from Sun's site [3].
A database that another program links to is called a data source. Many data sources, including products produced by Microsoft and Oracle, already use a standard called Open Database Connectivity (ODBC). Many legacy C and Perl programs use ODBC to connect to data sources. ODBC consolidated much of the commonality between database management systems. JDBC builds on this feature, and increases the level of abstraction. JDBC-ODBC bridges have been created to allow Java programs to connect to ODBC-enabled database software [1].
This article assumes that readers already have a data source established and are moderately familiar with the Structured Query Language (SQL), the command language for adding records, retrieving records, and other basic database manipulations. See Hoffman's tutorial on SQL if you are a beginner or need some refreshing.

Using a JDBC driver
Regardless of data source location, platform, or driver (Oracle, Microsoft, etc.), JDBC makes connecting to a data source less difficult by providing a collection of classes that abstract details of the database interaction. Software engineering with JDBC is also conducive to module reuse. Programs can easily be ported to a different infrastructure for which you have data stored (whatever platform you choose to use in the future) with only a driver substitution.
As long as you stick with the more popular database platforms (Oracle, Informix, Microsoft, MySQL, etc.), there is almost certainly a JDBC driver written to let your programs connect and manipulate data. You can download a specific JDBC driver from the manufacturer of your database management system (DBMS) or from a third party (in the case of less popular open source products) [5]. The JDBC driver for your database will come with specific instructions to make the class files of the driver available to the Java Virtual Machine, which your program is going to run. JDBC drivers use Java's built-in DriverManager to open and access a database from within your Java program.
To begin connecting to a data source, you first need to instantiate an object of your JDBC driver. This essentially requires only one line of code, a command to the DriverManager, telling the Java Virtual Machine to load the bytecode of your driver into memory, where its methods will be available to your program. The String parameter below is the fully qualified class name of the driver you are using for your platform combination:

Class.forName("org.gjt.mm.mysql.Driver").newInstance();

Connecting to your database
To actually manipulate your database, you need to get an object of the Connection class from your driver. At the very least, your driver will need a URL for the database and parameters for access control, which usually involves standard password authentication for a database account.
As you may already be aware, the Uniform Resource Locator (URL) standard is good for much more than telling your browser where to find a web page: http://www.vusports.com/index.html
The URL for our example driver and database looks like this: jdbc:mysql://db_server:3306/contacts/
Even though these two URLs look different, they are actually the same in form: the protocol for connection, machine host name and optional port number, and the relative path of the resource. Your JDBC driver will come with instructions detailing how to form the URL for your database. It will look similar to our example.
You will want to control access to your data, unless security is not an issue. The standard least common denominator for authentication to a database is a pair of strings, an account and a password. The account name and password you give the driver should have meaning within your DBMS, where permissions should have been established to govern access privileges.
Our example JDBC driver uses an object of the Properties class to pass information through the DriverManager, which yields a Connection object: Properties props = new Properties();
props.setProperty("user", "contacts");
props.setProperty("password", "blackbook");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/contacts/", props);
Now that we have a Connection object, we can easily pass commands through it to the database, taking advantage of the abstraction layers provided by JDBC.
Structuring statements
Databases are composed of tables, which in turn are composed of rows. Each database table has a set of rows that define what data types are in each record. Records are also stored as rows of the database table with one row per record. We use the data source connection created in the last section to execute a command to the database.
We write commands to be executed by the DBMS on a database using SQL. The syntax of a SQL statement, or query, usually consists of an action keyword, a target table name, and some parameters. For example: INSERT INTO songs VALUES (
"Jesus Jones", "Right Here, Right Now");
INSERT INTO songs VALUES (
"Def Leppard", "Hysteria");
These SQL queries each added a row of data to table "songs" in the database. Naturally, the order of the values being inserted into the table must match the order of the corresponding columns of the table, and the data types of the new values must match the data types of the corresponding columns. For more information about the supported data types in your DBMS, consult your reference material.
To execute an SQL statement using a Connection object, you first need to create a Statement object, which will execute the query contained in a String. Statement stmt = con.createStatement();
String query = ... // define query
stmt.executeQuery(query);
Example: Parsing a text file into a database table
In the course of modernizing a record keeping system, you encounter a flat file of data that was created long before the rise of the modern relational database. Rather than type all the data from the flat file into the DBMS, you may want to create a program that reads in the text file, inserting each row into a database table, which has been created to model the original flat file structure.
In this case, we examine a very simple text file. There are only a few rows and columns, but the principle here can be applied and scaled to larger problems. There are only a few steps:
Open a connection to the database.
Loop until the end of the file:
Read a line of text from the flat file.
Parse the line of text into the columns of the table.
Execute a SQL statement to insert the record.
Here is the code of the example program: import java.io.*;
import java.sql.*;
import java.util.*;
public class TextToDatabaseTable {
private static final String DB = "contacts",
TABLE_NAME = "records",
HOST = "jdbc:mysql://db_lhost:3306/",
ACCOUNT = "account",
PASSWORD = "nevermind",
DRIVER = "org.gjt.mm.mysql.Driver",
FILENAME = "records.txt";
public static void main (String[] args) {
try {
// connect to db
Properties props = new Properties();
props.setProperty("user", ACCOUNT);
props.setProperty("password", PASSWORD);
Class.forName(DRIVER).newInstance();
Connection con = DriverManager.getConnection(
HOST + DB, props);
Statement stmt = con.createStatement();
// open text file
BufferedReader in = new BufferedReader(
new FileReader(FILENAME));
// read and parse a line
String line = in.readLine();
while(line != null) {
StringTokenizer tk = new StringTokenizer(line);
String first = tk.nextToken(),
last = tk.nextToken(),
email = tk.nextToken(),
phone = tk.nextToken();
// execute SQL insert statement
String query = "INSERT INTO " + TABLE_NAME;
query += " VALUES(" + quote(first) + ", ";
query += quote(last) + ", ";
query += quote(email) + ", ";
query += quote(phone) + ");";
stmt.executeQuery(query);
// prepare to process next line
line = in.readLine();
}
in.close();
}
catch( Exception e) {
e.printStackTrace();
}
}
// protect data with quotes
private static String quote(String include) {
return("\"" + include + "\"");
}
}
Processing a result set
Perhaps even more often than inserting data, you will want to retrieve existing information from your database and use it in your Java program. The usual way to implement this is with another type of SQL query, which selects a set of rows and columns from your database and appears very much like a table. The rows and columns of your result set will be a subset of the tables you queried, where certain fields match your parameters. For example: SELECT title FROM songs WHERE artist="Def Leppard";
This query returns:

title
Hysteria


The boxed portion above is a sample result set from a particular database program. In a Java program, this SQL statement can be executed in the same way as in the insert example, but additionally, we must capture the results in a ResultSet object. Statement stmt = con.createStatement();
String query = "SELECT FROM junk;"; // define query
ResultSet answers = stmt.executeQuery(query);
The JDBC version of a query result set has a cursor that initially points to the row just before the first row. To advance the cursor, use the next() method. If you know the names of the columns from your result set, you can refer to them by name. You can also refer to the columns by number, starting with 1. Usually you will want to get access all of the rows of your result set, using a loop as in the following code segment: while(answers.next()) {
String name = answers.getString("name");
int number = answers.getInt("number");
// do something interesting
}
All database tables have meta data that describe the names and data types of each column; result sets are the same way. You can use the ResultSetMetaData class to get the column count and the names of the columns, like so:
ResultSetMetaData meta = answers.getMetaData();
String[] colNames = new String[meta.getColumnCount()];
for (int col = 0; col < colNames.length; col++)
colNames[col] = meta.getColumnName(col + 1);
Example: Printing a database table
We choose to write a simple software tool to show the rows and columns of a database table.
In this case, we are going to query a database table for all its records, and display the result set to the command line. We could also have created a graphical front end made of Java Swing components.
Notice that we do not know anything except the URL and authentication information to the database table we are going to display. Everything else is determined from the ResultSet and its meta data.
Comments in the code explain the actions of the program. Here is the code of the example program: import java.sql.*;
import java.util.*;

public class DatabaseTableViewer {
private static final String DB = "contacts",
TABLE_NAME = "records",
HOST = "jdbc:mysql://db_host:3306/",
ACCOUNT = "account",
PASSWORD = "nevermind",
DRIVER = "org.gjt.mm.mysql.Driver";

public static void main (String[] args) {
try {
// authentication properties
Properties props = new Properties();
props.setProperty("user", ACCOUNT);
props.setProperty("password", PASSWORD);

// load driver and prepare to access
Class.forName(DRIVER).newInstance();
Connection con = DriverManager.getConnection(
HOST + DB, props);
Statement stmt = con.createStatement();

// execute select query
String query = "SELECT * FROM " + TABLE_NAME + ";";
ResultSet table = stmt.executeQuery(query);

// determine properties of table
ResultSetMetaData meta = table.getMetaData();
String[] colNames = new String[meta.getColumnCount()];
Vector[] cells = new Vector[colNames.length];
for( int col = 0; col < colNames.length; col++) {
colNames[col] = meta.getColumnName(col + 1);
cells[col] = new Vector();
}
// hold data from result set
while(table.next()) {
for(int col = 0; col < colNames.length; col++) {
Object cell = table.getObject(colNames[col]);
cells[col].add(cell);
}
}

// print column headings
for(int col = 0; col < colNames.length; col++)
System.out.print(colNames[col].toUpperCase() + "\t");
System.out.println();
// print data row-wise
while(!cells[0].isEmpty()) {
for(int col = 0; col < colNames.length; col++)
System.out.print(cells[col].remove(0).toString()
+ "\t");
System.out.println();
}
}
// exit more gently
catch(Exception e) {
e.printStackTrace();
}
}
}
Conclusions
In this article, you saw a quick introduction to manipulating databases with JDBC. More advanced features of JDBC require a greater knowledge of databases. See the references for more articles about JDBC and its applications [4]. As a Java programmer, JDBC is a good tool to have in your arsenal.
I encourage you to copy the code in this article to your own computer. With this article and documentation for another JDBC driver, you are on your way to creating data source-driven Java programs. Experiment with this code, and adapt it to connect to data sources available to you.

100 Interview Questions

100 Java Technical Questions to Software Companies


1.what is polymorphism with example ? types of polymorphism?

2.what is final method & final variable with example?

3.How to deploy your struts application in JBOSS?

4.what exactly happens when we execute "Class.forname("Driver class name");"?Explain in detail

5.What are 5 common problems in the software development process?

6.What are the design patterns and How can they make life easier for software development ?

7.Design the Factory pattern and What is its application ?

8.What is impedance mismatch and How to solve the problem?

9.How can we design/implement singleton object

10.what is mean by overriding in which situation we will use?

11.How to create an instance of a class without using "new" operator?

12.How can we serialize a jsp page.

13.What are the benefits obtained by using the Client Server oriented TP Monitors Client Server applications?

14.What are the three types of SQL database server architecture?

15.what is servlet engineer?

16.what is the difference b/w design pattern and architecture?

17.In the HashMap, we know the values but we dont know the key, then how can we get the key from HashMap ?

18.What is the use of a form in html page? Is there any way to submit the page without using the form.

19.what is the difference between abstract class and Interface?where we can use it in realtime projects?

20.which class to use when concatenating strings in a loop.

21.explain System.out.println?

22.what is the difference between equals method and ==?

23.Iterator in the HashMap is fail-safe means ?

24.how to deploy apache tomcat server to weblogic server in java?

25.what is difference between method overloading & method overridding with example?

26.what is difference between perfom() & excute() ?

27.write a progam hashmap & hashtable?

28.Can java provide security ?

29.How to implement or use the singleton class in java?

30.What is the singleton class in java?

31.What is JIT ?

32.Is it possible to create Userdefined Unchecked Exception also? If Yes, give an example?

33.What is the need of "creating and throwing an UserdefinedException" when the "Exception" class is already available?

34.What is the difference between throw and throws? What is the similarity between try and throw?

35.Why operator overloading is not in Java?

36.Is Struts Action class Thread Safe?

37.what is webservices?

38.why java does not support multiple inheritance?

39.we cant Override Jsp Service method?Why?

40.What is the difference between sendRedirect() and forward()?

41.what s the difference b/w EJB 2.0 and EJB 3.0 technically?

42.what is ForwardAction and IncludeAction in struts?
43.Different types of threads?

44.what is features of jdk 1.5?

45.what is java bean?where can we use it?

46.what is jndi?

47.Diff between C++ and java?

48.what is an anonymous class?

49.what is the difference between pagecontext and servletcontext?

50.What is data abstraction? Elaborate with example?

51.Is ResultSet class?

52.whats the diff between jsp and servlets?

53.Differences between UNIQUE and DISTINCT in select statements?

54.Which is not Object in Java?

55.which method is used to know the status of the Thread?

56.what is data access layer?

57.Which Design Patterns you know?

58.what is MVC Pattern?

59.What is the difference between C++ & Java?

60.how session will be expired?

61.what is overloading in java?

62.What is serializable interface?

63.What is CardLayout?

64.How can we create object to a class in a jsp file?

65.which situation you use static include and dynamic include in jsp?

66.Difference between overloading and Overriding.

67.What is the exact difference in between Unicast and Multicast object ?

68.Which Math method is used to calculate the absolute value of a number?

69.What is meant by throwing an Exception?
.Write a program to know whether string is palindrome or not?

70 A C program is given and asked what will be output.............

71.A Recursive function is given asked what will be output how and why?

72.write a prg / function to remove the duplicate from a sorted array. (8 m)

5.write a prg to genrate fibonacci series upto 100 recursively. (7 m)

73.predict the output of the following:
char c[]={ " enter" , "first" , "print" , "new" }.;
char **cp[]={c+3, c+2, c+1, c};
char ***cpp[]=cp;
printf("%s", ++*cp);
printf("%s",--*++cp);

74.A program given and asked what are variables value1 and value2 stores?(ie, in that program they store GCD and LCM)

75.Write a program to sort linked list.

In a table their 20 records.I had update 6 records???How can see and retrieve particular 6 records


76.class A { class B { psvm(String args[]) { } } } if the prg saved in A.java whats the o/p?
78.the control commands in the report program are
atfirst,atnew,atlast,atend of and what is the difference
between them
79.Difference between abstract class and interface
80.what's diff between struts 1.1 & 1.2?
81.can we have virtual functions in java?
82.what is Assertion?
83.Can we declare an anonymous class as both extending a class and implementing an interface?
84.What is hard code & soft code?
85.what is the difference between ArrayList and Vector?
86.How do you set security in applets?
87.what is an object and how do you allocate memory to it?
88.what is meant by string pooling?
89.Why Java is not purely object oriented?
90.What are other modifiers?
91.Can try statements be nested?
92.Can an exception be rethrown?
93.Name the class that used to read objects directly from a stream?
94.What Method and class used for Connection pooling ?
95.What are integer overflows and underflows and how to handle them?
96.How to eliminate duplicates from an array?
97.For which statements we use a label?
98.What is 3-tier model?
99.Difference between Application and Applet ?
100.Is there is any error if you have multiple main methods in the same class?

Java Interview Questions

Java Interview Questions Frequently Asked Basic Questions


Q:
What is the difference between an Interface and an Abstract class?
A:
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods..

Q:
What is the purpose of garbage collection in Java, and when is it used?
A:
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Q:
Describe synchronization in respect to multithreading.
A:
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

Q:
Explain different way of using thread?
A:
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

Q:
What are pass by reference and passby value?
A:
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

Q:
What is HashMap and Map?
A:
Map is Interface and Hashmap is class that implements that.

Q:
Difference between HashMap and HashTable?
A:
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

Q:
Difference between Vector and ArrayList?
A:
Vector is synchronized whereas arraylist is not.

Q:
Difference between Swing and Awt?
A:
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

Q:
What is the difference between a constructor and a method?
A:
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q:
What is an Iterator?
A:
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

Q:
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A:
public : Public class is visible in other packages, field is visible everywhere (class must be public too)private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.

Q:
What is an abstract class?
A:
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

Q:
What is static in java?
A:
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

Q:
What is final?
A:
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

Towers of Honii Program

class HanoiTower
{
static int nDisks = 3;
public static void main(String[] args) { hanoiTower(nDisks, 'A', 'B', 'C');
}
private static void hanoiTower(int topN, char src, char inter, char dest) { if(topN==1)
{
System.out.println("Disk 1 from " + src + " to " + dest);
}
else
{
hanoiTower(topN - 1, src, dest, inter);
System.out.println("Disk " + topN + " from " + src + " to " + dest);
hanoiTower(topN - 1, inter,src, dest);
}
}
}