Thursday, April 30, 2009

Using JTextField and JTextArea

TextFields are used to take input from user also it can be used to display results.
The various constructors and methods are defined in the previous JTextField tutorials.

Values from a TextField is extracted using String getText() and set using void setText(String txt).
The user can select a portion from the JTextField and JTextArea using String getSelectedText() and void select(int start_index,int end_index)
String getSelectedText() retrurns the String portion selected by the user from the textfield.
You can also enable or disable the TextField that is if you want TextField to be editable the use the methos void setEditable(boolean value) to true else set false.If you want to get value of editable TextField use boolean isEditable().

Sometimes you wish to set a password field in which the entered character must not be shown.It has to be replaced by some other sign or value.To set a password field you must use void setEchoChar(Char ch) character you specified in 'ch' will be shown when some charater is typed.
If you want to get the Charcter specified the use char getEchoChar().
Example :-
getting selected value from a text field and displaying it to other and use of Password field.

// textfield.java

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

public class textfield extends JFrame implements ActionListener
{
JFrame frame;
JPanel panel;
JTextField txtname,txtdisplay;
TextField txtpass;
JButton button;
public textfield()
{
frame=new JFrame("Text Field usage demo");
panel=new JPanel();
txtname=new JTextField(25);
txtpass=new TextField(25);
txtpass.setEchoChar('#');
txtdisplay =new JTextField(25);
JButton button=new JButton("Display selected");
button.addActionListener(this);
panel.setLayout(new GridLayout(3,2));
panel.add(new JLabel("Name :"));
panel.add(txtname);
panel.add(new JLabel("Password :"));
panel.add(txtpass);
panel.add(txtdisplay);
panel.add(button);
frame.getContentPane().add(panel);
frame.show();
frame.pack();

}

public void actionPerformed(ActionEvent ae)
{

txtdisplay.setText("Name :"+txtname.getSelectedText()+" Pass :"+txtpass.getText());

}
public static void main(String a[])
{
new textfield();
}
}

Example:-
getting selected value from a text area and displaying selected in textfield.

// textarea.java

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

public class textarea extends JFrame implements ActionListener
{
JFrame frame;
JPanel panel;
JTextField txtname,txtdisplay;
TextField txtpass;
JTextArea area;
JButton button;
public textarea()
{
frame=new JFrame("Text Area usage demo");
panel=new JPanel();
txtdisplay =new JTextField(25);
area = new JTextArea("vaibhav pandey has made this programme",5,5);
JButton button=new JButton("Display selected");
button.addActionListener(this);
panel.add(area);
panel.add(txtdisplay);
panel.add(button);

frame.getContentPane().add(panel);
frame.show();
frame.pack();

}

public void actionPerformed(ActionEvent ae)
{
txtdisplay.setText("Selected String :"+area.getSelectedText());
}
public static void main(String a[])
{
new textarea();
}
}.

Read more...

Wednesday, April 29, 2009

5 Best Mobile Java Games

Below is the list of 5 best selling Java games for mobile phones.If you are a game lover you are surely going to love them.

1.Darkest Fear 3: Nightmare is the final part of Rovio Mobile’s award winning Darkest Fear horror trilogy. The game offers a ultimate visual atmosphere and completely new lightning effects like never seen on mobile. Ingenious puzzles, two controllable characters, fifteen different endings and Helen’s new monster abilities take mobile gaming to a advanced level. The painful history of Grim Oak is about to be revealed. But can you confront your worst nightmare?
Supported on:-

  • Alcatel: One Touch 735 One Touch 735i
  • LG: C1100 C3300 C3310 C3400 F2250 F2300 L1100 L3100
  • Motorola: C380 C385 C450 C550 C650 C975 C980 E1060 E1120 E378i E380 E398 E550 E770 T720 V1050 V176 V180 V220 V230 V235 V3 V303 V360 V400 V500 V525 V535 V545 V547 V555 V557 V600 V620 V635 V80 V975 V980
  • Nokia: 2650 3100 3105 3108 3120 3125 3152 3155 3155i 3200 3220 3300 3510i 3520 3560 3585i 3586 3586i 3587 3587i 3595 3650 3660 5100 5140 6010 6012 6015 6020 6021 6030 6060 6100 6101 6108 6152 6155 6155i 6170 6220 6230 6230i 6260 6270 6280 6560 6600 6610 6610i 6620 6630 6670 6681 6682 6800 6810 6820 6822 7200 7210 7250 / 7250i 7360 7370 7610 8910i N-Gage N-Gage QD N70 N71 N92
  • Panasonic: X400
  • Samsung: D410 D500 D500E D508 D600 D600E D800 E100 E310 E600 E700 E720 E730 E800 E810 X105 X120 Z105 Z107
  • Sharp: GX-10 GX-20
  • Siemens: C55 C65 CX65 M65 S55 S65 SL55 SL65
  • Sony-Ericsson: D750 J300 K300 K600 K700 S600 S710 T610 T616 T630 V800i W550 W600 Z500i Z520i Z600



2.World Poker Tour SP2:-
Supported on:-

  • Alcatel: One Touch 735 One Touch 735i
  • LG: C1100 C3300 C3310 C3400 F2250 F2300 L1100 L3100
  • Motorola: C380 C385 C450 C550 C650 C975 C980 E1060 E1120 E378i E380 E398 E550 E770 T720 V1050 V176 V180 V220 V230 V235 V3 V303 V360 V400 V500 V525 V535 V545 V547 V555 V557 V600 V620 V635 V80 V975 V980
  • Nokia: 2650 3100 3105 3108 3120 3125 3152 3155 3155i 3200 3220 3300 3510i 3520 3560 3585i 3586 3586i 3587 3587i 3595 3650 3660 5100 5140 6010 6012 6015 6020 6021 6030 6060 6100 6101 6108 6152 6155 6155i 6170 6220 6230 6230i 6260 6270 6280 6560 6600 6610 6610i 6620 6630 6670 6681 6682 6800 6810 6820 6822 7200 7210 7250 / 7250i 7360 7370 7610 8910i N-Gage N-Gage QD N70 N71 N92
  • Panasonic: X400
  • Samsung: D410 D500 D500E D508 D600 D600E D800 E100 E310 E600 E700 E720 E730 E800 E810 X105 X120 Z105 Z107
  • Sharp: GX-10 GX-20
  • Siemens: C55 C65 CX65 M65 S55 S65 SL55 SL65
  • Sony-Ericsson: D750 J300 K300 K600 K700 S600 S710 T610 T616 T630 V800i W550 W600 Z500i Z520i Z600
3.Sudoku:-The Universally popular game you can it anywhere on the go,whether in the bus or in your living room.Just choose suitable difficulty level and you are game.
Supported on:-

  • Alcatel: One Touch 735 One Touch 735i
  • LG: C1100 C3300 C3310 C3400 F2250 F2300 L1100 L3100
  • Motorola: C380 C385 C450 C550 C650 C975 C980 E1060 E1120 E378i E380 E398 E550 E770 T720 V1050 V176 V180 V220 V230 V235 V3 V303 V360 V400 V500 V525 V535 V545 V547 V555 V557 V600 V620 V635 V80 V975 V980
  • Nokia: 2650 3100 3105 3108 3120 3125 3152 3155 3155i 3200 3220 3300 3510i 3520 3560 3585i 3586 3586i 3587 3587i 3595 3650 3660 5100 5140 6010 6012 6015 6020 6021 6030 6060 6100 6101 6108 6152 6155 6155i 6170 6220 6230 6230i 6260 6270 6280 6560 6600 6610 6610i 6620 6630 6670 6681 6682 6800 6810 6820 6822 7200 7210 7250 / 7250i 7360 7370 7610 8910i N-Gage N-Gage QD N70 N71 N92
  • Panasonic: X400
  • Samsung: D410 D500 D500E D508 D600 D600E D800 E100 E310 E600 E700 E720 E730 E800 E810 X105 X120 Z105 Z107
  • Sharp: GX-10 GX-20
  • Siemens: C55 C65 CX65 M65 S55 S65 SL55 SL65
  • Sony-Ericsson: D750 J300 K300 K600 K700 S600 S710 T610 T616 T630 V800i W550 W600 Z500i Z520i Z600

4.Smile Lines Winter Edition:-Winter Smilines is not easier but best pastime. In this arcade logic game you should with all your sharpness gather together all men who have a tedious time in solitude in merry companies . Just start it and you 'll be inveigle in the vortex of smiles, excitement and riddle-problems which get complicated constantly.
Supported on:-

  • Alcatel: One Touch 735 One Touch 735i
  • LG: C1100 C3300 C3310 C3400 F2250 F2300 L1100 L3100
  • Motorola: C380 C385 C450 C550 C650 C975 C980 E1060 E1120 E378i E380 E398 E550 E770 T720 V1050 V176 V180 V220 V230 V235 V3 V303 V360 V400 V500 V525 V535 V545 V547 V555 V557 V600 V620 V635 V80 V975 V980
  • Nokia: 2650 3100 3105 3108 3120 3125 3152 3155 3155i 3200 3220 3300 3510i 3520 3560 3585i 3586 3586i 3587 3587i 3595 3650 3660 5100 5140 6010 6012 6015 6020 6021 6030 6060 6100 6101 6108 6152 6155 6155i 6170 6220 6230 6230i 6260 6270 6280 6560 6600 6610 6610i 6620 6630 6670 6681 6682 6800 6810 6820 6822 7200 7210 7250 / 7250i 7360 7370 7610 8910i N-Gage N-Gage QD N70 N71 N92
  • Panasonic: X400
  • Samsung: D410 D500 D500E D508 D600 D600E D800 E100 E310 E600 E700 E720 E730 E800 E810 X105 X120 Z105 Z107
  • Sharp: GX-10 GX-20
  • Siemens: C55 C65 CX65 M65 S55 S65 SL55 SL65
  • Sony-Ericsson: D750 J300 K300 K600 K700 S600 S710 T610 T616 T630 V800i W550 W600 Z500i Z520i Z600
5.Patron Angel:-You are a patron angel protecting Sam on his journey. Keep both him and yourself alive. Red bullets gives damage to Lucia. Yellow bullets will give damage to Sam. Collecting them with Lucia rises the bless level, which makes weapons better and Lucia faster. Weapon shoots automatically when enemy is at fire range.
Supported on:-

  • Alcatel: One Touch 735 One Touch 735i
  • LG: C1100 C3300 C3310 C3400 F2250 F2300 L1100 L3100
  • Motorola: C380 C385 C450 C550 C650 C975 C980 E1060 E1120 E378i E380 E398 E550 E770 T720 V1050 V176 V180 V220 V230 V235 V3 V303 V360 V400 V500 V525 V535 V545 V547 V555 V557 V600 V620 V635 V80 V975 V980
  • Nokia: 2650 3100 3105 3108 3120 3125 3152 3155 3155i 3200 3220 3300 3510i 3520 3560 3585i 3586 3586i 3587 3587i 3595 3650 3660 5100 5140 6010 6012 6015 6020 6021 6030 6060 6100 6101 6108 6152 6155 6155i 6170 6220 6230 6230i 6260 6270 6280 6560 6600 6610 6610i 6620 6630 6670 6681 6682 6800 6810 6820 6822 7200 7210 7250 / 7250i 7360 7370 7610 8910i N-Gage N-Gage QD N70 N71 N92
  • Panasonic: X400
  • Samsung: D410 D500 D500E D508 D600 D600E D800 E100 E310 E600 E700 E720 E730 E800 E810 X105 X120 Z105 Z107
  • Sharp: GX-10 GX-20
  • Siemens: C55 C65 CX65 M65 S55 S65 SL55 SL65
  • Sony-Ericsson: D750 J300 K300 K600 K700 S600 S710 T610 T616 T630 V800i W550 W600 Z500i Z520i Z600

Read more...

Monday, April 27, 2009

Oracle Sun Deal and Microsoft,IBM

There will be some short and long term effects of the blockbuster $7.4 billion deal between Oracle and Sun MicroSystems on the whole IT industry and is set to affect business of top companies around the globe.As said by the CEO of Oracle Larry Ellison they have mainly acquired Sun for OpenSolaris Operating system and Java(not much concerned for MySQL).The effects of this deal on Microsoft may be either leave them smiling or the competition will get even tougher.Oracle Sun deal if happened may leave Microsoft SqlServer in a very difficult place if Oracle allowed OpenSource MySQL to remain OpenSource(after bearing some losses) and allowed MySQL to upgrade to its high end products.This will lead them to earn through MySQL .

Let's take a look what the Oracle president Oracle President Charles Phillips has said about the deal :-
"Oracle plans to engineer and deliver an integrated system—applications to disk—where all the pieces fit and work together so customers do not have to do it themselves. ... Oracle's ownership of two key Sun software assets, Java and Solaris, is expected to provide our customers with significant benefit. Java is one of the computer industry's best known brands and most widely deployed technologies. Oracle Fusion Middleware is built on top of Sun's Java language and software. Oracle can now ensure continued innovation and investment in Java technology for the benefit of customers and the Java community. The Sun Solaris operating system is the leading platform for the Oracle database. With the acquisition of Sun, Oracle can optimize the Oracle database for some of the unique, high-end features of Solaris. Oracle is as committed as ever to Linux and other open platforms, and will continue to support and enhance our strong industry partnerships."

From his speech it become clear that Oracle has much to do with Java and Solaris Operating System.Remember he did not mentioned anything about MySQL he said Oracle can optimize the Oracle database after acquisition of Sun MicroSystem.What it means I don't want to guess but still there is something inside.If Oracle curtails the OpenSource MySQL from the market then Microsoft will definitely get a sigh of relief and surely it will raise their market in Web World,because MySQL is not proprietary and is free, secondly it provides high end solutions for small websites.The Hardware market of Microsoft is very very small so this deal will never going to harm them but for IBM this is a danger alarm.See the other side that Oracle and Google are friends from a long time this deal will even strengthen their relationship,which means the foe of Microsoft, Google will enjoy on this deal .

After Finishing the deal Oracle will be able to supply compete System Solutions under one roof like from chips, servers, storage, desktops, thin clients, and more including Operating Systems,programming language and whats more an Office Suite OpenOffice,Previously which was only offered by IBM .It will surely hurt the business of IBM .Some guys say that IBM must buy SAP in order to remain competent with Oracle/Sun but the process is not too easy it needs days of analysis and speculations ,IBM will be doing their homework for improving their markets and be on top of their business.Their are news coming out that Oracle is not much interested in the Hardware business of Sun and may sell it to Fujitsu.The market share of Sun in Servers is mere 4% and also it builds servers on Sparc technology which are called outdated by many.Since Oracle does not make Sparc technology servers so this decision is right,and why not make some money from it to strengthen their server business.Story not ends here many Hardware giants like hp,Dell also looking forward for this deal and are busy finding out the consequences of Oracle Sun deal on their business.

Read more...

Sunday, April 26, 2009

Java Practice Questions

***********************JAVA QUESTIONS*****************************

TOTAL QUESTIONS:-22

1. Why JAVA is called platform independent language?

2. What is JVM?

3. Give an example of Constructor Overloading in Java?

4. What is method overriding?

5. Is the following code an example of method overloading?

class a{
int b(int c,int d)
{
return 1;
}
double(int c,int d)
{
return 1;
}
}
6. What will be the output of following code fragment:-

class abc
{
abc(int a,int b)
{
System.out.println(a+b);
}
abc(int a)
{
System.out.println(a);
}

public static void main(String a[])
{
new abc(2,3);
new abc(2);
new abc();
}
}

7.What is the difference between Type Conversion And Type Casting give examples.

8.How runtime polymorphism is achieved in java?

9.Will the following code compile?

class b
{
public static int main(String a[])
{
System.out.println("this is the test");
}
}

10.What will be the output of following code:-

switch(2)
{
case 1:System.out.println("1");
case 2:System.out.println("2");
case 3:System.out.println("3");
default:System.out.println("default");
}

11.What will be the output of following code:-

switch(2)
{
case 1:System.out.println("1");
case 2:System.out.println("2");
case 3:System.out.println("3");
continue;
default:System.out.println("default");
}

12.Explain 'new' operator.

13.How many basic data types java provides.

14.Why "goto" is not used oftenly in most programming languages?

15. Given:

class Clidders {
public final void flipper() { System.out.println("Clidder"); }
}
public class Clidlets extends Clidders {
public void flipper() {
System.out.println("Flip a Clidlet");
super.flipper();
}
public static void main(String [] args) {
new Clidlets().flipper();
}
}

What is the result?

A. Flip a Clidlet

B. Flip a Clidder

C. Flip a Clidder
Flip a Clidlet

D. Flip a Clidlet
Flip a Clidder

E. Compilation fails.

16.Given:

public abstract interface Frobnicate { public void twiddle(String s); }

Which is a correct class? (Choose all that apply.)

A. public abstract class Frob implements Frobnicate {
public abstract void twiddle(String s) { }
}

B. public abstract class Frob implements Frobnicate { }

C. public class Frob extends Frobnicate {
public void twiddle(Integer i) { }
}

D. public class Frob implements Frobnicate {
public void twiddle(Integer i) { }
}

E. public class Frob implements Frobnicate {
public void twiddle(String i) { }
public void twiddle(Integer s) { }
}

17.Given:

class Top {
public Top(String s) { System.out.print("B"); }
}

public class Bottom2 extends Top {

public Bottom2(String s) { System.out.print("D"); }

public static void main(String [] args) {
new Bottom2("C");
System.out.println(" ");
} }

What is the result?

A. BD

B. DB

C. BDC

D. DBC

E. Compilation fails.

18.Given:

class Clidder {
private final void flipper() { System.out.println("Clidder"); }
}

public class Clidlet extends Clidder {
public final void flipper() { System.out.println("Clidlet"); }
public static void main(String [] args) {
new Clidlet().flipper();
} }

What is the result?

A. Clidlet

B. Clidder

C. Clidder
Clidlet
D. Clidlet
Clidder

E. Compilation fails.

19.Given:

1. class Programmer {
2. Programmer debug() { return this; }
3. }

4. class Sssspublic class Foo {
void doStuff() { }
}

class Bar extends Foo {
void doStuff(String s) { }
}
The extends Programmer {
5. // insert code here
6. }

Which, inserted at line 5, will compile? (Choose all that apply.)

A. Programmer debug() { return this; }

B. SCJP debug() { return this; }

C. Object debug() { return this; }

D. int debug() { return 1; }

E. int debug(int x) { return 1; }

F. Object debug(int x) { return this; }

20.Given:

class Uber {
static int y = 2;
Uber(int x) { this(); y = y * 2; }
Uber() { y++; }
}

class Minor extends Uber {
Minor() { super(y); y = y + 3; }
public static void main(String [] args) {
new Minor();
System.out.println(y);
} }

What is the result?

A. 6

B. 7

C. 8

D. 9

E. Compilation fails.

F. An exception is thrown.

21.Given:

1. class Dog { }

2. class Beagle extends Dog { }
3.
4. class Kennel {
5. public static void main(String [] arfs) {
6. Beagle b1 = new Beagle();
7. Dog dog1 = new Dog();
8. Dog dog2 = b1;
9. // insert code here
10. }
11. }
Which, inserted at line 9, will compile? (Choose all that apply.)


A. Beagle b2 = (Beagle) dog1;

B. Beagle b3 = (Beagle) dog2;

C. Beagle b4 = dog2;

D. None of the above statements will compile

22.It is the example of overloading or overriding

public class Foo {
void doStuff() { }
}
class Bar extends Foo {
void doStuff(String s) { }
}

These questions are only for practice.If you want to know the answers e-mail me at javatute@gmail.com with your list of answers.

Some of these Questions are taken from the book of SCJP by Catherine Sierra and Bert Bates.

Read more...

Saturday, April 25, 2009

Oracle Sun Deal Raises Questions among Professional

Oracle Sun deal has raised few questions in the minds of the IT professionals as well as business gurus.It will be interesting to see how Oracle handles these after the deal is finalised.The main point becomes pretty unclear that whether it make Oracle's presence stronger in the market or it will sink the business of Sun.The main Questions are Summarised below:-

# What will happen to the OPEN SOURCE ??

The most important of all questions(leaving business one's), if you little bit of Open Source software.Open Source technology might see wrong effects if this deal happens.Open Source software are those that doesn’t have the same license and copyright limits as most commercial software.A good example of Open Source software is Mozilla FireFox which is a famous web browser.Sun has most biggest and popular Open Source software like widely used Java technology and MySQL Database server,Largest open source office suite OpenOffice and operating system OpenSolaris.Since Oracle is a Profit-profit organisation this technology may be under threat.But one thing Oracle can do that to continue with these technologies and put their technical expertise into it to ensure they must not vanish and remain profitable too.What Oracle will do with Open Source is to remain major concern of many tech gurus,as everyone is closely following the Oracle Sun deal.


# Oracle own Java technology ??

Currently Java is the most widely used programming language around the world which runs on almost 800 millions PC's and 2.10 billion cellular phones.When the owner of Oracle CEO Larry Ellison made announcement about the deal he said "Java is the single most important software asset we have ever acquired".This deal help Oracle and its acquired Companies to release the new version of its products to its customers and may increase the price of its products to ensure the profitability of this deal.Most importantly the rivals of Oracle The IBM uses Java as its programming language for its products.After the deal if Oracle own Java it may put a firm restriction on the use of Java Technology by its rival which will boost their market .Owning Java gives Oracle more components of the software ,that companies use to create applications, including the programming language, Java middleware, and Oracle's market-leading database. The combination of Oracle's database with Java as middleware give tough competition to to Microsoft.

Many more Questions are raised like:
1.what Oracle will do with Sun's Hardware business ??
2.How many peoples in Sun will lose their jobs ??
3.Will Oracle save Sun's existence ??
4.Will MySQL stay as compelling ??

The world is watching this deal very closely as this deal may transform the industry and its norms.Keep a close eye its getting interesting and serious as well.

Read more...

BitWise Right Shift Operator

Bitwise Right Shift Operator which is denoted by >> ,shifts all bits in a value to the right of specified number of times.

Syntax:-

value >> number

where value is,whose bits are to be shifted by number of times specified by number.

for example:- Shifting 32 to right by two positions

24 >> 2 equal to 6
27 >> 2 equal to 6

Explanation:-
24 in binary form is given by 00011000 which after shifting twice returns 00000110 which is equal to 6.Similarly 27 after shifting twice also result in 6 due to loss of lower order bits.

NOTE:-Each time we shift a value we are dividing the value by 2 and leave any remainder.

In this signed right shift operation the sign of value remains preserved.When we are shifting right the higher order bit is shifted and it is replaced by the previous content of highest order bit.This is called as sign extension and it preserves the sign of the value

For Example:-

- 8 >>.1 = - 4 as following happens

11111000 >> 1

11111100 and it is equal to - 4

IMPORTANT:-Value of -1 remains same whether it is shifted or not because its binary value is 11111111.If you will shift this value you will get the same result.

Go to:-

Home
Assignment Operators
Arithmetic Operators
Logical operators
Relational Operators
Conditional Operators
Bitwise Operator Intro
Bitwise Logical operator
Bitwise Left shift Operator

Sponsored Links :-

Get Your SCJP preparation Kit free!!!!!!!
Get Your SCWCD preparation Kit free!!!
Are you Intelligent check here

Read more...

Tuesday, April 21, 2009

Oracle to Buy Sun MicroSystems for $7.4 billion

The renowned Information Technology company Sun who is mainly known for company who invented most used Java Technology and also known for their Servers is going to be sold out in near future according to sources.Oracle is going to buy SunMicroSystems for $7.40 billion after IBM pulled out after bidding $7.00 billion.The Oracle corp is agreed to pay $7.4 billion in a complete cash deal.This came as a shock after a week of IBM pullout.IBM valued SunMicrosystems for $7 billion,But Sun was not agree on this they demanded to raise the price value of their shares to $58 which was strictly denied by the governing body of IBM.This deal is surely going to hurt IBM since Oracle is giving a very tough market competition to IBM.After buying Sun MicroSystems ,Oracle will get a niche in the market which is led by the biggest company HP.IBM were hoping that if they will buy Sun They will rule the market of Unix Servers but somehow they can't just wake up on the call.They must have thought about the call of Sun to raise the price a bit.As you can see Oracle came of nowhere to clinch the deal which will be great advantage to them over rival companies in the market of Java enabled Unix servers.Oracle's market is rising and they want to give it a fly.If this deal happens then no doubt Oracle will also be in line with HP and IBM for providing servers and with open source Java, that will be huge advantage to Oracle which is mainly known for its database related products.

Read more...

Monday, April 20, 2009

How to Use CheckBoxGroup

CheckboxGroup class is used to group togather the Checkboxes,from which only one can be selected at a time.
That is exactly one Checkbox in that goup will be "on" else remain "false".By clicking on Checkbox we may "on" or "off" the desired Checkbox.This control is mostly used in making selection ,where exactly one selection is needed form given choices.

more on Checkboxes Visit Checkbox Tutorial
Constructor:-

CheckboxGroup() ---> Creates a new instance of CheckboxGroup.
Important Methods:-

void getSelectedCheckbox() ----> Gets the current choice from this check box group.
void setSelectedCheckbox(Checkbox cb) ----> Turn "on" the specified CheckBox.
How to Use CheckboxGroup:-

Example:-

// test.java

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

public class test{
public static void main(String[] args){
JFrame frame = new JFrame("Check Box Frame");
CheckboxGroup cb=new CheckboxGroup();
Checkbox chkop1 = new Checkbox("option1",false,cb);
Checkbox chkop2 = new Checkbox("option2",false,cb);
Checkbox chkop3 = new Checkbox("option3",true,cb);
JPanel panel=new JPanel();
panel.add(chkop1);
panel.add(chkop2);
panel.add(chkop3);
frame.getContentPane().add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Read more...

Friday, April 17, 2009

do-while Loop

do-while looping construct

As we have seen in previous tutorial of while loop that if the controlling expression is false then the loop will not execute at all.However in some situations you may need that loop must at least execute once.do-while loop does just that .The do-while loop executes atleast once even if the controlling expression is false.The reason is that the controlling expression is placed at bottom of loop after body of loop.

Syntax:-

do
{
//Body of loop
}while(condition);

Thus,each iteration in do-while loop first executes the body then evaluates the conditional expression.If the boolean value is true then loop continues else terminates.

Example:-

int i=0;
do
{
System.out.println("Loop completes :"+(++i)+"times");
}while(i<5);

The output produced by above code snippet is:-

Loop completes :1times
Loop completes :2times
Loop completes :3times
Loop completes :4times
Loop completes :5times


NOTE:- The do-while loop is particularly useful in cases where menu selection is done.Where you need atleast once the loop to execute.Because in the end you wish to check whether user have entered a valid choice or not.This can be performed easily through do-while loop.

IMPORTANT:-Never forget to place a semicolon at the end of while in the do-while construct that is

do
{
}while(condition); //semicolon is must remember

Go to :-
Home
Control Statements
Operators

Read more...

Wednesday, April 15, 2009

How to create and use Check Boxes

CheckBox is a unique java control which lets user select one or more options.This control becomes handy where some sort of selection is to be made.I will explain here the CheckBoxes In Java Swings.Which are created using JCheckBox class.

Constructors:-There are five constructors of CheckBox

1.Checkbox() --> Creates a check box with an empty string for its label.

2.Checkbox(String label, boolean state) --> Creates a check box with the specified label and sets the specified state.

3.Checkbox(String label) --> Creates a check box with the specified label.

4.Checkbox(String label, boolean state, CheckboxGroup group) --> Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group.

5.Checkbox(String label, CheckboxGroup group, boolean state) --> Creates a check box with the specified label, in the specified check box group, and set to the specified state.

Example:-This simple swing example illustrates how checkboxes are added.

//test.java

import javax.swing.*;

public class test{
public static void main(String[] args){
JFrame frame = new JFrame("Check Box Frame");
JCheckBox chkop1 = new JCheckBox("option 1");
JCheckBox chkop2 = new JCheckBox("option 2");
JCheckBox chkop3 = new JCheckBox("option 3");
JPanel panel=new JPanel();
panel.add(chkop1);
panel.add(chkop2);
panel.add(chkop3);
frame.getContentPane().add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Selecting Checkboxes:-In this example the checkboxes are default selected using setSelected(boolean state) method of JCheckBox class.

//test1.java

import javax.swing.*;

public class test{
public static void main(String[] args){
JFrame frame = new JFrame("Check Box Frame");
JCheckBox chkop1 = new JCheckBox("option 1");
chkop1.setSelected(true);
JCheckBox chkop2 = new JCheckBox("option 2");
chkop2.setSelected(true);
JCheckBox chkop3 = new JCheckBox("option 3");
JPanel panel=new JPanel();
panel.add(chkop1);
panel.add(chkop2);
panel.add(chkop3);
frame.getContentPane().add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


Other useful methods:-

setLabel() :-Sets Label as provided string to this CheckBox.
getLabel() :-Returns Label of CheckBox.
addItemListener() :-Only ItemListeners can be added to CheckBox control for event handling purposes.

For More Detailed API for CheckBox Go to awt(CheckBox) API and swing(JCheckBox) API

Read more...

The While Loop

The while looping construct

The while loop is Java's most basic and fundamental looping statement.It continuously repeats the statement or some block of expression while its controlling expression is true.This controlling expression is of Boolean form that is it may either return true or false.The basic syntax is:-

while(Condition)
{
//statements or block of statements
}

As I said earlier the condition is a Boolean expression.The code inside loop will be executed as long as the condition is true.When condition becomes false the loop terminates and control returns to the very next line of code following the loop.

Consider following example:-

int i=0;
while(i < 5)
{
i++;
System.out.println("Loop completes :"+i+"times");

}

If you will run that code snippet you will get output something like following

Loop completes :1 times
Loop completes :2 times
Loop completes :3 times
Loop completes :4 times
Loop completes :5 times

Any Boolean expression can be placed in place of condition.
If you are executing only one statement the curly braces are unnecessary.

Explanation:-We initialized a variable i as 0.It is checked in the while as if it is less than 5 or not since it returns a Boolean value and at first it returns true thus code inside curly braces is executed until the value of i reach 5.When it will reach 5 then in next iteration the loop will terminate.

NOTE:-
1.Since Java evaluates the conditional expression at the very start so there is no chance that loop may execute once.We will see further how once loop is executed using do-while construct.

2.The body of a while loop can be empty.That is no statements inside loop body:
example:-
//this is an empty while loop
while(i++
In professionally written java code,programmers often code short loops without body,where most of work is done in controlling expression itself.So try to match it but at very basic level use it as suits you once you mastered it go for professional writing.

Read more...

College Days Over

It is not a great feeling to say that for me College days are now over.Yesterday I attended farewell party organised by our juniors.It was great, full of fun and enjoyment.I too with my friends enjoyed a lot.Every body can be seen roaming freely and freely snapping each other(coz cell phones and cameras are not allowed in my college ).The emotions were high since we are approaching end of days in college.The guys were handsome in trousers and shirts and girls were rocking in traditional Indian Saree.We hugged each other as it is for last time.Today when I came to college(nobody else came in my class)I just want to see more and more of my classroom. There was a feeling that some day I surely miss My college.My experience with college were not always good there was a mix feeling that yes I lost and I got many things and friends.I got my life here.I watched this world closely here.It let me know the peoples.It is not always a great feeling when you loose a place you are attached to but as time moves on you have to carry on.I am one of those lucky guys who got campus placements and will join my company in six months from now. I don't know what will happen there but one thing is sure ,the lesson of professionalism that I have learnt here will help me a lot. My exams are also approaching .I have completed my Final year project titled "Citizen Database using FingerPrint Authentication".I always want to give more and more what I have to everybody I will continue writing this blog whatever the conditions be.I want guys to learn the bestv of technologies and Java is one of the best.Keep tuned here and don't forget to check hot offers section.

Va
Gud Bye
Happy reading

Read more...

Declaring Constructor

Constructor Declaration

In Java, objects are constructed. Every time you make a new object, at least one
constructor is invoked. Every class has a constructor, although if you don't create
one explicitly, the compiler will build one for you. There are tons of rules concerning
constructors. For now, let's focus on the basic declaration rules. Here's a simple example:

class Boo {
protected Boo() { } // this is Boo's constructor
protected void Boo() { } // this is a badly named,
// but legal, it is a method!!!
}

The first thing to notice is that constructors look an awful lot like methods. A
key difference is that a constructor can't ever, ever, ever, have a return type.
Constructor declarations can however have all of the normal access modifiers, and
they can take arguments (including var-args), just like methods.
The other BIG RULE, to understand about constructors is that they must have the same name as
the class in which they are declared. Constructors can't be marked static (as they
are associated with object instantiation), they can't be marked final
or abstract (because they can't be overridden). Here are some legal and illegal
constructor declarations:

class Boo2 {

legal constructors
Boo2() { }
private Foo2(byte b) { }
Boo2(int x) { }
Boo2(int x, int... y) { }

illegal constructors
void Boo2() { } // it's a method, not a constructor
Boo() { } // not a method or a constructor
Boo2(short s); // looks like an abstract method
static Boo2(float f) { } // can't be static
final Boo2(long x) { } // can't be final
abstract Boo2(char c) { } // can't be abstract
Foo2(int... x, int t) { } // bad var-arg syntax
}


Go To
Home
Interface Declaration
Declaring Class Members
Variable Declaration

Read more...

Monday, April 13, 2009

DropDown Menu or Choice menu

DropDown Menu or The Choice class

A choice menu is a dropdown menu which upon clicking presents a list of menus(choices) from which user may choose one.That is when a user clicks on the choice control a list of option drops down from which a user can select only one choice.It enforces user to choose from the list of options provided.

Constructor:-

// Choice();
creating an object of Choice class
e.g. Choice choice=new Choice();

Adding Items:-

Items in the list of menu are added by using addItem(String Item) method.
e.g. choice.addItem("Option 1");




Example:-
//choice.java

import java.awt.*;

public class choice
{
public static void main(String a[])
{
Frame frm=new Frame("Choice menu demo");
Panel panel=new Panel();
Choice choice=new Choice();
frm.add(panel);
choice.addItem("Option 1");
choice.addItem("Option 2");
choice.addItem("Option 3");
choice.addItem("Option 4");
panel.add(new Label("This is DropDown MENU"));
panel.add(choice);
frm.show();
frm.pack();
frm.setBounds(100,100,250,200);
}
}

Useful Methods of Choice Class:-



Go to
Home
JLabel
JButton
JTextField
Setting Mnemonics and shortcut keys
Setting ToolTip Icon

Read more...

Saturday, April 11, 2009

Advertise With us

Now You can advertise on Java world at a very low price.As an advertiser you have to consider following:-

1.Only banner ads can be used for advertising.
2.The size suited are

125 x 125 small banner
100 x 100 tiny rectangle
240 x 60 half banner
480 x 60 full banner
720 x 90 top banner
120 x 600 skyscraper
160 x 600 skyscraper
300 x 250 medium rectangle
250 x 250 small rectangle

3.The cost for small banner,tiny rectangle,half banner is $5 per month.
4.The cost for full banner,medium rectangle is $8 per month.
5.The cost for both skyscrapers and medium rectangle is $10 per month.
6.The ads will be permanent that is no rotating ads.
7.Advertisers support provided round the clock.


Apart from this the advertisement can be placed at advertisers choice,If available.It is truly first come first serve basis.

For Advertising contact
javatute@gmail.com

Read more...

BitWise Left Shift Operators

The BitWise Left Shift Operators

The Left Shift:-The left shift Operator ,shifts all of the bits in a value to the left of a specified number of times.Its general form is:

value << number

Here, value specifies the number which is to be left shifted and number specifies the number of positions to left shift the value.
That is << moves all the bits of any value to the left by the number of bit positions specified by number.This means that whenever this shift operation is performed to int the 31st bit will be lost.Similarly For all integer types the highest order bit will be lost.

Lets take a look at following example:

int i;
byte a,b=64;

i = b << 2;
a= (byte)b << 2;

System.out.println(b);
System.out.println("value of i and a after shifting is:"+i+" "+a);

Th e output is as expected
64
value of i and a after shifting is 256 0

Lets see how it is done: here b is promoted to int for evaluation purpose,thus when we left shift value of b twice it will result in 256 that is (01000000) is converted to (100000000) which is equal to 256.But the value contained in a would be 0 because it is explicitly typecasted as byte thus it will lose its highest order bit and result in 0.If it would have shifted once then result would be 128.

This is main problem occurs with the smaller data types that is they lose most of values when typecasted.

Important:-Since each left shift has an effect of doubling the value by 2,thus often programmers use this fact as an effective alternative to multiplying by 2.But be careful in case of int if you shift a bit 1 into the highest order bit it will make the value negative.So be careful about the higher order shifting.

Read more...

Friday, April 10, 2009

Declaring Class Members

Declaring Class Members

Access Modifiers

A class can use just two of the four access control levels –
1. public
2. default

A method can have all four access control levels -
1. public
2. protected
3. default
4. private



Public Members
When a method or variable member is declared public, it means all other classes, regardless of the package they belong to, can access the member.That is the class is visible to every one.

There are three ways for accessing method
1. Invoking a method declared in the same class
2. Invoking a method using a reference of the class.
3. Invoking an inherited method

For example :

Class SportsBike //superclass
{
goFast(){}
}

Class Sports extends SportsBike //subclass
{
doWork(){
SportsBike sc=new SportsBike(); // Invoking a method using a reference of the class.
sc.goFast();
}
doMoreStuff(){
goFast(); // Invoking an inherited method
}
}

Look at the following source file:
package book;
import foo.*; // Import all classes in the cert package
class Goo {
public static void main(String[] args) {
Sludge o = new Sludge();
o.testIt();
}
}
Now look at the second file:
package foo;
public class Sludge {
public void testIt() { System.out.println("sludge"); }
}

As you can see, Goo and Sludge are in different packages. However, Goo can invoke the method in Sludge without problems because both the Sludge class and its testIt() method are marked public.

Remember For a subclass, if a member of its superclass is declared public, the subclass inherits that member regardless of whether both classes are in the same package:



Private Members
Members declared as private can't be accessed by code in any class other than the class in which the private member was declared. When a member of superclass is declared private, a subclass can't inherit it.

For example :

Class SportsBike //superclass
{
private goFast(){}
}

Class Sports extends SportsBike //subclass
{
doWork(){
SportsBike sc=new SportsBike(); // Invoking a private method using a reference of the class.
sc.goFast();
}
doMoreStuff(){
goFast(); // Invoking an inherited method
}
}

If you try to execute the above code, compiler will give error
%javac Sports.java
Sports.java:5: Undefined method: goFast()
sc.goFast();

Sports.java:8: Undefined method: goFast()
goFast();
2 errors


Protected and Default Members
The protected and default access control levels are almost identical, but with one critical difference. A default member may be accessed only if the class accessing the member belongs to the same package, whereas a protected member can be accessed (through inheritance) by a subclass even if the subclass is in a different package.

Protected Details
Let's take a look at a protected instance variable (remember, an instance variable is a member) of a superclass.

package ample;
public class Compute {
protected int x = 4; // protected access
}

The preceding code declares the variable x as protected. This makes the variable accessible to all other classes inside the sample package, as well as inheritable by any subclasses outside the package. Now let's create a subclass in a different package, and attempt to use the variable x (that the subclass inherits):

package hello; // Different package
import ample.Compute;
class Print extends Compute {
public void testIt() {
System.out.println("x is " + x); // No problem; Print
// inherits x
Compute c = new Compute (); // Can we access x using the
// c reference?
System.out.println("X in Compute is " + c.x); // Compiler error!
}
}

The preceding code .

%javac -d . hello/Print.java
other/Print.java:7: x has protected access in sample.Calculate
System.out.println("X in Compute is " + c.x);
^
1 error

Default Details
Let's start with the default behavior of a member in a superclass. We'll modify the Parent's member x to make it default.

package sample;
public class Calculate {
int x = 2; //if no access modifier, means default
// (package) access
}

Notice we didn't place an access modifier in front of the variable x. Remember that if you don't type an access modifier before a class or member declaration, the access control is default, which means package level.

Local Variables and Access Modifiers

We can never apply access modifiers to local variables. In fact, there is only one modifier that can ever be applied to local variables—final. If access modifiers are applied to local variables it will not compile. Variables defined in loops, methods without access modifiers are local variables whose scope ends with the termination of container block.

Non-access Member Modifiers

Final Methods

The final keyword prevents a method from being overridden in a subclass, and is often used to enforce the API functionality of a method. This can't-be-overridden restriction provides for
safety and security, but you should use it with great caution.

A typical final method declaration looks like this:
class SuperClass{
public final void showSample() {
System.out.println("One thing.");
}
}

It's legal to extend SuperClass, since the class isn't marked final, but we can't override the final method showSample(), as the following code attempts to do:

class SubClass extends SuperClass{
public void showSample() { // Try to override the final
// superclass method
System.out.println("Another thing.");
}
}

Attempting to compile the preceding code gives us something like this:

%javac FinalTest.java
FinalTest.java:5: The method void showSample() declared in class SubClass cannot override the final method of the same signature declared in class SuperClass.
Final methods cannot be overridden.
public void showSample() { }
1 error



Final Arguments
Method arguments are the variable declarations that appear in between the parentheses in a method declaration. A typical method declaration with multiple arguments looks like this:

public Record getRecord(int fileNumber, final int recordNumber) {}

In this example, the variable recordNumber is declared as final, which of course means it can't be modified within the method.

An abstract method is a method that's been declared (as abstract) but not implemented. In other words, the method contains no functional code.
Abstract method looks like this :
public abstract void showSample();

Notice that the abstract method ends with a semicolon instead of curly braces. It is illegal to have even a single abstract method in a class that is not explicitly declared abstract! Look at the following illegal class:

public class IllegalClass{
public abstract void doIt();
}

The preceding class will produce the following error if you try to compile it:

IllegalClass.java:1: class IllegalClass must be declared
abstract.
It does not define void doIt() from class IllegalClass.
public class IllegalClass{
1 error

Three different clues tell you it's not an abstract method:
1. The method is not marked abstract.
2. The method declaration includes curly braces, as opposed to ending in a semicolon. In other words, the method has a method body.
3. The method provides actual implementation code.
Any class that extends an abstract class must implement all abstract methods of the superclass, unless the subclass is also abstract. The rule is this:
The first concrete subclass of an abstract class must implement all abstract methods of the superclass.


Synchronized Methods
The synchronized keyword indicates that a method can be accessed by only one thread at a time.
A typical synchronized declaration looks like this:
public synchronized Record retrieveInfo(int id) { }

You should also know that the synchronized modifier can be matched with any of the four access control levels.

Native Methods
The native modifier indicates that a method is implemented in platform-dependent code, often in C.
The native is a modifier (thus a reserved keyword) and that native can be applied only to methods—not classes, not variables, just methods.
Note that a native method's body must be a semicolon (;) (like abstract methods), indicating that the implementation is omitted.

Strictfp Methods
strictfp forces floating points (and any floating-point operations) to adhere to the IEEE 754 standard. With strictfp, you can predict how your floating points will behave regardless of the underlying platform the JVM is running on. The downside is that if the underlying platform is capable of supporting greater precision, a strictfp method won't be able to take advantage of it.

You can apply this keyword either on a class or all individual methods of that class.

Read more...

if-else-if Control Statement

The if-else-if Control Statement

A common programming construct that is based on nested if's is if-else-if ladder construct.In it the if condition is followed by else if conditions which are executed in drop down fashion if first if is not executed then program flow takes it to nest else if condition and so on.

Syntax:-

if(condition)
statement;
else if(condition)
statement;
else if(condition)
statemet;
....

else
statement;

The if statement are executed from top to bottom.As soon as one if condition becomes true then respective statements are exceuted and rest of conditions are bypassed.If none of condition is true then final else statemenst are executed.This final else statement acts as default condition.If there is no else condition and no if condition is true then no action will occur.

Example:-

if(salary<1000)>1000)
System.out.println("Job Grade 3");
else if(salary<4000&&salary>2500)
System.out.println("Job Grade 2");
else
System.out.println("Job Grade 1");

Read more...

Wednesday, April 8, 2009

BitWise Logical Operators

Types of BitWise Logical Operators are explained as follows:-
The BitWise logical Operators are & , |, ~ and ^.The Biltwise Logical Operators are applied to each and every bit of each opernd.

1.The BitWise AND:-The BitWise AND operator produces value 1 if the value of both the operands is also 1.A 0 is produced in all other case.

For Example:-

applying AND Operation to 42,15

00101010
& 0001111
---------------------------
00001010
---------------------------
It is equal 10


2.The BitWise OR:-The BitWise OR Operator produces a 1 bit if either of operands bit value is 1.A 0 would be produced if both operands bits are 0 otherwise a 1 bit is produced.

For Example:-

Applying OR Operation to 42,15

00101010
| 00001111
---------------------------
00101111
--------------------------
It is equal to 47


3.The BitWise NOT:-The BitWise NOT inverts the value of bits of its operand remember there is only one operand.If value of bit is 1 then it is changed to 0 and vice versa.

For Example:- The Binary value of 42 is 00101010
and applying Bitwise NOT we get

~ (00101010) = 11010101
11010101 in decimal is equal to 213 that is (255-42)


4.The BitWise XOR:-The BitWise XOR produces a bit value of 1 when both values of operand bits are different.Produces 0 in all other cases.

For Example:-

Applying XOR to 42,15

=> 00101010
^ 00001111
-----------------------------
00100101
-----------------------------
It is equal to 37

Useful Links:-

Assignment Operators
Arithmetic Operators
Logical operators
Relational Operators
Conditional Operators
Bitwise Operator Intro
Bitwise Left shift Operator
Bitwise Right shift Operator

Sponsored Links :-

Get Your SCJP preparation Kit free!!!!!!!
Get Your SCWCD preparation Kit free!!!
Are you Intelligent check here

Read more...

Head First Java Book and Ebook Download

It has taken four years, but with Head First Java the introductory Java book category has finally come of age. This is an excellent book, far more capable than any of the scores of Java-for-novices books that have come before it. Kathy Sierra and Bert Bates deserve rich kudos--and big sales--for developing this book's new way of teaching the Java programming language, because any reader with even a little bit of discipline will come away with true understanding of how the language works. Perhaps best of all, this is no protracted "Hello, World" introductory guide. Readers get substantial exposure to object-oriented design and implementation, serialization, network programming, threads, and Remote Method Invocation (RMI).


Key to the authors' teaching style are carefully designed graphics. Rather than explain class inheritance (to cite one example) primarily with text, the authors use a series of tree diagrams that clarify the mechanism far more succinctly. The diagrams are carefully annotated with arrows and notes. Also characteristic of the unique teaching strategy is heavy reliance on exercises, in which the reader is asked to complete partial classes, write whole new code segments and do design work. Though there's little discussion of why the exercises' correct answers are what they are, it's clear that the practice work was carefully designed to reinforce the lesson at hand. If you've waited this long to give Java a try, this book is a great choice. --David Wall

Topics covered: The Java programming language for people with no Java experience, and even people with no programming experience at all. Key concepts read like a list of Java features: Object oriented design, variable type and scope, object properties and methods, inheritance and polymorphism, exceptions, graphical user interfaces (GUIs), network connectivity, Java archives (JAR files), and Remote Method Invocation (RMI). --This text refers to an out of print or unavailable edition of this title.

Review

"I can heartily recommend it ... It takes a lot of effort to produce a book this good and it's going to be difficult to sustain." - Computer Shopper, October 2003 "In general the book works well. I found it interesting in the way that it presented Java in a not overtly technical manner; the prose was readable and generally well structured. For example the coverage of object references I thought was well done remaining accurate while being clear to a non-expert reader." - James Robert, CVu, April 2004 --This text refers to an out of print or unavailable edition of this title.
Buy Here
Head First Java, 2nd Edition

Read more...

Back to Work

Guys after a week long break from my studies and blogging stuff I am back now.Most of you don't know that I am an Indian and there are so many traditions on every occasion.I was out because Of the Ring Ceremony of my sister.It took almost a week to prepare.Finally all traditions happend in a very delightful environment.I enjoyed it a lot but for me to remain away from my readers is very harsh and I wanted to get back as soon as possible.Because I love you all I appreciate all my readers across the globe.Without their support and appreciation I would not be able to do what I am doing right now.So thank you all for your paitence.Most of you don't know but I am graduating this year In computer sciences.My exams are approaching so in this month I may not be able to write as much but still I will manage something for you.So thank you guys Have a happy reading .

Read more...

Arrays

Arrays

Arrays are a way to store a list of items that have the same primitive data type, the same
class.Each item on the list goes into its own numbered slot so that you can easily
access the information.
Once Array is created of certain type then it can only used to store and retrieve the
value of specified type.
Java implements arrays differently than some other languages do—as objects treated like
other objects.
To create an array in Java, you must do the following:
1. Declare a variable to hold the array.
2. Create a new array object and assign it to the array variable.
3. Store information in that array.

The following statements are examples of array variable declarations:
String[] requests;
Point[] targets;
float[] donations;
String targets[];
Point targets[];

Creating Array Objects
After you declare the array variable, the next step is to create an array object and assign
it to that variable. To do this:
1.use the new operator.
2.Initialize the contents of the array directly.

Because arrays are objects in Java you can use new operator to create an instance like:

String[] ename=new String[10];

This statement creates array with 10 elements Starting with ename[0].
You can also create array of primitive data types as of int,Boolean,char etc.
At the beginning when no value is allocated to array elements by default they
contain null values.
You can directly create array as:

String[] name={"roma","milano","cristy"};
That is dirctly specify values within curly braces but remember values must match
the specified data type.

Retrieving values from Arrays

The values stored in arrays can be retrieved directly by specifying index number of element
such as:

//System.out.println(ename[0]);

or we can retrieve them using a loop such as

/* for(int i=o;iMultidimensional Arrays

A multidimensional array has more than one dimension unlike simple arrays .
A Multidimensional array can be stated as array of arrays

Basic Syntax for declaration
Two dimensional array
[][] = new [size][size];
if you want to crate n dimensional the the square brackets can be n.
Example:-

int[][] numbers=new numbers[10][10];
This will create an array named numbers with 10*10 matrix.


Read more...

Thursday, April 2, 2009

Interface Declaration

Declaring an Interface

When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it. This means an interface can contain only abstract methods. Interfaces can be implemented by any class, from any inheritance tree.

Remember:-abstract class can define both abstract and non-abstract methods, an interface can have only abstract methods

Interface has following rules :

1. All interface methods are implicitly public and abstract. In other words,
you do not need to actually type the public or abstract modifiers in the
method declaration, but the method is still always public and abstract.

2. All variables defined in an interface must be public, static, and final—
in other words, interfaces can declare only constants, not instance variables.

3. Interface methods must not be static.

4. Because interface methods are abstract, they cannot be marked final,
strictfp, or native. (More on these modifiers later.)

5. An interface can extend one or more other interfaces.

6. An interface cannot extend anything but another interface.

7. An interface cannot implement another interface or class.

8. An interface must be declared with the keyword interface.

9. Interface types can be used polymorphically

Interface is a way to implement multiple inheritance.Since this feature is not available directly
so you can implement it indirectly through interfaces.Consider following

class multiple extends Ramos implements Callable{}

The following is a legal interface declaration:
public abstract interface Callable { }

both of these declarations are legal, and functionally identical:
public abstract interface Rollable { }
public interface Rollable { }

The public modifier is required if you want the interface to have public rather
than default access.


Following 5 methods declarations are legal

void boe();
public void boe();
abstract void boe();
public abstract void boe();
abstract public void boe();

The following interface method declarations won't compile:

final void boe(); // final and abstract can never be used
// together, and abstract is implied
static void boe(); // interfaces define instance methods
private void boe(); // interface methods are always public
protected void boe(); // (same as above)

Declaring Interface Constants

You need to remember one key rule for interface constants. They must always be
public static final

keyword final – prevents the value from being change.

Because interface constants are defined in an interface, they don't have to be declared as public, static, or final. They must be public, static, and final, but you don't have to actually declare them that way.

interface Fun {
int BAZ = 42;
void do();
}
class Zap implements Fun {
public void do() {
BAR = 27;
}
}

This sample code trys to change the value of BAZ which is unacceptable. Hence, the code gives compilation error.

Read more...

Class Declaration

Class Declaration

Source File Declaration Rules

1. There can be only one public class per source code file.
2. Comments can appear at the beginning or end of any line in the source code
file.They are independent of any of the rules explained here.
3. If there is a public class in a file, the name of the file must be same as the name
of the public class. For example, a class declared as public class Cat { }
must be in a source code file named Cat.java.
4. If the class is part of a package, then package statement must be the first line
in the source code file, before any import statements that may be present.
5.If there are import statements, they must go between the package statement
and the class declaration. If there isn't a package statement,
then the import statement(s) must be the first line(s) in the source code file.
If there are no package or import statements, the class declaration must be
the first line in the source code file.
6. import and package statements apply to all classes within a source code file.
In other words, there's no way to declare multiple classes in a file and have
them in different packages, or use different imports.
7.A file may contain more than one nonpublic class.
8. Files with no public classes can have a name that does not match any of the
classes in the file.

Class Declarations and Modifiers

The class can be declared by the following code

class MyFirstClass { }
{}
This code compiles fine, but you can also add modifiers before the class
declaration. Modifiers fall into two categories:
1. Access modifiers: public, protected, private.
2. Non-access modifiers (including strictfp, final, and abstract).

Class Access
When we say code from one class (class A) has access to another class (class B), it means class A can do one of three things:
1. Create an instance of class B.
2. Extend class B (in other words, become a subclass of class B).
3. Access certain methods and variables within class B, depending on the access
control of those methods and variables.

Default Access A class with default access has no modifier preceding it in the
Declaration.A class with default access can be seen only by classes within the same package.
For example, if class X and class Y are in different packages, and class X has default access, class Y
won't be able to create an instance of class , or even declare a variable or return
type of class X.


package drink;
class Cold { }
Now look at the second source file:
package exam.stuff;
import drink.Cold;
class Tea extends Cold { }

The superclass (Cold) is in a different package from the
subclass (Tea). The import statement at the top of the Tea file is trying (fingers
crossed) to import the Cold class. The Cold file compiles fine, but when we
try to compile the Tea file we get something like:

Can't access class cert.Beverage. Class or interface must be
public, in same package, or an accessible member class.
import drink.Cold;

Public Access A class declaration with the public keyword gives all classes
from all packages access to the public class. In other words, all classes in the Java
have access to a public class.

package cert;
public class Beverage { }

Other (Nonaccess) Class Modifiers
You can modify a class declaration using the keyword final, abstract, or
strictfp. These modifiers are in addition to whatever access control is on the class,
so you could, for example, declare a class as both public and final. But you can't
always mix nonaccess modifiers. strictfp can be used in combination with
final, for example, but you must never, ever, ever mark a class as both final and
abstract.

Final Classes When used in a class declaration, the final keyword means
the class can't be subclassed. In other words, no other class can ever extend (inherit
from) a final class, and any attempts to do so will give you a compilation error. Use this final for safety purpose. Marking a class final means, in essence, your class can't ever be Extended , or even specialized, by another programmer.


Let's modify our Beverage example by placing the keyword final in the
declaration:
package cert;
public final class Beverage {
public void importantMethod() { }
}

Now, if we try to compile the Tea subclass:
package exam.stuff;
import cert.Beverage;
class Tea extends Beverage { }

We get an error something like
Can't subclass final classes: class
cert.Beverage class Tea extends Beverage{
1 error

Abstract Classes An abstract class can never be instantiated. It is always extended.

Take a look at the following abstract class:
abstract class Bike {
private double price;
private String model;
private String year;
public abstract void goFast();
public abstract void goUpHill();
public abstract void impressNeighbors();
}

The preceding code will compile fine. However, if you try to instantiate a Bike in
another body of code, you'll get a compiler error something like this:
AnotherClass.java:7: class Bike is an abstract
class. It can't be instantiated.
Bike x = new Bike();
1 error

Notice that the methods marked abstract end in a semicolon rather than
curly braces.

Read more...

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP