12.07.2015 Views

OsmWv

OsmWv

OsmWv

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Java basicsQ: Whydoes everything haveto be In a dass7A: ~ava is an object-oriented(00) language. It's not Iiketheold days when you had steamdrivencompliers and wrote onemonolithic source file with a pileof procedures. In chapter 2 you'lllearn that a class Is a blueprint foran object, and that nearly everythingin Java Is an object.Q: Do I have to put a main Inevery class Iwrite1A: Nope .A Java prog rammight use dozens of classes (evenhundreds), but you might onlyhave one with a maIn methodtheone that starts the programrunning.You might wrIte testclasses, though, that have mainmethods for testing your otherclasses,Q: In my other language Icando a boolean test on an Integer.InJava, can Isay something like:int x .. 1;while (J&:) (A: No.A boolean and anintegerare not compatible types InJava.Since the result of a conditionaltest must be a boolean, theonly varIable you can directly test(without using a comparison operator)Is a boolean. For example,you can say:boolean isBot • true;while (llIHot) ( )Exall1ple of awhile looppublic class Loopy {public static void main (String[] args) (int x .. 1;System.out.println("Before the Loop");while (x < 4) {)System.out.println("In the loop");System.out.prlntln("Value of x is " + x);x = x + 1;System.out.println("This is after the loop");% java LoopyBefore the LoopIn the loopVa.lue ot x is 1In the loopVa.lue of x i8 2In th8 loopValue of x is 3This is aft.r the loop,------ BULLD POI~ ----------,• Statements end ina semicolon;• Code blocks are defined byapair of cu~y braces { }• Declare an int variable with a name and atype: Intx;••The assignment operator Isone equals sign =The equals operator uses two equals signs ==• Awhile loop runs everything within itsblock (defined by cu~ybraces) as long as the conditional test Is true.• If the conditional test isfa1S8, the while loop code block won'trun, and execution will move down to the code Immediatelyefterthe loop block.• Put a boolean test Inside parentheses:while (x = 4) ( }12 chapter 1

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!