Você está na página 1de 53

Solutions to Chapter One Questions 1. Why is Java known as a platform-neutral language? Ans.

Java is known as platform-neutral language because Java's bytecodes are designed to be read, interpreted, and executed in exactly the same manner on any computer hardware or operating system that supports a Java run-time.

2. ow is Java more secure than other languages? Ans. !ne of the potential terrors of the "nternet is the possibility of security breaches- viruses that infect your computer, or hackers who take advantage of a software glitch to invade your personal cyberspace and make off with confidential information. #pplets, which are Java programs, are automatically downloaded when a Web page is displayed. Java applets, by default, execute within the Java executing environment and are limited to the environment. $his means, an applet cannot access the local file system or other programs of the system where it executes. $his reduces the chance that simply viewing someone's page might harm your system or data. %o system is absolutely reliable and none will ever be& but Java represents the state-of-the-art in reducing the chances of a disaster.

3. What is multithreading? Ans.

ow does it improve the performance of Java?

"n a multithreading environment, a thread is the smallest unit of dispatchable code. $his means that a single program can perform two or more tasks simultaneously. 'or instance a text editor can format text at the same time that it is printing. $he benefit of Java's multithreading is that the main loop(polling mechanism is eliminated. !ne thread can pause without stopping other parts of the program. 'or example, the idle time created when a thread reads data from a network or waits for user input can be utili)ed elsewhere. When a thread blocks in a Java program, only the single thread that is blocked pauses. #ll other threads continue to run.

4. *ist at least seven ma+or differences between , and Java. Ans. $he following are the differences between , and Java-

Java does not have a preprocessor, and as such, does not have macros like .define. ,onstants can be created by using the final modifier when declaring class and instance variables. "n Java, all methods are tied to classes. Java does not support stand-alone methods. Java does not include the const keyword as present in , or the ability to pass by const reference explicitly. "n Java strings are implemented as ob+ects and not as an array of null-terminated characters. Java has some additional primitive data types like byte and /oolean. 0ata types in Java have a fixed si)e regardless of the operating system used. $he goto keyword does not exist in Java 1it's a reserved word, but currently unimplemented2. 3ou can, however, use labeled breaks and continues to break out of and continue executing complex switch or loop constructs. Java does not use pointers. "n Java, arrays are real ob+ects because you can allocate memory using the new operator.

5. ow is Java strongly associated with the "nternet? Ans. "nternet users can use Java to create applet programs and run them locally using 4Java-enabled browsers4 such as otJava. $hey can also use a Java-enabled browser to download an applet located on a computer anywhere in the "nternet and run it on their local computer. "nternet users can also set up their websites containing +ava applets that could be used by other remote users of the "nternet.

6. What is Ans.

ypertext 5arkup *anguage? 0escribe its role in the implementation of Java applets.

ypertext 5arkup *anguage or $5* is a markup language that uses predefined tags to specify the browser how it needs to display a Web page. /rowsers allow us to retrieve the information from the "nternet and display it using the ypertext 5arkup *anguage 1 $5*2. otJava, %etscape %avigator and "nternet 6xplorer are some popular Web browsers. # Web page can embed Java applets. $o embed an applet, the 7#pplet8 tag is used in the $5* document. When a browser encounters the 7#pplet8 tag it loads the applet and executes it with the browser Java 9irtual 5achine 1J952.

7. *ist out primary goals of Java $echnology. Ans. $he primary goals of Java technology are-

$o provide an easy to use language by avoiding pitfalls of other languages and enables users to create clear and streamlined code. $o provide an interpreted environment for improved speed of development and code portability. $o provide a way for programs to run more than one thread of activity. $o furnish better security.

Solutions to Chapter Two Questions 1. What is ob+ect-oriented programming? Ans. !b+ect- oriented programming is a method of implementation in which programs are organi)ed as co-operative collection of ob+ects, each of which represents an instance of some class and whose classes all members of a hierarchy of classes united in inheritance relationships. With procedural programming you are able to combine returning se:uences of statements into one single place. # procedure call is used to invoke the procedure. #fter the se:uence is processed, flow of control proceeds right after the position where the call was made ow is it different from the procedure-oriented programming?

2. ow are data and methods organi)ed in an ob+ect-oriented program? Ans. "n an ob+ect-oriented program, a set of variables and functions used to describe an ob+ect constitutes a 4class4. # class defines the structure and behavior 1data and method2 that will be shared by a set of ob+ects. 6ach ob+ect of a given class contains the structure and behavior defined by the class, as if it were stamped out of a mould in the shape of a class. # class is a logical construct. #n ob+ect has physical reality. When you create a class, you will specify the code and data that will constitute that class. ,ollectively, these elements are called the members of the class. ;pecifically, the data defined by the class are referred to as member variables or instance variables. $he code that operates on that data is referred to as member methods or +ust methods, which define the use of the member variables.

3. What are uni:ue advantages of an ob+ect-oriented programming paradigm? Ans. !!< offers several advantages to both the program designer and the user. $he important advantages are-

Reusability- 6limination of redundant code and use of existing classes through inheritance. $hus provides economy of expression. o!ularity- <rograms can be the built from standard working modules. Se"urity- <rinciple of information hiding helps programmer to build secure programs. #asy $appin%- !b+ect in the problem domain can be directly mapped to the ob+ects in the program.

S"alability- ,an be easily upgraded from small programs to large programs. !b+ectoriented systems are also resilient to change and evolve over time in a better way. #asy $ana%e$ent- 6asy management of software complexity.

4. 0istinguish between the following terms-


Ans.

!b+ects and classes 0ata abstraction and data encapsulation "nheritance and polymorphism 0ynamic binding and message passing

Ob&e"ts an! "lasses- !b+ect is a physical entity which represents a person, vehicle or a conceptual entity 1thing in existence2 like bank account, company etc. # set of variables and functions used to describe an ob+ect is a 4class4. # class defines the structure and behavior 1data and code2 that will be shared by a set of ob+ects. 6ach ob+ect of a given class contains the structure and behavior defined by the class, as if it were stamped out of a mould in the shape of a class. # class is a logical construct. #n ob+ect has physical reality. When you create a class, you will specify the code and data that will constitute that class. ,ollectively, these elements are called the members of the class. ;pecifically, the data defined by the class are referred to as member variables or instance variables. $he code that operates on that data is referred to as member methods or +ust methods, which define the use of the member variables. 'ata abstra"tion an! !ata en"apsulation- #bstraction - the act or process of leaving out of consideration one or more :ualities of a complex ob+ect so as to attend to others. ;olving a problem with ob+ects re:uires you to build the ob+ects tailored to your solution. We choose to ignore its inessential details, dealing instead with the generali)ed and ideali)ed model of the ob+ect. 6ncapsulation - $he ability to provide users with a well-defined interface to a set of functions in a way, which hides their internal workings. "n ob+ect-oriented programming, the techni:ue of keeping together data structures and the methods 1procedures2 which act on them. $he easiest way to think of encapsulation is to reference phones. $here are many different types of phones, which consumers can purchase today. #ll of the phones used today will communicate with each other through a standard interface. 'or example, a phone made by =6 can be used to call a phone made by <anasonic. #lthough their internal implementation may be different, their public interface is the same. $his is the idea of encapsulation. (nheritan"e an! poly$orphis$- "nheritance in ob+ect-oriented programming means that a class of ob+ects can inherit properties from another class of ob+ects. When inheritance occurs, one class is then referred as the 'parent class' or 'superclass' or 'base class'. "n turn, these serve as a pattern for a 'derived class' or 'subclass'. "nheritance is an important concept since it allows reuse of class definition without re:uiring ma+or code changes. "nheritance can mean +ust reusing code, or can mean that you have used a whole class of ob+ect with all its variables and functions. <olymorphism- "t is a key concept in ob+ect-oriented programming. <oly means many, morph means change 1or 'form'2. <olymorphism is simply a name given to an action that is performed by similar ob+ects. <olymorphism allows a common data-gathering message to be sent to each class and allows each subclass ob+ect to respond to a message format in an appropriate manner to its own properties. <olymorphism encourages something we call 'extendibility'. "n other words, an ob+ect or a class can have its uses extended. 'yna$i" bin!in% an! $essa%e passin%- 0ynamic binding in +ava is the mechanism by which compiler cannot determine which method implementation to use in advance. /ased on the class of the ob+ect, the runtime system selects the appropriate method at runtime. 0ynamic binding is also needed when the compiler determines that there is more than one possible method that can be executed by a particular call. Java's program units, classes, are loaded dynamically 1when needed2 by the Java run-time system. *oaded classes are then dynamically linked with existing classes to form an integrated unit. $he lengthy link-and-load step re:uired by thirdgeneration programming languages is eliminated. 5essage <assing- "n an ob+ect based world the only way for anything to happen is by ob+ects communicating with each other and acting on the results. $his communication is called message passing and involves one ob+ect sending a message to another and 1possibly2 receiving a result.

5. 0escribe inheritance as applied to !!<. Ans.

"nheritance in ob+ect oriented programming means that a class of ob+ects can inherit properties from another class of ob+ects. When inheritance occurs, one class is then referred to as the 'parent class' or 'superclass' or 'base class'. "n turn, these serve as a pattern for a 'derived class' or 'subclass'. "nheritance is an important concept since it allows reuse of class definition without re:uiring ma+or code changes. "nheritance can mean +ust reusing code, or can mean that you have used a whole class of ob+ect with all its variables and functions.

6. *ist a few areas of application of !!< technology. Ans. !!< can be used for such diverse applications as >eal-time systems, simulation and modeling, #" and 6xpert systems parallel programming and %eural networks, 0ecision support systems, !ffice automation systems and others.

7. ;tate whether the following statements are $>?6 or '#*;6-

Ans. True

"n conventional, procedure-oriented programming, all data are shared by all functions.

Ans. True

$he main emphasis of procedure-oriented programming is on algorithms rather than on data.

Ans.True

!ne of the striking features of ob+ect-oriented programming is the division of programs into ob+ects that represent real-world entities.

Ans. $rue

Wrapping up of data of different types into a single unit is known as encapsulation.

Ans. True

!ne problem with !!< is that once a class is created, it can never be changed.

Ans. True

"nheritance means the ability to reuse the data values of one ob+ect by other ob+ects.

Ans. )alse

<olymorphism is extensively used in implementing inheritance.

Ans. True

!b+ect-oriented programs are executed much faster than conventional programs.

Ans. $rue

!b+ect-oriented systems can scale up better from small to large.


Ans. 'alse

!b+ect-oriented approach cannot be used to create databases.

Solutions to Chapter Three Questions 1. 0escribe the structure of a typical Java program. Ans. # Java program may contain many classes of which only one class defines a main method. ,lasses contain data members and methods. 5ethods of a class operate on the data members of the class. 5ethods may contain data type declarations and executable statements. $o write a Java program, we first define classes and then put them together. # Java program may contain one or more sections as shown in the following figure0ocumentation ;ection ;uggested

<ackage ;tatement "mport ;tatements "nterface ;tatements ,lass 0efinitions 5ain 5ethod class @ 5ain 5ethod 0efinition A

!ptional !ptional !ptional 6ssential

6ssential

General Structure Of a Java program 'o"u$entation Se"tion $he documentation section comprises a set of comment lines giving the name of the program, the author and other details. Java also uses the comment (BB...B( known as documentation comment. *a"+a%e State$ent $he first statement allowed in a Java file is a package statement. $his statement declares a package name and informs the compiler that the classes defined here belong to this package. 6xample- package student& ($port State$ent $he next thing after a package statement 1but before any class definitions2 may be a number of import statements. $his is similar to the .include statement in ,CC. 6xampleimport student.test& $his statement instructs the interpreter to load the test class contained in the package student. (nter,a"e State$ents #n interface is like a class but includes a group of method declarations. $his is also an optional section and is used only when we wish to implement the multiple inheritance feature in the program.

Class 'e,initions # Java program may contain multiple class definitions. ,lasses are the primary and essential elements of a Java program. ain etho! Class

;ince every Java stand-alone program re:uires a main method as its starting point, this class is the essential part of a Java program. # simple Java program may contain only this part. $he main method creates ob+ects of various classes and establishes communications between them.

2. What is the task of the main method in a Java program? Ans. #fter you specify the keywords for declaring the main12 method, you specify a ;tring array as parameter of the main12 method. $he ;tring array represents command line arguments. "t is compulsory for a user to specify the parameter to the main12 method in all Java programs unlike in , and ,CC. 'or example, class classD @ public static void main 1;tring argsEF2 @ ;ystem.out.println14 ello42 A A

3. What is a token? *ist the various types of tokens supported by Java. Ans. Java *anguage includes four types of tokens. $hey are-


-eywor!s

>eserved Geywords "dentifiers *iterals !perators

Geywords are an essential part of a language definition. $hey implement specific features of the language. Java language has reserved HI words as keywords. $he following table lists the keywords. $hese keywords have specific meaning in Java, we cannot use them as names for variables, classes, methods. #ll keywords are to be written in lower case letters. ;ince Java is case-sensitive. $he following table lists the Java keywordsabstract boolean case cast constB continue else extends float for if implements int "nterface nullBB operatorB protected public static super threadsafeB throw $ry varB B >eserved for future use break catch default falseBB futureB import long outerB restB switch throws void byte char do final genericB innerB native package return synchroni)ation transient volatile byvalueB class double finally gotoB instanceof new private short this trueBB while

(!enti,iers "dentifiers are used for naming classes, methods, variables, ob+ects, labels, package and interfaces in a program. 6xamples#verage ;um /atchJstrength .iterals *iterals in Java are a se:uence of characters 1digits, letters, and other characters2 that represent constant values to be stored in variables. Java language specifies five ma+or types of literals. $hey are-


Operators

"nteger literals 'loating point literals ,haracter literals ;tring literals /oolean literals

#n operator is a symbol that takes one or more operands and operates on them to produce a result.

4. Why can't we use a keyword as a variable name? Ans. Geywords are an essential part of a language definition. $hey implement specific features of the language. Java language has reserved HI words as keywords. $hese keywords have specific meaning in Java, so you cannot use them as names for variables.

5. 6numerate the rules for creating identifiers in Java. Ans. Java identifiers follow the following rules-

$hey can have alphabets, digits, and the underscore and dollar sign characters. $hey must not begin with a digit ?ppercase and lowercase letters are distinct. $hey can be of any length.

6. What are the conventions followed in Java for naming identifiers? =ive examples. Ans. ,onventions for naming Java identifiers are-

"dentifier name has to be meaningful. $here should be no embedded space in an identifier name.

'or example- student%ame, employee"0.

7. 6xplain the println statement in Java with an example? Ans. ,onsider the following statement;ystem.out.println 14string to be printed42& $he statement begins with ;ystem.out. $his is a constant that represents the default output mode, which in this case is the screen. $he constant helps to read and display the data in a Java program. $he output is generated using the built-in println12 method. $he string that is assigned to the println12 method is displayed when the statement is executed. 'or example, class ,lassK @ public static void main 1;tring argsEF2 @ ;ystem.out.println14 ere is your string42& A A $he above program will show the following outputere is your string

/. Why is the main12 method in Java declared static? Ans. $he keyword static helps to specify that the main12 method can be called without instantiating an ob+ect of a class. $his is necessary because the main12 method is called by the Java interpreter before any ob+ects are created. public static void main 1;tring argsEF2 @((codeA #fter specifying the keyword static, you specify the void keyword. $his keyword indicates to the compiler that, the main12 method does not return a value.

0. What is an applet? Ans. #pplets are small Java programs developed for "nternet applications. #n applet located on a distant computer 1;erver2 can be downloaded via "nternet and executed on a local computer 1,lient2 using a Java-capable browser.

11. 6xplain with a simple example how to create, compile and run a program in Java. Ans. Java program involves two stepsD. K. ,ompiling source code into bytecode using +avac compiler 6xecuting the bytecode program using +ava interpreter 'or example, consider the following program class <rogram0emo @ public static void main 1;tring argsEF2 @ ;ystem.out.println14 ere is your string42&

A A 'irst, save the program as <rogram0emo.+ava. $hen, to compile this program type the following command at command prompt,-L0irD8 +avac <rogram0emo.+ava. !nce the program compiles successfully run this program by typing the following command at command prompt,-L0irD8 +ava <rogram0emo

Solutions to Chapter )our Questions 1. What is a constant? Ans. ,onstants are fixed values that do not change during the execution of a program. "n Java, you can use the final keyword to specify that the value of a variable cannot change. 'or example, public static final int x MDI& ere, x is a final variable with value DI.

2. What is a variable? Ans. # variable is an identifier that denotes a storage location used to store a data value. ?nlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program.

3. *ist the eight basic data types used in Java. =ive examples. Ans. $he eight basic data types used in +ava arebyte- "t is the smallest integer type. $his is a signed N-bit type and has a range from -DKN to DKO. 'or example, the following declaration declares two variables / and , of type byte. byte b,c& b MK& c M -DDP& short- "t is a signed DH-bit type and has a range from -QK,OHN to QK,OHO. 'or example, the following declaration declares variable G of type short. short k& k M K& int- "t is a signed QK-bit type and has a range from -K,DPO,PNQ,HPN to K,DPO,PNQ,HPO. 'or example, int x M DI& int + M RN& lon%- $his is signed HP-bit type and has a range from -KHQ to KHQ -D. 'or example, long ds M DIII& long se& se Mds B KP B HI B HI& !ouble- "t uses HP bits to store a value.

'or example, double <, >& < M DI.N& > MQ.DPKDS& ,loat- "t uses QK bits to store a value. 'or example, float x& x M -DDDD& int 2 (t uses 32 bits to store a 3alue. )or e4a$ple5 (nt s"ore6 S"ore7016 "har- this data type is used to store characters. "t is DH-bit type and has a range from I to HS,SQH. 'or example, char cD,cK& cD MNP& cK M'g'& boolean- it can have only one of two possible values, true or false. 'or example, boolean flag& flagM false&

4. What is scope of a variable? Ans. $he area of the program where the variable is accessible 1i.e., usable2 is called its scope. Java variables are actually classified into three kinds-

"nstance 9ariables ,lass variables *ocal variables

"nstance and class variables are declared inside a class. "nstance variables are created when the ob+ects are instantiated and therefore they are associated with the ob+ects. $hey take different values for each ob+ect. !n the other hand, class variables are global to a class and belong to the entire set of ob+ects that the class creates. 9ariables declared and used inside methods are called local variables. $hey are called so because they are not available for use outside the method definition. *ocal variables can also be declared inside program blocks that are defined between an opening brace '@' and a closing brace 'A'. $hese variables are visible to the program only from the beginning of its program block to the end of the program block. When the program control leaves a block, all the variables in the block will cease to exist.

5. What is type casting? Why is it re:uired in programming? Ans. $he process of converting one data type to another is called casting. $ype variableD M 1type2 variableK& 6xamplesint m M SI& byte n M 1byte2m&

long distance M 1long2m& $ype casting is re:uired in programming when you want to assign the value of one variable to another variable of different data type.

6. Which of the following are invalid constants and why? 0.001 +100 -45.! Ans. $he following are invalid constants5*1.5 75.42E-2 -1.4e"+4# RS 75.50 15.75 0.0000012$4

>; OS.SI- "t should be written as 4>; OS.SI4 -D.Pe1CP2- "t should be written as -D.PeCP

7. Which of the following are invalid variable names and why? m%n%mum (ou)le& float Ans. $he following are invalid variable namesf%r&t.'ame $r( *ro+ Sum -otal n1+ n2 ', -otal-.ar/&

,irst.8a$e- 9ariable name should not have a period in between n19 n2- 9ariable name should not have a 'C' in between 3r! :row- 9ariable name should not begin with a digit ,loat- 9ariable name should not be a keyword Su$ Total- 9ariable name should not have an embedded space Total: ar+s- 9ariable name should not have a '-' in between. "t can only have underscore sign. the

/. 'ind errors, if any, in the following declaration statementsint x& float length, height& double M p,:& character cD& final int total& final pi M Q.DPK& long int m& Ans. $he statements that contain errors aredouble M p,:& character cD& final pi M Q.DPK& long int m&

0. Write a program to determine the sum of the following harmonic series for a given value of nDCD(K C D(QC ..............CD(n $he value of n should be given interactively through the keyboard.

Ans. public class ;eries @ double total& public void calculate1int n2 @ for1double ctrMD&ctr7Mn&ctrCC2 @ totalMtotalCD(ctr& A ;ystem.out.println14;um of harmonic series- 4Ctotal2& A public static void main1;tring aEF2 @ ;eries ob+ectMnew ;eries12& int numM"nteger.parse"nt1aEIF2& ob+ect.calculate1num2& A A

11. Write a program to convert the given temperature in 'ahrenheit to ,elsius using the following conversion formula '-QK , M D.N and display the values in a tabular form. Ans. public class ,elsius @ double celsius& double fahrenheit& public ,elsius12 @ fahrenheitMRN.P& A public void convert12 @ celsiusM1fahrenheit-QK2(D.N& ;ystem.out.println14$emperature in celsius- 4Ccelsius2& A public static void main1;tring aEF2 @ ,elsius ob+ectMnew ,elsius12& ob+ect.convert12& A A

Solutions to Chapter )i3e Questions 1. Which of the following arithmetic expressions are valid? a# 250$ 1 2 )# +204 + 5 c# 7.5 1 $ (# 14 1 $ + 7 1 2 e# -14 1 $ f# 15.25 + -5.0 g# "50$# * $ + 5 1 $ 3# 21 1 "%nt# 4.5

Ans. #ll of the above arithmetic expressions are valid.

2. Write Java assignment statements to evaluate the following e:uationsa2 #rea M rKCK rh b2 c2 ;ide

Torque =

2m1m 2 *g m1m 2

M aK C bK T Kab cos1x2

d2

velocity2 Energy = mass acceleration * height + 2

Ans. import +ava.io.B& public class #ssignment;tatements@ int r, h, mD, mK, a, b, x, mass, acceleration, height, velocity& double area, tor:ue, side, energy& public void calculate#rea12@ try@ ;ystem.out.print146nter radius - 42& /uffered>eader br M new /uffered>eader1new "nput;tream>eader1;ystem.in22& r M "nteger.parse"nt1br.read*ine122& ;ystem.out.print146nter height - 42& h M "nteger.parse"nt1br.read*ine122& area M 1Q.DPBrBr2C1KBQ.DPBrBh2& ;ystem.out.println14$he area is - 4 C area2& A catch16xception e2@ ;ystem.out.println146rror42& A A public void calculate$or:ue12@ try@

;ystem.out.print146nter mD - 42& /uffered>eader br M new /uffered>eader1new "nput;tream>eader1;ystem.in22& mD M "nteger.parse"nt1br.read*ine122& ;ystem.out.print146nter mK - 42& mK M "nteger.parse"nt1br.read*ine122& tor:ue M 11KBmDBmK2(1mDCmK22BR.N& ;ystem.out.println14$he tor:ue is - 4 C tor:ue2& A catch16xception e2@ ;ystem.out.println146rror42& A A public void calculate;ide12@ try@ ;ystem.out.print146nter a - 42& /uffered>eader br M new /uffered>eader1new "nput;tream>eader1;ystem.in22& a M "nteger.parse"nt1br.read*ine122& ;ystem.out.print146nter b - 42& b M "nteger.parse"nt1br.read*ine122& ;ystem.out.print146nter x - 42& x M "nteger.parse"nt1br.read*ine122& side M 5ath.s:rt11aBa2 C 1bBb2 -1KBaBbB5ath.cos1x222& ;ystem.out.println14$he area is - 4 C side2& A catch16xception e2@ ;ystem.out.println146rrpr42& A A public void calculate6nergy12@ try@ ;ystem.out.print146nter mass - 42& /uffered>eader br M new /uffered>eader1new "nput;tream>eader1;ystem.in22& mass M "nteger.parse"nt1br.read*ine122& ;ystem.out.print146nter acceleration - 42& acceleration M "nteger.parse"nt1br.read*ine122& ;ystem.out.print146nter height - 42& height M "nteger.parse"nt1br.read*ine122& ;ystem.out.print146nter velocity - 42& velocity M "nteger.parse"nt1br.read*ine122& energy M massB1accelerationBheightC11velocityBvelocity2(K22& ;ystem.out.println14$he energy is - 4 C energy2& A catch16xception e2@ ;ystem.out.println146rrpr42& A A

public static void main1;tring argEF2@ #ssignment;tatements as M new #ssignment;tatements12& as.calculate#rea12& as.calculate$or:ue12& as.calculate;ide12& as.calculate6nergy12& A A 3. "dentify unnecessary parenthesis in the following arithmetic expressions. 1a2 1x-1y(S2C)2 U N2 C KS 1b2 11x-y2 B p2 C : 1c2 1mBn2 C 1-x(y2 1d2 x(1QBy2 Ans. 1a2 1x-1y(S2C)2 U N2 C KS. $he parenthesis after N in this expression has no opening parenthesis. 1b2 11x-y2 B p2 C :. "t can also be written 1x-y2Bp C: 1c2 1mBn2 C 1-x(y2. "t can also be written mBn C-x(y 1d2 x(1QBy2. %o unnecessary parenthesis is there in it.

4 0etermine the value of each of the following logical expressions if aMS, bMDI and cM-H 1a2 a8b VV a7c Ans. false

1b2 a7b VV a8c Ans. true

1c2 aMMc WW b8a Ans. true

1d2 b8DS VV c7I WW a8I Ans. true

1e2 1a(K.I MM I.I VV b(K.I XM I.I2 WW c7 I.I Ans. true

5 $he straight-line method of computing the early depreciation of the value of an item is given by

Depreciation =

Purchase price Salvage value Years of service

Write a program to determine the salvage value of an item when the purchase price, years of service, and the annual depreciation are given. Ans. class 0epreciation @ double <urchase<rice& double ;alvage9alue& double 0epricat9alue& int 3ears& public double ;alvage1double <urchase<rice, double 0epricat9alue, int 3ears2 @ return <urchase<rice - 10epricat9alue B 3ears2& A public static void main1;tring argsEF2 @ 0epreciation dep M new 0epreciation 12& ;ystem.out.println14$he salvage value is- 4 C dep.;alvage1KIII.II, KSI.II, S22& A A

6. $he total distance traveled by a vehicle in t seconds is given by 0istance M ut C 1atK2(K Where u is the initial velocity 1metres per second2, a is the acceleration 1metres per second2. Write a program to evaluate the distance traveled at regular intervals of time, given the values of u and a. $he program should provide the flexibility to the user to select his own time intervals and repeat the calculations for different values of u and a. Ans. import +ava.io.B& class 0istance@ int a& int t& int u& int dist& public 0istance12 @ a M DI& u M DI& A public void calculate12@ try@ /uffered>eader br M new /uffered>eader1new "nput;tream>eader1;ystem.in22& ;ystem.out.print146nter time 1sec2- 42&

t M "nteger.parse"nt1br.read*ine122& dist M 1uBt2 C 1aBtBt2(K& ;ystem.out.println14$he distance is - 4 C dist C 4 meters42& Acatch16xception e2@ ;ystem.out.println14error42& A A public static void main1;tring argEF2@ 0istance d M new 0istance12& d.calculate12& A A

7. "n inventory management, the 6conomic !rder Yuality for a single item is given by

EO =

2*demand rate *setup costs !olding cost per item per unit time 2*setup costs demand rate* holding cost per unit time

and the optimal $ime /etween !rders

T"O =

Write a program to compute 6!Y and $/!, given demand rate 1items per unit time2, setup costs 1per order2, and the holding cost 1per item per unit time2. Ans. class "nven5anagement @ int 0emand>ate& double ;etup,ost& double old,ost& public double 6!Y1double ;etup,ost, double old,ost, int 0emand>ate2 @ double value M 1KB0emand>ateB;etup,ost2( old,ost& return 5ath.s:rt1value2& A public double $/!1double ;etup,ost, double @ double value M 1KB;etup,ost2(10emand>ateB old,ost2& return 5ath.s:rt1value2& A public static void main1;tring argsEF2 @ "nven5anagement "5 M new "nven5anagement12& ;ystem.out.println14$he value of 6!Y is- 4 C "5.6!Y1DIIII.II, QIII.II, S22& old,ost, int 0emand>ate2

;ystem.out.println14$he value of $/! is- 4 C "5.$/!1DIIII.II, QIII.II, S22&

A A

Solutions to Chapter Si4 Questions 1. 0etermine whether the following are true or false. 1a2When if statements are nested, the last else gets associated with the nearest if without an else. Ans. $rue

1b2!ne if can have more than one else clause. Ans. 'alse

1c2 # switch statement can always be replaced by a series of if....else statements Ans. $rue

1d2 # switch expression can be of any type. Ans. 'alse

1e2 # program stops its execution when a break statement is encountered. Ans. 'alse 2. "n what ways does a switch statement differ from an if statement? Ans. #n if statement can be used to make decisions based on range of values or conditions, whereas a switch statement can make decisions based only on a single integer value. #lso, the value provided to each case statement must be uni:ue.

3. 'ind errors, if any, in each of the following segments& 1a2 if 1xCy M ) VV y 8 I2 Ans. $his is not a valid expression. xCy M) and y8I must be enclosed in parenthesis.

1b2 if 1code8D2& a M bCc else aMI Ans. "t will give an error because of the semicolon present after the if statement.

1c2 if 1p 7 I2 WW 1: 7 I2 Ans. $his statement needs to be written asif 1 1p 7 I2 WW 1: 7 I22

4. >ewrite each of the following without using compound relations1a2 if 1grade 7 M SR VV grade 8MSI2 second M second C D Ans. "f 1grade 7 M SR2 @ if 1grade8 MSI2 second M second C D& A

1b2 if 1number 8 DII VV number 7 I2 ;ystem.out.print14!ut of range42& else ;um M sum C number& Ans. if 1number 8 DII 2 @ if 1number 7 I 2 ;ystem.out.print14!ut of range42& A else ;um M sum C number& A

1c2 if 115D8HI VV 5K8HI WW $ 8KII2 yMD& else yMI& Ans. if1$8KII2@ y MD& A else if15D8HI2@ if15K8HI2@ y MD& A else y MI&

5. Write a program to find the number of and sum of all integers greater than DII and less than KII that are divisible by O. Ans. public class 0ivisible @ int num& int sum& public void calculate12 @ sumMI& ;ystem.out.println14%umbers divisible by O-42& for1numMDII&num7KII&numCC2 @ if1numUOMMI2 @ ;ystem.out.println1num2& sumMsumCnum& A A ;ystem.out.println14;um- 4Csum2& A public static void main1;tring aEF2 @ 0ivisible ob+Mnew 0ivisible12& ob+.calculate12& A A

6. =iven a list of marks ranging from I to DII, write a program to compute and print the number of students who have obtained marks 1a2 in the range ND to DII, 1b2 in the range HD to NI, 1c2 in the range PD to HI, and 1d2 in the range I to PI. $he program should use a minimum number of if statements. Ans. import +ava.io.B& public class ;tudent5arks @ int rDMI& int rKMI& int rQMI&

int rPMI& int rnMD& static /uffered>eader br& public ;tudent5arks1int num2 @ int arrEFMnew intEnumF& try @ for1int iMI&i7arr.length&iCC2 @ ;ystem.out.println14enter the marks for >oll number4C rn2& arrEiFM"nteger.parse"nt1br.read*ine122& rnCC& A for1int +MI&+7arr.length&+CC2 @ if1arrE+F8MI VV arrE+F7MPI2 @ rDCC& A else if1arrE+F8PI VV arrE+F7MHI2 @ rKCC& A else if1arrE+F8HI VV arrE+F7MNI2 @ rQCC& A else if1arrE+F8NI VV arrE+F7MDII2 @ rPCC& A A ;ystem.out.println14;tudents securing marks in the range of I-PI areLt4CrD2& ;ystem.out.println14;udents securing marks in the range of PI-HI areLt4CrK2& ;ystem.out.println14;udents securing marks in the range of HI-NI areLt4CrQ2& ;ystem.out.println14;udents securing marks in the range of NI-DII areLt4CrP2& A((end of try catch16xception exp2 @ ;ystem.out.println1exp2& A((end of catch

A((end of constructor public static void main1;tring argsEF2 @ try @ brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& ;ystem.out.println146nter the total number of students in the class42& int totalJstudentsM"nteger.parse"nt1br.read*ine122& ;tudent5arks smMnew ;tudent5arks1totalJstudents2& A((end of try catch16xception exp2 @ ;ystem.out.println1exp.get5essage122& A((end of catch A((end of main A((end of class

7. # cloth showroom has announced the following seasonal discounts on purchase of itemsPurchase Amount Mill Cloth 0-100 101-200 201-$00 4)ove $00 5.01 7.51 10.01 5.01 7.51 10.01 15.01 Discount Handloom Items

Ans. import +ava.io.B& class purchase @ double bill& ;tring str& ;tring strJdiscountM44& public purchase12 @ try @ /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& ;ystem.out.println146nter the amount of /ill- 42& billM0ouble.parse0ouble1br.read*ine122& ;ystem.out.println146nter the types of clothe- 42&

str M br.read*ine12& if 1str.e:uals"gnore,ase14handloom422 @ if1bill 8MI VV bill 7MDII2 @ bill M bill- 1billBS2(DII& strJdiscountM4S U4& A if1 bill 8DII VV bill 7MKII2 @ bill M bill - 1billBO.S2(DII& strJdiscountM4O.S U4& A if1bill 8KII VV bill7MQII2 @ bill M bill - 1billBDI2(DII& strJdiscountM4DI U4& A if 1bill 8 QII2 @ bill M bill - 1billBDS2(DII& strJdiscountM4DS U4& A

A if1str.e:uals"gnore,ase14mill422 @ ;ystem.out.println14enter42& if1bill 8MI VV bill 7MDII2 @ bill M bill& strJdiscountM4I U4& A if1 bill 8DII VV bill 7MKII2 @ bill M bill - 1billBS2(DII& strJdiscountM4S U4& A if1bill 8KII VV bill7MQII2 @ bill M bill - 1billBO.S2(DII& strJdiscountM4O.S U4& A

if 1bill 8 QII2 @ bill M bill - 1billBDI2(DII& strJdiscountM4DI U4& A A ;ystem.out.println14$he 0iscount is- 4 C strJdiscount2& ;ystem.out.println14$he final bill after discount is- 4 C bill2& A catch16xception e2 @ ;ystem.out.println146xception is -4Ce2& A A public static void main1;tring argsEF2 @ purchase pur M new purchase12& A A .

Solutions to Chapter Se3en Questions 1. ,ompare in terms of their functions, the following pairs of statements1a2 while and do........while. 1b2 while and for. 1c2 break and continue. Ans. 1a2 $he difference between the do-while statement and the while statement is that in the while statement, the loop body is executed only when the condition stated in the statement is true. "n the do-while loop, the loop body is executed at least once, regardless of the condition evaluating to true or false. $he while loop is also called the top tested loop whereas the do-while loop is also called the bottom tested loop. 1b2 "n the for loop, three sections, initiali)ation, test condition and increment(decrement are placed in the same line whereas in the while loop, all three sections are placed in three different places in a program. "n the for loop, more than one variable can be initiali)ed, tested and incremented at a time. 1c2 $he continue statement stops the current iteration of a loop and immediately starts the next iteration of the same loop. When the current iteration of a loop stops, the statements after the continue statement in the loop are not executed. $he break statement immediately terminates the loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside the loop, the loop is terminated and program control resumes the next statement following the loop.

2. Write a program to compute the sum of the digits of a given integer number Ans. public class ;um @

int arrEF& int rMI,iMI,sumMI& public void calculate1int num2 @ arrMnew intESF&

while1numUDI8I2 @ rMnumUDI& arrEiFMr& iCC& numMnum(DI& sumMsumCr& A ;ystem.out.println14;um- 4Csum2& A public static void main1;tring aEF2 @ int numberM"nteger.parse"nt1aEIF2& ;um ob+Mnew ;um12& ob+.calculate1number2& A A

3. =iven a number, write a program using while loop to reverse the digits of the number. 'or examples, the number DKQPS should produce an output SPQKD.

Ans. public class >everse @ int num& int arrEF,arrDEF& int rMI,iMI& int lenMI& public void calculate1int num2 @ int numDMnum& arrMnew intESF& arrDMnew intESF& while1numDUDI8I2 @ rMnumDUDI& arrEiFMr& iCC& numDMnumD(DI& A lenMi& int +,b,kMi& ;ystem.out.print14>everse %umber-42& for 1int aMI&k8I&aCC,k--2 @ arrDEaFMarrEk-DF& ;ystem.out.print1arrEaF2& A A public static void main1;tring argEF2 @ int numberM"nteger.parse"nt1argEIF2& >everse ob+Mnew >everse12& ob+.calculate1number2& A A

4. #naly)e each of the program segments that follow and determine how many times the body of each loop will be executed. a2 x M S& y M SI& while1x 7M y2 @ x M y ( x& ZZZZZ. ZZZZZ. A int i& for 1iMI& i7MS& iM iCK(Q2 @ ZZZZ. ZZZZ. A b2 m M D& do @ ZZZZ ZZZ. m M m C K& Awhile 1m 7 DI2 int m M DI int nM O& while 1 m U n 8M I2 @ ZZZZ.. m M m C D& n M n C K& ZZZZ. A

c2

d2

Ans. 1a2 "nfinite 1b2 'ive 1c2 "nfinite 1d2 "nfinite 5. What is empty statement? 6xplain its usefulness. Ans. $he empty statement consists of a semicolon. $he empty statement is used when the statements within the loop are not executed.

Solutions to Chapter #i%ht Questions 1. What is class? 0ifferentiate between instance and class variables of a Java class. Ans. ,lass is a template that defines a particular type of ob+ect. ,lasses contain all the features of a particular set of ob+ects. We can use the class definition to create ob+ects of that of class type, that is, to create ob+ects that incorporate all the features belonging to that class. 6ach ob+ect of the class will have its own copy of each of the instance variables that appear in the class definition. 6ach ob+ect will have its own values for each instance variable. $he name 'instance variable' originates from the fact that an ob+ect is an 'instance' or an occurrence of a class and the values stored in the instance variables for the ob+ect differentiate the ob+ect from others of the same class type. #n instance variable is declared within the class definition in the usual way, with a type name and a variable name, and can have an initial value specified. # given class will only have one copy of each of its class variables, and these will be shared between all the ob+ects of the class. $he class variables exist even if no ob+ects of the class have been created. $hey belong to the class, and they can be referenced by any ob+ect or class, and not +ust instances of that class. 2. ow do classes help us to organi)e our programs? Ans. "n essence a class definition is very simple. $here are +ust two kinds of things that you can include in a class definition;ariables 9ariables are the data types that store data items that typically differentiate one ob+ect of the class from another. $hey are also referred to as data members of a class. 6very class you write in Java is generally made up of two componentsattributes and behavior. *et's consider an ob+ect to define a motorcycle. #ttributes are the individual things that differentiate one ob+ect from another and determine the state, appearance, or other :ualities of that ob+ect. $he attributes of our motorcycle might include-

color- red, green, silver, brown. make- onda, /5W, /ultaco. engine!n- true, false.

#ttributes are defined by variables, in fact, you can consider them because each instance of a class can have different values for its variables, each variable is called an instance variable. etho!s $hese define the operations you can perform for the class--so they determine what you can do to, or with, ob+ects of the class. 5ethods typically operate on the fields--the variables of the class. # class's behavior determines what instances of that class do when asked to by another class or ob+ect. /ehavior is the only way that ob+ects can have anything done to them. !ur motorcycle class might well have the following behavior;tart the engine ;top the engine ;peed up ,hange gear $o define an ob+ect's behavior you create methods.

3. What are ob+ects? Ans.

ow are they created from a class?

#n ob+ect in +ava is a block of memory that contains a space to store all the instance variables. #s with real-world ob+ects, software ob+ects have state and behavior. "n programming terms the state of an ob+ect is determined by its data 1variables2& the behavior by its methods. $hus a software ob+ect combines data and methods into one unit. ,reating an ob+ect is referred to as instantiating an ob+ect. $he creating ob+ect to a class is two-step processD. K. 0eclare a variable of class type. $his variable does not define an ob+ect instead it is a simply a variable that can refer to an ob+ect. <hysical copy of the ob+ect is created and assigned to that variable.

4. ow is a method defined? Ans. # method is a group of programming language statements that are given a name. # method is associated with a particular class. $he syntax of a method is modifier1s2 return-type method-name 1parameter-list2 @ statement-list A

5. When do we declare a member of a class static? Ans. # member of a class can be created that can be used without referencing to a specific instance. ;uch a member is created by preceding its declaration with the keyword static. # member declared as static can be accessed without referencing to any other ob+ects of class and before creating any ob+ects of its class. 5ethods and variables both can be declared as static. $he most common example of static member, main12 is declared static as it is called before any ob+ects exist. #ll instance variables that are declared as static are global variables.

6. What is a constructor? What are its special properties? Ans. $he central player in ob+ect initiali)ation is the constructor. "n Java, constructors are similar to methods, but they are not methods. *ike a method, a constructor has a set of parameters and a body of code. ?nlike methods, however, constructors have no return type. *ike methods, you can give access specifiers to constructors, but unlike methods, constructors with public, protected, or package access are not inherited by subclasses. 1#lso, instead of determining the ability to invoke a method, the access level of a constructor determines the ability to instantiate an ob+ect.2 $he special properties of a constructor are-

,onstructor- names are the same as the name of the class. ,onstructor does not specify a return type.

7. ow do we invoke a constructor? Ans. $he name of the constructor needs to be same as the name of class in which the constructor is declared. 'or example, to define a )ero-parameter constructor for the /ox class, you would write the following%o return type specified ,onstructor name is the same as class name

public /ox 1 2 @ ... A 3ou can invoke the constructor box12 by writing /ox b M new /ox12& $o create a box instance, you deploy the new keyword with the class name and a pair of parentheses, as shown in the following expressionB-- Geyword B--,lass name

new box1 2

/. What is inheritance and how does it help us create new classes :uickly? Ans. "nheritance refers to the properties of a class being available to other classes as well. $he original class is called /ase ,lass and 0erived classes are classes created from the existing class 1/ase ,lass2. "t will have all the features of the /ase class. $he concept of inheritance is very important in ob+ect-oriented programming languages. "t simplifies code writing thus making programs easier to maintain and debug. "t allows reusability of the code # subclass is defined as followsclass subclass extends superclass @ 9ariables declaration& 5ethods declaration& A $he keyword extends signifies that the properties of the superclass are extended to the subclass. $he subclass will now contain its own variables and methods as well those of the superclass. $his kind of situation occurs when we want to add some more properties to existing class without actually modifying it.

0. 0escribe different forms of inheritance with examples. Ans. $he two forms of inheritance areD. K. ;ingle- level inheritance 5ultiple- level inheritance

Sin%le:.e3el (nheritan"e2 "n this form of inheritance, there is only one subclass as an extended subclass of the superclass. # subclass is defined as follows class subclass extends superclass @ 9ariables declaration& 5ethods declaration& A $he keyword extends signifies that the properties of superclass are extended to the subclass. $he subclass will now contain its own variables and methods as well those of the superclass. $his kind of situation occurs when we want to add some more properties to existing class without actually modifying it. import +ava.io.B& ((super class declaration class book @ ;tring name& int id& void showsuper1 2 @ ;ystem.out.println14the id and name of the book is -4 CidC 4 4 A A class bookD extends book @ ;tring author& void showderived1 2 @ ;ystem.out.println14the author name is-4 Cauthor2& A A class simpleinhertence @ public static void main1;tring argsE F2 @ book superobMnew book1 2& bookD subob+ M new bookD1 2& superob.idMDI& superob.nameM4+ava4& ;ystem.out.println14the contents of super ob+ect is42& superob.showsuper1 2& ;ystem.out.println1 2& subob+.idMKI& subob+.nameM4c programming4& subob+.authorM4/alaguruswamy4& ;ystem.out.println14the contents of the subob+-42& subob+.showsuper1 2& subob+.showderived1 2& A A Cname2&

>esult$he contents of super ob+ect is $he id and name of the book is- DI +ava $he contents of the subob+$he id and name of the book is - KI c programming $he autor name is- ;wamy ultiple:.e3el (nheritan"e2 "n this form of inheritance, subclass is further extended. $his means, that there are subclasses of a subclass. $he general form of class declaration that further inherits the subclass is shown hereclass subclass-name extends superclass-name @ body of the class A class subclass-nameD extends subclass-name @ body of the class A 'or example, the following program shows the multiple inheritance. import +ava.io.B& ((super class declaration class book @ ;tring name& int id& void showsuper1 2 @ ;ystem.out.println14the id and name of the book is -4 CidC 4 4Cname2& A A class bookD extends book @ ;tring author& void showderived1 2 @ ;ystem.out.println14the author name is-4 Cauthor2& A A class bookK extends bookD @ void showderivedD1 2 @ ;ystem.out.println14$his is multilevel inheritance42& A A class simpleinhertence @ public static void main1;tring argsE F2 @ book superobMnew book1 2& bookD subob+ M new bookD1 2&

bookK subob+D M new bookK1 2& superob.idMDI& superob.nameM4+ava4& ;ystem.out.println14the contents of super ob+ect is42& superob.showsuper1 2& ;ystem.out.println1 2& subob+.idMKI& subob+.nameM4c programming4& subob+.authorM4/alaguruswamy4& ;ystem.out.println14the contents of the subob+-42& subob+.showsuper1 2& subob+.showderived1 2& subob+D.showdeivedD12& AA

11. 0esign a class to represent a bank account. "nclude the following member0ata members %ame of the depositor #ccount %umber $ype of account /alance amount in the account 5ethods $o assign initial values $o deposit an amount $o withdraw an amount after checking balance $o display the name and balance Ans. import +ava.io.B& public class /ank @ ;tring name& ;tring acc%o& ;tring acc$ype& double balanceMI& ;tring amount& public void input12 @ try@ /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& ;ystem.out.println146nter the %ame of a #ccount older42& nameMbr.read*ine12& ;ystem.out.println146nter the #ccount %umber of a #ccount older42& acc%oMbr.read*ine12& ;ystem.out.println146nter the #ccount $ype of a #ccount older42&

acc$ypeMbr.read*ine12& ;ystem.out.println146nter the #mount to be deposited42& amountMbr.read*ine12& double balanceM0ouble.parse0ouble1amount2& A catch1"!6xception g2@A A public void deposit12 @ try@ /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& ;ystem.out.println146nter the #mount to be deposited42& amountMbr.read*ine12& double amtM0ouble.parse0ouble1amount2& balanceMbalanceCamt& ;ystem.out.println14/alance- 4Cbalance2& A catch1"!6xception e2@A A public void withdraw12 @ try@ /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& ;ystem.out.println146nter the #mount to be withdrawl42& amountMbr.read*ine12& double amtM0ouble.parse0ouble1amount2& balanceMbalance-amt& ;ystem.out.println14/alance- 4Cbalance2& A catch1"!6xception e2@A A public void display12 @ ;ystem.out.println14#ccount older 0etails42& ;ystem.out.println14----------------------42& ;ystem.out.println14%ame4Cname2&

;ystem.out.println14/alance- 4Cbalance2& A public static void main1;tring aEF2 @ /ank ob+ectMnew /ank12& while1true2 @

;ystem.out.println145enu42& ;ystem.out.println14D. 6nter 0etails42& ;ystem.out.println14K. 0eposit #mount42& ;ystem.out.println14Q. Withdraw #mount42& ;ystem.out.println14P. 6xit42& try@ /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& ;ystem.out.println146nter the #mount to be withdrawl42& char chM1char2br.read12& switch1ch2 @ case 'D'ob+ect.input12& break& case 'K'ob+ect.deposit12& break& case 'Q'ob+ect.withdraw12& break& case 'P';ystem.exit1I2& A A catch1"!6xception e2@A A A A 11. #ssume that a bank maintains two kinds of account for its customers, one called savings account and the other current account. $he savings account provides compound interest and withdrawal facilities but no che:ue book facility. $he current account provides che:ue book facility but no interest. ,urrent account holders should also maintain a minimum balance and if the balance falls below this level, a service charge is imposed. ,reate a class #ccount that stores customer name, account number and the type of account. 'rom this derive the classes ,urr-acct and ;av-acct to make them more specific to their re:uirements. "nclude the necessary methods in order to achieve the following tasksAns. import +ava.io.B& class #ccount@ ;tring cust%ame& ;tring acc%o& ;tring amount& double balance& public void input12@ try@ /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22&

;ystem.out.println146nter the %ame of a #ccount older42& cust%ameMbr.read*ine12& ;ystem.out.println146nter the #ccount %umber of a #ccount older42& acc%oMbr.read*ine12& ;ystem.out.println146nter the #mount to be deposited42& amountMbr.read*ine12& balanceM0ouble.parse0ouble1amount2& Acatch16xception g2@A A public void deposit12@ try@ /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& ;ystem.out.println146nter the #mount to be deposited42& amountMbr.read*ine12& double amtM0ouble.parse0ouble1amount2& balanceMbalanceCamt& ;ystem.out.println14/alance- 4Cbalance2& Acatch1"!6xception e2@A A public void withdraw12 @ try@ /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& ;ystem.out.println146nter the #mount to be withdrawl42& amountMbr.read*ine12& double amtM0ouble.parse0ouble1amount2& balanceMbalance-amt& ;ystem.out.println14/alance- 4Cbalance2& Acatch1"!6xception e2@A A public void display12@ ;ystem.out.println14#ccount older 0etails42& ;ystem.out.println14----------------------42& ;ystem.out.println14%ame4Ccust%ame2&

;ystem.out.println14/alance- 4Cbalance2& A A class ,urrent extends #ccount@ public void che:uebook12@ if1balance7DIII2 ;ystem.out.println14,he:ue book has not been issued42& else ;ystem.out.println14,he:ue book has been issued42& A

public void minimum/al12@ double penaltyMDIII& if1balance 7 DIIII2@ balanceMbalance-penalty& A A public void display12@ minimum/al12& super.display12& A A public class ;aving extends #ccount@ public void cal"nterest12@ double interestMI& ;ystem.out.println1interest2& balanceMbalanceB5ath.pow1D.IS, K2& ;ystem.out.println1balance2& A public void display12@ cal"nterest12& ;ystem.out.println1balance2& super.display12& A public char menu12@ char choiceM'a'& ;ystem.out.println145enu42& ;ystem.out.println14D. ,urrent #ccount42& ;ystem.out.println14K. ;avings #ccount42& ;ystem.out.println14Q. 6xit42& ;ystem.out.println146nter your choice1D-Q242& try@ /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& choiceM1char2br.read12& Acatch16xception e2@ ;ystem.out.println146rror42& A if 1choice MM'Q'2@ return choice& A public static void main1;tring aEF2@ char choice& ;aving oMnew ;aving12& ;ystem.exit1I2&A

while1true2@ choice M o.menu12& try@ switch1choice2@ case 'D',urrent ob+ectMnew ,urrent12& while1true2@ ;ystem.out.println145enu42& ;ystem.out.println14D. 6nter 0etails42& ;ystem.out.println14K. 0eposit #mount42& ;ystem.out.println14Q. Withdraw #mount42& ;ystem.out.println14P. 0isplay /alance42& ;ystem.out.println14S. "ssue ,he:ue/ook42& ;ystem.out.println14H. 6xit42& try@ ;ystem.out.println146nter your choice1D-H242& /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& char chM1char2br.read12& switch1ch2@ case 'D'ob+ect.input12& break& case 'K'ob+ect.deposit12& break& case 'Q'ob+ect.withdraw12& break& case 'P'ob+ect.display12& break& case 'S'ob+ect.che:uebook12& break& case 'H'choice M o.menu12& default;ystem.out.println14<lease 6nter the valid choice42& break& A Acatch1"!6xception e2@A A case 'K'-

;aving ob+ectDMnew ;aving12& while1true2@ ;ystem.out.println145enu42& ;ystem.out.println14D. 6nter 0etails42& ;ystem.out.println14K. 0eposit #mount42& ;ystem.out.println14Q. Withdraw #mount42& ;ystem.out.println14P. 0isplay /alance42& ;ystem.out.println14S. 6xit42& try@ ;ystem.out.println146nter your choice1D-P242& /uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& char chM1char2br.read12& switch1ch2@ case 'D'ob+ectD.input12& break& case 'K'ob+ectD.deposit12& break& case 'Q'ob+ectD.withdraw12& break& case 'P'ob+ectD.display12& break& case 'S'o.menu12& default;ystem.out.println14<lease enter the valid choice42& break& A A A case 'Q'(( ;ystem.out.println14<lease enter the valid choice42& ;ystem.exit1I2& break& A ((switch A catch16xception e2@A A ((while A ((main A catch16xception e2@A

Solutions to Chapter 8ine Questions 1. What is an array? Ans. #n array is a se:uence of logically related data items. "t is a kind of row made of boxes, with each box holding a value. $he number associated with each box is the index of the item. 6ach box can be accessed by, first box, second box, third box, and so on, till the nth box. $he first box, or the lowest bound of an array is always )ero, which means, the first item in an array is always at position )ero of that array. <osition in an array is called index. ;o the third item in an array would be at index K 1I, D,K2.

2. Why are arrays easier to use compared to a bunch of related variables? Ans. #n array is a se:uence of logically related data items. "t is a kind of row made of boxes, with each box holding a value. #rrays have following advantages over bunch of related variables-

#rrays of any type can be created. $hey can have one or more dimensions. #ny specific element can be indexed in an array by its index. #ll like type variables in an array can be referred by a common name.

3. Write a statement to declare and instantiate an array to hold marks obtained by students in different sub+ects in a class. #ssume that there are up to HI students in a class and there are N sub+ects. Ans. int marksEFEFMnew intEHIFENF

4. 'ind errors, if any, in the following code segmentsint m& int xE F Mint EDIF& int E F y Mint EDDF& for 1mMD&m7MDI& CCm2 xEmFMyEmFMm& xMyMnew intEKIF& for 1mMI& m7DI& CCm2 ;ystem.out.println1xEmF2 Ans. $he errors in the above statements are mentioned as comments as followsint m& int xE F Mint EDIF& ((array created without using new keyword int E F y Mint EDDF& (( array created without using new keyword for 1mMD&m7MDI& CCm2 xEmFMyEmFMm& ((array can not be assigned values before they are created. xMyMnew intEKIF& for 1mMI& m7DI& CCm2 ;ystem.out.println1xEmF2

5. #n election is contested by S candidates. $he candidates are numbered D to S and the voting is done by marking the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast for each candidate using an array variable count. "n case, a number read is outside the range D to S, the ballot should be considered as a 'spoilt ballot' and the program should also count the number of spoilt ballots.

Ans. import +ava.io.B& public class 6lection @ int count, i, candidateD, candidateK, candidateQ, candidateP, candidateS, spoilt& public 6lection12@ count M I& i M I& candidateD M I& candidateK M I& candidateQ M I& candidateP M I& candidateS M I& spoilt M I& A public void election,ount12@ while1true2@ try@ ;ystem.out.println146nter integer between D to S to vote a candidate42& /uffered>eader br M new /uffered>eader1new "nput;tream>eader1;ystem.in22& i M "nteger.parse"nt1br.read*ine122& if 11i8S2WW1i7D22@ ;ystem.out.println146nter a valid vote id between D to S42& spoiltCC& countCC& Aelse if1iMMD2@ candidateDCC& countCC& Aelse if1iMMK2@ candidateKCC& countCC& Aelse if1iMMQ2@ candidateQCC& countCC& Aelse if1iMMP2@ candidatePCC& countCC& Aelse if1iMMS2@ candidateSCC& countCC& A ;ystem.out.println14;poilt M 4Cspoilt2& ;ystem.out.println14,andidateD M 4CcandidateD2& ;ystem.out.println14,andidateK M 4CcandidateK2&

;ystem.out.println14,andidateQ M 4CcandidateQ2& ;ystem.out.println14,andidateP M 4CcandidateP2& ;ystem.out.println14,andidateS M 4CcandidateS2& ;ystem.out.println14$otal - 4Ccount2& ;ystem.out.println140o you want to continue1y(n2- 42& char ch M 1char2br.read12& if1ch MM 'n'WWch MM '%'2 break& Acatch16xception e2@;ystem.out.println146rror42&A A A public static void main1;tring argEF2@ 6lection e M new 6lection12& e.election,ount12& A A

6. $wo matrices that have the same number of rows and columns can be multiplied to produce a third matrix. ,onsider the following two matrices.

a11 a 12 ############# a 1n $ 11 $ 12 ############# $ 1n % = a 21 a 22 ############# a 2n " = $ 21 $ 22 ############# $ 2n a n1 a n2 ############# a nm $ n1 $ n2 ############# $ nm


$he product of # and / is a third matrix , of si)e b by n where each element of , is given by the following e:uation.

(i& = a1' $'&


' =1

7. Write a program that will read the values of elements of # and / and produce the product matrix ,. Ans. import +ava.io.B& class 5atrix5ult @ int mMI& int nMI& int aEFEFMnew intEQFEQF& int bEFEFMnew intEQFEQF& int iMI& int +MI& int kMI& int term& public 5atrix5ult12 @ try @

/uffered>eader brMnew /uffered>eader1new "nput;tream>eader1;ystem.in22& ;ystem.out.print146nter the value of m and n for a matrix- Ln42& ;ystem.out.print14Lnm- 42& int m M"nteger.parse"nt1br.read*ine122& ;ystem.out.print14Lnn- 42& int n M"nteger.parse"nt1br.read*ine122& ;ystem.out.print14Ln6nter first matrix elements1mxn2Ln42&

(B "nput the first matrix B( for1iMI&i7m&iCC2 @ ;ystem.out.print14Ln6nter the row numbers-Ln42& for1+MI&+7n&+CC2 aEiFE+F M "nteger.parse"nt1br.read*ine122&

A ;ystem.out.print14Ln6nter second matrix elements1nxm2Ln42& (B "nput the second matrix B( for1+MI&+7n&+CC2 @ ;ystem.out.print14Ln6nter the row numbers-Ln42& for1kMI&k7m&kCC2 bE+FEkF M "nteger.parse"nt1br.read*ine122& A (B 5ultiplication of two matrices B( ;ystem.out.print14Ln5ultiplication of the two matrix is- LnLn42& term M I& for1iMI&i7m&iCC2 @ for1kMI&k7m&kCC2 @ termMI& for1+MI&+7n&+CC2 @ term M term C 1aEiFE+FBbE+FEkF2& (( multiplication A ;ystem.out.print14Lt42& ;ystem.out.print1term2& ;ystem.out.print14 42& A ;ystem.out.print14Ln42& A Acatch16xception e2 @ ;ystem.out.println146xception is -4Ce2& A A public static void main1;tring argsEF2 @ 5atrix5ult 55 M new 5atrix5ult12& A A

/. ow does ;tring class differ from the ;tring/uffer class? Ans. ;tring class has a limit while there is no limit in ;tring/uffer class. "n the ;tring/uffer class input is flushed while it is not so in the ;tring class.

;tring is an array whose all elements are of character type. ;tring class is used in the same manner that we might use any other predefined class. 'or example we might declare an instance of the ;tring class as follows;tring name M new ;tring12&

0. 6xplain abouti2 ,omparison of two strings ii2 ,oncatenation of two strings

Ans. i2 ,omparison of two strings $o compare two strings for e:uality, use e:uals12. "t has the general formboolean e:uals1ob+ect str2& ere, str is the string ob+ect being compared with the invoking ;tring ob+ect. "t returns true if the string contains the same characters in the same order compare$o1 2 !ften, it is not enough to simply know whether two strings are identical. 'or sorting applications, we need to know which is less than, e:ual to, or greater than the next. $he compare$o1 2 method of the ;tring class serves this purpose. "t has the general form of compare$o1;tring str2. Value value le&& t3an 5ero greater t3an 5ero 6ero Meaning t3e %nvo/%ng &tr%ng %& le&& t3an &tr t3e %nvo/%ng &tr%ng %& greater t3an &tr t3e t+o &tr%ng are e7ual

,lass 6:uals0emo @ public static void main1;tring argsE F2 @ ;tring sDM4 ello4& ;tring sKM4 ello4& ;tring sQM4bye4& ;ystem.out.println14,!5<#>6 ;$>"%=;42& (( $he compare$o method ;ystem.out.println1sD C 4e:uals4 C sK C 4-84 C sD.e:als1sK22& ;ystem.out.println1sD C 4e:uals4 C sQ C 4-84 C sD.e:als1sQ22& (( ?sing the compare$o method within an if-else statement if 1nameD.compare$o1nameK2MMI2 ;ystem.out.println14the same42& else ;ystem.out.println14not the same42& A A

ii2 ,oncatenation of two strings ;tring manipulation is something we do :uite often in our applications. !ne of the simplest methods to concatenate two ;trings is by using the 'C' operator. $o append ;tring sK to sD we simply usesD CM sK

/ut Java provides more ways for concatenating ;trings. $he ;tring class contains a instance method named concat1;tring s2. $o add a new ;tring to a existing ;tring we would code something like thissD.concat1sK2& public class $est @ public static void main1;tring argE F2 @

(( defining two strings and printing them out ;tring sD M new ;tring14sachin42& ;tring sK M new ;tring14tendulkar42& ;ystem.out.println14'irst ;tring- 4 C sD2& ;ystem.out.println14;econd ;tring- 4 C sK2& (( adding the second string to the first and printing result sD M sD.concat1sK2& ;ystem.out.println14,oncatenated- 4 C sD2& A A !utput'irst ;tring- ;achin ;econd ;tring- $endulkar ,oncatenated- ;achin $endulkar

0. 6xplain the methodsi2 trim ii2 substring iii2 length Ans. i2 trim $he trim method returns a copy of the invoking string from which any leading and trailing white space has been removed. "t has the general form ;tring trim 1 2& class alt;tr@ public static void main 1;tring argsE F2 ;tring str M 4 ello4& ;tring strK M 4Java4& str M str.to?pper,ase12& strK M strK.to*ower,ase12& ;ystem.out.println 1str2& (( 6**! ;ystem.out.println 1strK2&(( +ava str M str.concat1strK2& (( str now e:uals 4 6**! +ava4 ;ystem.out.println 1str2& str M str.trim12& (( str now e:uals 4 6**!+ava4 @

;ystem.out.println 1str2& str M str.substring 1S,str.length122& (( str M 4+ava4 ;ystem.out.println 1str2&

str M str.replace 1'a', 'i'2& (( str M 4+ivi4 ;ystem.out.println 1str2& A A

ii2 substring $he sub;tring method is used to create new instances of the class ;tring from existing instances. $he new string is specified by giving the re:uired index range within the existing string. ;tring substring1int start"ndex2 $his returns the sub string that starts at start"ndex and runs to the end of the invoking string. ;tring substring1int start "ndex, int end"ndex2 $his returns the substring that starts at startindex and runs through end"ndex-D&

iii2 length $he length of a string is the number of characters that it contains. $o obtain this value call a length method. int length12& class str,mp @ @

public static void main 1;tring argsE F2 ;tring str M 4 ello4& ;tring strK M 4Java4&

;ystem.out.println 1str.e:uals1strK22& (( false ;ystem.out.println 1str.compare$o1strK22& (( a negative number, i.e. str is less than strK ;ystem.out.println 1str.char#t1I22& (( , i.e. char is position I

;ystem.out.println 1str.length12 C strK.length122& (( S C P M R A A Solutions to Chapter Ten Questions 1. What is a $hread? Ans. "n a thread based multitasking environment, thread is the smallest unit of dispatchable code. # $hread is a single stream of execution within a process. $his means that a single program can perform two or more tasks simultaneously. 'or instance a text editor can format text at the same time that it is printing.

2. 0istinguish between 5ultiprocessing and 5ultithreading. Ans. 5ultiprocessing- >efers to a computer system's ability to support more than one process 1program2 at the same time. 5ultiprocessing operating systems enable several programs to run concurrently 5ultiprocessing systems are much more complicated than single-process systems because the operating system must allocate resources to competing processes in a reasonable manner. 5ultithreading - $he ability of an operating system to execute different parts of a program, called threads, simultaneously. $he programmer must carefully design the program in such a way that all the threads can run at the same time without interfering with each other.

3. 0escribe the life cycle of a $hread? Ans.

$hread exists in several states. # thread that has been +ust created is in the born state. $he thread remains in this state until the thread's start method is called. $his causes the thread to enter the runnable 1ready2 state when the system assigns a processor to the thread. # thread enters the dead state when its run method completes or terminates for any reason. When a sleep method is called in a running thread, that thread becomes ready after the designated sleep time expires. 6ven if a processor is available, sleeping thread cannot use it. # running thread can enter a blocked state. !ne common way is when thread issues an input(output re:uest. "n this case, a blocked thread becomes ready when the "(! it is waiting for completes. When a running thread calls wait, the thread enters a waiting state for the particular ob+ect on which 'wait' was called. # thread in the 'waiting' state for a particular ob+ect becomes ready on a call to 'notify' issued by another thread associated with that ob+ect. # thread enters the 'dead' state when its 'run' method is either completed or throws an uncaught exception.

4. What is ;ynchroni)ation? Why do we use it? Ans. 5ultithreading introduces a synchronous behavior in programs. $here is a need to enforce synchronicity when it is necessary. 'or example, if two threads are to communicate and share a data structure, there is a need to avoid conflict between them. $hat is, a thread must be prevented from writing data while the other thread is reading the data. $o overcome this problem, Java implements a model of interprocess communication called monitor. $he monitor is a control mechanism that can hold only one thread at a time. !nce a thread enters a monitor, all other threads have to wait until that exits from the monitor.

5. ow is a thread created? Ans. $hreads are implemented in the form of ob+ects that contain a method called run1 2. $he run12 method makes up the entire body of the thread. # typical run1 2 would appear as followspublic void run12 @ ------------------------------ 1;tatements for implementing thread2 --------------A $he run12 method should be invoked by an ob+ect at the concerned thread. # new thread can be created in two ways-

0efine a class that implements >unnable interface. 0efine a class that extends $hread class.

Solutions to Chapter #le3en Questions 1. What is a package? Ans. <ackages are containers for classes that can be shared by Java programs. <ackages are stored in a hierarchical manner and are explicitly imported into new class definitions. <ackages are Java's way of grouping a variety of classes and(or interfaces together. $he grouping is done according to functionality. /y organi)ing the classes into packages, we get the following benefits-

,lasses contained in packages of other programs can be reused. $wo classes in two different packages can have the same name. <ackages provide a way to hide classes. 0esigning is separated from coding by the use of packages.

2. Write a procedure to create your own package. Ans. $he procedure to create you own package is-

package 7packageJname8

0eclare the package at the beginning of a file using the package keyword. 0efine the class that is to be put into the package and declare it public. ,reate the subdirectory under the directory where the main source file is stored. ;tore the listing as the classJname.+ava file in the subdirectory.

3. 0efine interface. ow can multiple inheritance be implemented using interfaces? Ans. "nterfaces are syntactically similar to classes but they lack instance variables, and their methods are without any body. !nce an interface is defined, any number of classes can implement it. #n interface only defines a method's name, return type, and arguments. "t does not include executable code. #n interface is defined using the interface keyword. Java does not support multiple inheritance. $his means that classes in Java cannot have more than one superclass. owever, there could be a situation where a class needs to inherit from more than one class. "n such a situation you use interfaces. !ne class can implement any number of interfaces.

Solutions to Chapter Twel3e Questions 1. What is an exception? Ans. #n exception is a run time error. 5ost of the computer languages do not support exception handling. 6rrors must be checked and handled manually. $his is cumbersome and troublesome. Java provides the facility of exception handling and avoids the above problems. /y this run time error management becomes easy. # Java exception is an ob+ect that describes an error condition that has occurred in a piece of code. When an error or an exceptional condition arises, an ob+ect representing that exception is created and is 'thrown' in the method that caused the error. $he method may handle the exception itself or pass it on. "n this way, the exception is caught and processed. 6xceptions thrown by Java relate to fundamental errors that violate the rules of the language.

2. ow do we define a try block? Ans. $he programmer encloses in a try block the code that may generate an exception. $he try block is immediately followed by )ero or more catch blocks. 6ach catch block specifies the type of exception it can catch and contains an exception handler. When an exception is thrown, program control leaves the try block and catch blocks are searched for an appropriate handler. 'or example, the following code defines a try block. try @ (( monitor a block of code dMI& aMPK(d& ;ystem.out.println1B$his will not be printed,B2& A

3. ow do we define a catch block? Ans. $he 'try' block is immediately followed by )ero or more catch blocks. 6ach catch block specifies the type of exception it can catch and contains an exception handler. When an exception is thrown, program control leaves the try block and catch blocks are searched for an appropriate handler. 'or example, the following code defines a try-catch block. try @ (( monitor a block of code dMI& aMPK(d& ;ystem.out.println1B$his will not be printed,B2& A catch1#rithmetic6xception e2 @ ;ystem.out.println140ivision by )ero42& A 4. ow many catch blocks can we use with one try block? Ans. $he try block is immediately followed by )ero or more catch blocks. "t means you can use as many catch blocks with one try block. /ut there must be at least one catch block following a try block, unless you are using a finally block. 'or example, consider the following program,lass 6xception @ <ublic ;tatic void main1string argsE F 2@ int d,a& try @ (( monitor a block of code dMI& aMPK(d& ;ystem.out.println1B$his will not be printed,B2& A catch1#rithmetic 6xception2 @ (( ,atch divide-by-)ero error ;ystem.out.println1B0ivision by [eroB2& A ;ystem.out.println1B#fter catch statement.B2& A A

$his program generates the following output 0ivision by [ero. #fter ,atch ;tatement.

5. What is a finally block? When and how is it used? =ive a suitable example. Ans. #fter the last catch block, an optional finally block provides code that always executes regardless of whether or not an exception occurs. "f there are no catch blocks following a try block, the finally block is re:uired. "f a finally block appears after the last catch block, it is executed regardless of whether or not an exception is thrown. 'or example, the following program shows the use of a finally block. class finaldemo

@ static void #12 @ try @ ;ystem.out.println1 4now in #42& throw new >untime6xception14demo42& A finally @ ;ystem.out.println14final#42& A A public static void main1;tring argsEF2 @ try @ #12& A catch1 6xception e2 @ ;ystem.out.println14exc caught42& A A A

Solutions to Chapter Thirteen Questions 1. What is a file? Why do we re:uire files to store data? Ans. 'ile is a collection of information, such as text, data or images saved on a storage device such as a disk or hard drive. !utput from a program may go to screen or the printer, which will not be permanently stored. "n order to store the data permanently we re:uire files to store the data.

2. What is a stream? Ans.

ow is the concept of streams used in Java?

# stream in Java is a path along which data flows 1like a river or a pipe along which water flows2. "t has a source 1of data2 and a destination 1for that data2. /oth the source and the destination may be physical devices or programs or other streams in the same program. Java uses the concept of streams to represent the ordered se:uence of data, a common characteristic shared by all the input(output devices as stated above. # stream presents a uniform, easy-to-use, ob+ect-oriented interface between the program and the input(output devices.

3. What are input and output streams? 6xplain them with illustrations. Ans.

#s you know, all Java programs automatically import the +ava.lang package. $his package defines a class called ;ystem, which encapsulates several aspects of the run-time environment. ;ystem.out refers to the standard output stream. /y default, this is the console. ;ystem.in refers to standard input, which is the keyboard by default. ;ystem.err refers to the standard error stream, which also is the console by default. owever, these streams may be redirected to any compatible "(! device. ;ystem.in is an ob+ect of type "nput;tream& ;ystem.out and ;ystem.err are ob+ects of type <rint;tream. $hese are byte streams, even though they typically are used to read and write characters from and to the console. #s you will see, you can wrap these within character-based streams, if desired.

4. What is a stream class? ow are the stream classes classified? Ans. $he +ava.io package contains a large number of stream classes that provide capabilities for processing all types of data. $hese classes may be categori)ed into two groups based on the data type on which they operate.

/yte stream classes that provide support for handling "(! operations on bytes. ,haracter stream classes that provide support for managing "(! operations on characters.

$hese two groups may further be classified based on their purpose. /yte stream and character stream classes contain speciali)ed classes to deal with input and output operations independently on various types of devices. We can also cross-group the streams based on the type of source or destination they read from or write to. $he source 1or destination2 may be memory, a file or pipe.

Você também pode gostar