53
Introduction to Java Java is popular third generation programming language which can be used to do any of the thousands of things that computer software can do. It is both a programming language & a platform (combination of hardware & software) Program is a set of instructions given to a computer. The program or code written by a programmer is usually called the Source code. Process of converting a source code into machine code is called compilation. Compiler is a translator which translates the program all at once into machine code Interpreter is a translator which translate the program into machine code instruction by instruction Java programs are compiled into Java byte code Java virtual machine is an abstract machine which is implemented on the top of existing processors Java byte code is a machine instruction for a Java processor chip called Java virtual machine. The byte code is independent of the computer system it has to run upon Java API (Application program Interface) are libraries of compiled code that can be used in your programs. It consists of functions and variables that programmers are allowed to use in their applications. Characteristics of Java Write once run anywhere - The java programs need to be written just once which can be run on different platforms without making changes in the Java program. Light weight code - With java big and useful applications can also be created with very light code. No huge coding is required. Security - Java offers many security features to make its programs safe and secure. Built-in graphics - Java offers many built in graphics features and routines which can be used to make Java application is more visual Java is object oriented language thereby very near to the real world Platform independent - Java is essentially platform independent. Change of platform does not affect the original Java program/ application Open product - Java is open product freely available to all. Architecture Neutral-The compiler generates an architecture neutral object file format- the compiled code is executable on many processors, given the presence of the java run time system. Concepts of Objects (Q&A)

Computers 2

Embed Size (px)

Citation preview

Page 1: Computers 2

Introduction to Java

Java is popular third generation programming language which can be used to do any of the thousands of things that computer software can do.It is both a programming language & a platform (combination of hardware & software)Program is a set of instructions given to a computer. The program or code written by a programmer is usually called the Source code.Process of converting a source code into machine code is called compilation.Compiler is a translator which translates the program all at once into machine codeInterpreter is a translator which translate the program into machine code instruction by instructionJava programs are compiled into Java byte codeJava virtual machine is an abstract machine which is implemented on the top of existing processorsJava byte code is a machine instruction for a Java processor chip called Java virtual machine. The byte code is independent of the computer system it has to run uponJava API (Application program Interface) are libraries of compiled code that can be used in your programs. It consists of functions and variables that programmers are allowed to use in their applications.Characteristics of JavaWrite once run anywhere - The java programs need to be written just once which can be run on different platforms without making changes in the Java program.Light weight code - With java big and useful applications can also be created with very light code. No huge coding is required.Security - Java offers many security features to make its programs safe and secure.Built-in graphics - Java offers many built in graphics features and routines which can be used to make Java application is more visualJava is object oriented language thereby very near to the real worldPlatform independent - Java is essentially platform independent. Change of platform does not affect the original Java program/ applicationOpen product - Java is open product freely available to all.Architecture Neutral-The compiler generates an architecture neutral object file format- the compiled code is executable on many processors, given the presence of the java run time system.

Concepts of Objects (Q&A)

1. How is an object implemented in software terms?Ans: An object is implemented in software terms as follows:

Characteristics/attributes are implemented through member variables or data items of the objectBehaviour is implemented through member functions called methodsData and methods are encapsulated into one unit and given a unique name to give it identity

2. What do you mean by Abstraction and Encapsulation? How are these two terms interrelated?

Page 2: Computers 2

Ans: Abstraction is the act of representing essential features without including the background details.Encapsulation is the act of combining both data and the functions that operate on the data under a single unit. Encapsulation, in a way, implements abstraction.

3. Encapsulation is one of the major properties of OOP. How is it implemented in software term?

Ans: Encapsulation is a way to implement data hiding and abstraction by wrapping up data associated functions into a single unit called object.An object binds together data and its associated functions under one unit thereby enforcing encapsulation as encapsulation means wrapping up of data and associated functions together into a single unit.

4. How do objects encapsulate state and behaviour?Ans: An object is an identifiable entity with some characteristics attributes and

behaviour. The state of an object depends upon the values of its attributes at any given point of time.Since state and behaviour of objects are interwoven, they are said to encapsulate state and behaviour. For instance, a car object has characteristics like number of wheels, seats, make etc. Its state is represented as halted, moving or stationary. And its behaviour is: it can move, stop, blow horn etc. Now all these things are wrapped up together in the form of ‘car’. We cannot segregate them. Thus, we can say that objects encapsulate their ‘state’ and ‘behaviour’.

5. What are methods? How are these related to an object?Ans: A method is an operation associated to an object. The behaviour of an

object is represented through associated functions, which are called methods.

6. What is a class?Ans: A class represents a set of objects that share common characteristics and

behaviour

7. What do you understand by an object factory?Ans: An object factory is a producer of objects. It accepts some information

about how to create an object such as values depicting its state, and then returns an instance of that object.

8. How can you say that a class is an object factory?Ans: Basically a class is an object maker or object factory. It contains all the

statements needed to create an object, its attributes as well as the statements to describe the operations that the object will be able to perform

9. How can you say that Java is both a programming language and a platform?

Ans: Like any other programming language, we can use Java to write or create various types of computer applications. The word platform generally is used to refer to some combination of hardware and system software. The Java platform is a new software platform designed to deliver and run highly interactive, dynamic and secure applications on networked computer systems.

Page 3: Computers 2

10. What do you understand by JVM?Ans: The Java Virtual Machine is an abstract machine designed to be

implemented on the top of existing processors. It hides the underlying operating system from Java applications. Programs written in Java are compiled into Java Byte Code which is then interpreted by a special Java Interpreter for a specific platform. This Java interpreter is known as the Java Virtual Machine

11. What is Write once Run anywhere characteristics of Java?Ans: The java programs need to be written just once, which can be run on

different platforms without making changes in the Java program. Only the Java interpreter is changed depending upon the platform. This characteristic is known as Write Once Run Anywhere

12. Define the keywords(i) Bytecode (ii) Java Virtual Machine (iii)Java API (iv) Internet Applet (v) Standalone application

Ans. (i) A machine instruction for a Java processor chip called Java Virtual Machine(ii) An abstract machine that hides underlying operating system from Java applications and executes the Java Byte code(iii) Java Application Programming Interface constitutes libraries of compiled code that can be used in Java Program.(iv) Small program embedded in a web page which runs on the viewer’s machine in a secured manner.(v) A program that can run independently without requiring external support.

13. Differentiate between operator and expression.Ans: An operator is a symbol that triggers an action

An expression is a group of tokens (identifiers, operator, keywords etc.) to represent/carry out some job/action.

14. What is a compound statement?Ans: A compound statement is a sequence of statements enclose within a pair

curly braces.

15. What is the purpose of the new operator?Ans: The new operator is used to create an object of a class and associate the

object with a reference variable that names it.

Constructors

1. (a) Differentiate between formal parameters and actual parameters (b) Why do we need constructor as a class member ?Ans: (a) Formal parameters are the list of parameters specified in the function prototype. These parameters accept the values passed to them by corresponding actual parameters.

Page 4: Computers 2

Actual parameters are the list of parameters specified in the statement that calls the function. These are the variables that actually store the value which is passed to the formal parameters and then are used in the function definition.

(b) A constructor is used to initialise values to the data members of the class upon object creation

2. What is a default constructor ?Ans: A constructor which does not accept any parameter’s values from the object when it gets created.

3. Which unit of class gets invoked when the object of a class is created?Ans: A constructor gets called when the object of the class is created.

4. What are the two types of constructors?Ans: The two types of constructors are default (non parameterised) and parameterised constructors

5. (a) How many constructors can a class have? (b) What is the implicit return type of a constructor ?Ans: (a) A class can have any number of constructors defined for itself provided that they differ in their arguments.(b) Constructors do not have any return type not even void because the implicit return type of a constructor is the class type itself

6. ‘ Only a function that has access to the constructor, can use the objects of this class. Comment on this statement.Ans: Since, every time an object is created, it is automatically initialized by the constructor of the class.Therefore, it is very much necessary for the function using an object that it must have access to the constructor of that class so that the object being defined could be properly constructed. Thus, a function not having access to constructor of a class cannot declare and use objects of that class.

7. What do you mean by temporary instance of a class? What is its use? How is it created?Ans: (a) A temporary instance of a class means an anonymous object(object having no name) of the same class and which is shortlived. (b) Its benefit is when an object is required only for very short time(say for an expression or a statement) we need not reserve memory for it for long. A temporary object for the same purpose can be created which remains in the memory as long as the statement defining it is getting executed. After the statement, this object is automatically destroyed and memory is released. Therefore, memory remains occupied only for the time when it is needed.(c)Temporary instance is created by explicit call to the constructor. For instance, following statement creates a temporary instance of Time type and invokes print() member function of Time class for it.

Time(10,12,30).print();

8. What is this keyword? What is its significance?Ans: The this keyword represents an object that invokes a member function. It stores the address of the object that is invoking a member function and it is an implicit argument to the member function being invoked.The this keyword is useful in returning the object(address) of which the function is a member.

Page 5: Computers 2

9. Differentiate between constructor and functionAns :

Constructor FunctionConstructor has the same name as the class

Functions do not have the same name as the class

Constructor has no return type Functions may have return type or the modifier void

Gets invoked when object is created Gets invoked when object calls for the method using dot operator

Used to initialise instance variables Used to perform a specific task.

The access of constructor should always be public

The access can be public, private protected

10. What is constructor overloading?Ans: The process having two or more constructors with different parameter list is called constructor overloading. Overloading improves the readability of the program and makes the language extensible.

11. What is a copy constructor?Ans: A copy constructor is a new object created with the same state as of another objectAbc obj2=obj1 // where obj1 is also an object of class Abc

Functions Q & A

1. Differentiate between actual parameters and formal parametersAns: Actual parameters are arguments passed to the function while calling the

function.Formal parameters are the parameters that receive the values from the actual parameters.

2. (i) What is the role of keyword void in declaring functions?(ii) If a function contains several return statements, how many of them

will be executed?(iii) Which OOP principle implements function overloading?

Ans: (i) void indicates that the function does not return any value(ii) only one return will be executed(iii) Polymorphism

3. Write advantages of using functions in programs.Ans: Advantages of using functions in programs are:

(i) functions lessen the complexity of programs(ii) functions hide the implementation details(iii) functions enhance reusability code

4. Differentiate between call by value and call by referenceAns: In call by value the called function creates its own workcopy for the

passed parameters and copies the passed values in it. Any changes that take place remain in the work copy and the original data remains intact.In call by reference, the called function receives the reference to the passed parameters and through this reference it accesses the original data. Any changes that take place are reflected in the original data.

Page 6: Computers 2

5. How are the following passed in Java? (i) primitive types (ii) reference typesAns: (i) call by value

(ii) call by reference6. Define an impure functionAns: An impure function is the function that changes/modifies the state of

received argument7. Explain the function of a return statementAns: The return statement is useful in two ways. First, an immediate exit from

the function is caused as soon as a return statement is encountered. Second use of return statement is that it is used to return a value to the calling code.

8. What does the term ‘side-effects’ refer to for a function in Java?Ans: A function or procedure in a programming language is said to have side-

effects if it makes changes to its environment. A side-effect really means that the function keeps some sort of hidden state inside it.

Control Flow statements

The selection statements allow to choose the set-of-instructions for execution depending upon an expression’s truth value. Java provides two types of selection statements: if and switchThe ? : is an alternative to if.Java has an operator that can be used as an alternative to if statement.Comparing if and ? :Compared to if-else sequence ? : offers more concise, clean and compact code but it is less obvious as compared to ifAnother difference is that the conditional operator ? : produces an expression and hence a single value can be assigned or incorporated into a larger expression, whereas, if is more flexible. The if statement can have multiple statements, multiple assignments and expressions (in the form of a compound statement) in its body.When ? : operator is used in its nested form, it becomes complex and difficult to understand. This form of ? : is generally used to conceal the purpose of code.The switch statementJava provides a multiple branch selection statement known as switch. This selection statement successively tests the value of an expression against a list of integer or character constants.The fall of control to the following cases of matching case is called Fall-throughSwitch Vs. if-else(Similarity)The switch and if-else both are selection statements and they both let you select an alternative out of given many alternatives by testing an expression.(Differences)The switch statement differs from the if statement in that switch can only test for equality whereas if can evaluate a relational or logical expression i.e. multiple conditions.The switch statement selects its branches by testing the value of same variable (against a set of constants) whereas the if-else construct lets you use a series of expressions that may involve unrelated variables and complex expressionsThe if-else is more versatile of the two statements. (if-else can handle ranges whereas switch cannot. Each switch case label must be a single valueThe if-else statement can handle floating point tests also apart from handling integer and character tests whereas switch cannot handle floating point tests

Page 7: Computers 2

The switch statement is more efficient choice in terms of code used in a situation that supports the nature of switch operationsA switch statement can only work for equality comparisonsNo two case labels in the same switch can have identical values.Switch statement works with integral typesThe switch statement is more efficient than if in a situation that supports the nature of switch operation

Control Flow(Theory Q& A)

1. What do you understand by ‘ dangling else ‘ ? How can one override the default ‘ dangling else ‘ ?.

Ans: The ambiguity that arises in a nested if statement due to more number of if than the number of else clauses is called as dangling else problem. A confusion is created with which if does the additional else clause matchup.

2. State at least two differences between ternary operator(? : ) and if statement.

Ans: ? : operator If else statement

Ternary operator can give only one value

If statement is flexible and can have more than one statement in a block

This operator is more concise, clean and compact but in its nested form it is more complex

If in its nested form is also not so complex

3. Explain ‘fall through’.Ans: In Java when the control of execution flows to the next case due to absence of break in a switch statement then it is called as fall through.(i.e.) the control falls to the cases following the matching case in the absence of break statement.

4. State the difference between if else and switch statement.Ans:

If else switchIf else can test relational and logical expression

If can test only equality

The value of more than one variable or expression can be compared to the value of more than one variable or expressions.

The value of the variable or of an expression is tested for equality against possible constants.

Range can be tested with the if else statement

Switch case labels are constants. So ranges cannot be tested.

Floating point tests can be performed.

Floating point test cannot be performed using switch case

Page 8: Computers 2

5. Name the data types that can be used as case constants in a switch statement.

Ans: Data types that can be used as case constant in a switch statement should be of any integral type. These include byte, char, short,int and long.

6. Why is it suggested to put a break statement after the last case statement in a switch even though it is not needed syntactically?

Ans: Syntactically it is not required to put a break after the last statement in a switch. Still it is suggested to put it there to avoid forgetting the break when another case statement is added at the end of switch in future i.e. for a good programming technique.

7. Why do we need if else statement in a program?Ans:Many times during programming we want to execute a statement or a set of statements only when a specific condition is true. So to take such decision we need if else statement in a program.

8. State the difference between selection and iteration construct.Ans:

Selection construct Iteration constructIn this construct a statement or a set of statement is either executed or skipped depending on the test condition.

In this construct a statement or a set of statements are executed repeatedly until a test condition becomes false.

Execution of a selected set of statements is maximum once.

Execution of a selected set of statements can be more than once.

9. What role do logical operators play in the functions of if statement ?Ans: Logical operators help in testing more than one condition using single if statement.

10. When do we prefer to use switch statement over if else statement although both are conditional statements.Ans: When the value of a variable or an expression is to be compared with the list of possible integer or character constants we prefer to use switch over if else.

Loops(Theory)

The iteration statements allow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iteration statements are also called loops or looping statements. Java provides three kinds of loops: for loop, while loop, and do-while loop.All three loop constructs of Java repeat a set of statements as long as specified condition remains true. This specified condition is generally referred to as a loop control.Elements that control a loop

A loop has four elements that have different purposes.(i) Initialisation Expression(s) The initialisation expression(s) gives the loop variable(s) their first value(s). It is executed only once , in the beginning of the loop.

Page 9: Computers 2

(ii) Test Expression. The test expression is an expression whose truth value decides whether the loop-body will be executed or not.(iii) Update Expression(s) The update expression(s) change the value(s) of loop variable(s). It is executed at the end of the loop after the loop-body is executed.(iv) The Body-of-the-Loop The statements that are executed repeatedly (as long as the test-expression is nonzero)form the body of the loop.

The for loop - fixed no. of iterations

The for loop is the easiest to understand of the Java loops. All its loop control elements are gathered in one place(at the top of the loop),while in the other loop construction of Java, they are scattered about the program.

The different variations of for loop are:

Multiple initialization and update Expressions. A for loop may contain multiple initialization and/or multiple update expressions, separated by commas.Optional expressions. In a for loop, initialization expression, test expression and update expression are optional i.e. you can skip any or all of these expressions.Infinite loop. An infinite or endless loop may be created by omitting the test-expressionEmpty loop. If a loop does not contain any statement in its loop-body it is said to be an empty loop.(often used for time delay or in pointer manipulations where you need to increment or decrement pointer position without doing anything else).

The While loop

In a while loop, a control variable should be initialized before the loop begins as an uninitialized variable can be used in an expression. The loop variable should be updated inside the body-of-the-while. A while loop can also have several variations. It can be empty loop or an infinite loop.

The do-while loop

Unlike the for and while loops, the do-while evaluates its test-expression at the bottom of the loop after executing its loop-body statements. This means that a do-while loop always executes at least once. The most common use of the do-while loop is in menu selection routine, where the menu is flashed at least once.

Two categories of Loops

Loop statements can belong to any of the following two categories:(1) Entry-controlled / Top-Tested / Pre-Tested loopsIn this class of loops, the loop condition is tested before entering in to the loop. If the test-condition evaluates to true, the loop body is executed. The loops belonging to this category are: for and while loops.(2) Exit-controlled/Bottom-Tested/ Post-Tested loopsIn this class of loops, the loop body is executed first and then the continuation condition is evaluated. The loop belonging to this category is do-while loop. These types of loops are useful when you want to execute the loop body at least once irrespective of the test-condition’s evaluation such as for displaying menu options.

Page 10: Computers 2

Nested loops

A loop may contain another loop in its body. This form of a loop is called nested loop. In this kind of loops, the inner loop must terminate before the outer loop.

Jump statements

The jump statements unconditionally transfer program control within a function. Java has three statements that perform an unconditional branch: return, break, and continue. In addition, to the above three, Java provides a standard library function System.exit() that helps you break out of a program.A break statement inside a loop will abort the loop and transfer control to the statement following the loop. A continue statement will just abandon the current iteration and let the loop start the next iteration.Both the statements skip over a part of the code. The break and continue statements can also be used with labels.Return statement is useful in two waysFirst, an immediate exit from the function is caused as soon as return statement is encountered and the central passes back to the Operating System which is functions caller.Second use of return statement is that it is used to return a value to the calling code

Loops(Theory Q & A)

1. State one similarity and one difference between while and do while loop.Ans: Similarity

These two loops while and do while are used in a situation when we do not know when the loop will terminate.

DifferenceWhile loop is an entry controlled loop, hence test expression is evaluated before the execution loop begins whereas do while loop is an exit controlled loop hence test expression is evaluated after the body of loop has been executed.

2. Explain the meaning of break and continue statements. Ans: break

This statement allows to skip a part of the program. It brings the control out of the loop to the statement immediately after the loop block in which break is contained. In case break is contained in a nested loop structure then it causes an exit from only the very loop it appears in.continueThis statement is similar to break in the sense that it also causes the control to skip few statements during the execution. But unlike break it skips the rest of the statements in the loop and takes the control to the next iteration.

3. What do you understand by multiple initialization expression in a for loop ? What is the use of comma(,) operator for the same ?Ans: In for loop the initialization along with the other control elements is on the top of the loop. This is separated from other control elements by a semi colon. In Java multiple initialization part we can have more than one initialization expression separated by commas.

Page 11: Computers 2

4. Explain labelled break statementAns: To cause the termination of loop at any height we use labelled break statement. In other words to bring the control of execution out of any loop we use labelled break. We use a labelled break statement when we want to break out of specific loop which is labelled by us, rather than breaking out of innermost loop.

5. Explain nested loop.Ans: A loop within a loop is called as nested loop. The second loop or the inner loop always ends before the end of the first loop or the outer loop. Criss crossing of loop is not allowed but nesting can be upto any desired depth.

6. Is the statement for(;;) legal or not? Give reasons for your answer.Ans: The statement for(; ; ) is legal and represents an infinite loop. It is legal because it satisfies the minimum condition necessary for a for loop to be correct syntactically. It executes null statement in the loop body and since the three control expressions are optional, they have been skipped.

Simple input in Java

The import statement identifies the packages and classes of the Java API that will be used in a program, so that the full package name is not necessary on each reference. It is a convenience to the programmer as it saves a lot of typing.Java programs perform I/O through streams.A stream is an abstraction that produces or consumes information. A stream is linked to a physical device by the Java I/O system. Java defines two types of streams: byte and character.Byte stream-8 bit (Ascii character set)Character stream-16 bit(Unicode character set)System.out refers to the standard output system. By default, this is the console. System.out is the object of PrintStream.System.in refers to the standard input which is Keyboard by default. System.in is an object of type InputStream.InputStream stores information about the connection between an input device and the computer or program.InputStreamReader translates data bytes received from InputStream objects into a stream of characters.BufferedReader buffers the input received from an InputStreamReader object.Exception HandlingContradictory or unexpected situations or unexpected errors during program execution is known as Exception.Way of handling anomalous situations in a program run is known as Exception handling.Creating /Using objectsObjects are created using the new operator along with the class ConstructorExampl: Point p1 = new Point(2,3)

Class obj operator Constructor(Arguments)Each object declaration statement has three parts

(i) Declaration: The code on the left of assignment operator(ii) Instantiation: A Java operator(new) that creates new object(allocates

space for it)

Page 12: Computers 2

(iii) Initialization: The new operator is followed by a call to constructor.

Advantages of Exception Handling(i) Exception handling separates error handling code from normal code.(ii) It clarifies the code and enhances readability(iii) It stimulates consequences as the error handling takes place at one

place and in one manner. It makes for clear,robust, fault-tolerant programs.

Raising of an imaginary error flag is called throwing an error.To intercept and thereby control an exception you use a try/catch/finally constructionKeyword throws is used to inform that an error has occurred. A throws clause lists the type of exceptions that a method might throw. Absence of throws clause will result in a compile time error.Java uses the try-catch-finally syntax to test a section of the code and if an error occurs in that region to trap the error.‘ Finally ‘ keyword is used to provide a block of code that is always performed regardless of whether an exception is signaled or not.

Math Functions

Method Description

Static double sin(double arg) returns the sine of the anglespecified by arg in radians

Static double cos(double arg) returns the cosine of the angleSpecified by arg in radians

Static double tan(double arg) returns the tangent of the angleSpecified by arg in radians

Static double exp(double arg) returns e to the arg.

Static double log(double arg) returns the natural logarithm of arg.

Static double pow( double y,double x) returns y raised to the x

Static double sqrt(double arg) returns the square root of arg.

*Static int abs(int arg) returns the absolute value of the arg

Static double ceil(double arg) returns the smallest whole number greater than or equal to arg.

Static double floor(double arg) returns the largest whole number less than or equal to arg

Page 13: Computers 2

*Static int max( int x,int y) returns the maximum of x and y.

*Static int min(int x, int y) returns the minimum of x and y.

Static double rint(double arg) returns the integer nearest in value to the arg.

*Static int round(float arg) returns arg rounded up to the nearest int.

Packages & Interfaces

Packages and interfaces are two basic components of a Java program. Packages are containers for classes that are used to keep the class

name space compartmentalized (i.e.) it allows us to create classes which can be stored in our own package without concern that it will collide with some other class name stored elsewhere .

Package is both a naming and a visibility control mechanism (i.e.) you can define classes inside a package that are not accessible by code outside that package.

To create a package include a package command as the first statement in a Java source file. The package statement defines a name space in which classes are stored. If you omit the package statement , the class names are put into default package.

Classes and packages are both means of encapsulating and containing the same space and scope of variables and methods.

Packages act as containers for classes and other subordinate packages.

Classes act as containers for data and code. Class is Java’s smallest unit of abstraction. Access specifiers provide a variety of ways to produce the many levels

of access required Public – can be accessed from anywherePrivate – cannot be seen outside of its class.Default/friendly/package level – visible to subclasses as well as to other classes in the same packageProtected - seen outside the current package, but only to classes that subclass the class directly.

Java includes the import statement to bring certain classes, or entire packages into visibility. It is a convenience to the programmer and is not technically needed to write a complete Java program.

Using an interface you can specify what a class must do but not how it does it.

An interface is a collection of constants and abstract methods1. What is the other name for instance variables?2. Which of the following statements is/are true.

(i) Within a class, static members can be accessed by static members only.

Page 14: Computers 2

(ii) Any change in the value of a static variable is not reflected in the objects of that class.

(iii) When you declare a method as static it cannot be accessed in another class without creating an object.

3. Mention the two aspects involved while declaring a variable4. Operations on primitive types based on operands can be categorized in

three ways. Name them.5. Which operator is an alternative to if… else?6. Which of the following variables is /are created when a method is called

and destroyed when a method finishes.(local, instance,class)

7. Mention two points of difference between String and StrinBuffer class8. What do you mean by scope and lifetime of a variable?9. Which of the following statements is/are true

(i) Two case constants in a switch case have identical values(ii) Switch statement can evaluate any type of boolean expression

10.On what factor does the result of mixed mode expression depend upon ?(The type of largest operand in the expression)

11.Which data types store single precision and double precision values? (float/double)

12.What is the advantage of single precision values over double precision values?(Single precision is faster on some processors and takes half as much space as double)

13.State two conditions under which an implicit conversion can be done.(Both types must be compatible, Destination type must be less than source type)

14.What will be the resultant expression which contains a character and an integer type?(integer)

15.What is the role of ‘final’ keyword?(for a variable the value of the variable remains constant throughout the program. For a class it cannot be inherited by any sub class even if you used extends keyword)

16.What is instantiation?(Process by which an object is created from given class template is called instantiation.

17.How is function overloading useful?(Function overloading supports polymorphism as it is the way java implements the “ one interface multiple methods “ paradigm. Overloading is useful as it allows related methods to be accessed by use of a common name.)

18.What are variables of class type known as?(objects)19.On what factor/factors does the size of a composite data type depend

upon?(The size of a composite data type depends upon the constituent member variables. It is generally the total of all sizes of its constituent member variables.)

20.Each object declaration has three parts. Name them21.What does the new operator return?(new operator returns a reference to

an object)22.What is the qualified name of a variable or object?(object.variable name)

Page 15: Computers 2

23.Define package(A collection of related classes providing access protection and namespace management)

24.State the purpose of the period (.) and comma (,) operators. (The dot operator is used to refer to the members of an object. Comma operator is used when multiple intialisations are to be done)

25.What is the return type for Math.round()?(int)26.Name any two overloaded Mathematical functions. (abs,max)27.What is data hiding?(The very insulation of the data from direct acces by

the program is termed as data hiding)28.State the differences and similarities between packages and classes.(class

– container of code and dataPackage- container of classes and sub classesBoth provide visibility controls and access protection)

29.What is NaN and infinity in java?(Nan stands for not a number)30.State the three ways in which a String object can be created in java.

(default constructor,passing an array of characters,passing as string as an argument)

Keywords(java)1. Abstraction The act of representing essential features without including

the background details or explanations2. Encapsulation Wrapping up of data and functions(that operate on the

data) into a single unit3. Object An identifiable entity with some characteristics and behaviour4. Method A member function representing some behaviour of an object5. Class Representation of a set of objects that share common characteristics

and behaviour 6. Object Factory A producer of objects that accepts some basic information

and creates objects based on this information7. Bytecode A machine instruction for a java processor chip called Java

Virtual Machine8. Java Virtual Machine(JVM) An abstract machine that hides underlying

operating system from Java applications and executes the Java byte code9. Java API Small program embedded in a web page which runs on the

viewer’s machine in a secured manner10.Standalone Applications A program that can run independently without

requiring external support.11.Constant( Literal ) A data item that never changes its value during a

program run12.Explicit type conversion User defined type conversion13.Expression Any valid combination of operators, constants and variables14.Identifier Name given by user for a part of the program15.Implicit type conversion Type conversion automatically carried out by the

compiler16.Integeral Promotion Conversion of shorter integeral types into bigger

integeral types17.Java shorthand A way of combining an arithmetic operator and and an

assignment operator

Page 16: Computers 2

18.Keyword Reserved word having special meaning and purpose19.Operator Symbol or keyword that represents a specific task20.String literal Sequence of characters enclosed in double quotes21.Token The smallest individual unit in a program22.Type Casting Explicit conversion of an operand to a specific type23.Type Conversion The process of converting one predefined type into

another24.Type Promotion Conversion of all operands upto the type of the largest

operand25.Actual Parameters Also called arguments. The variables or values passed

to a function26.Formal Parameters Also called parameters. The variables that receive the

incoming values in a function27.Function A named unit of a group of program statements28.Function call Statement invoking a function29.Function Declaration Also called function prototype. It is the statement

that declares a function‘s name,return type, number and type of its arguments

30.Function Declaration First line of function definition31.Function Definition A function declaration plus the statements in the body

of the function32.Constructor A member function having the same name as its class and

that initializes class objects with legal initial values33.Temporary Object An anonymous shortlived object34.This The keyword(which is actually a reference) storing the address of the

object currently invoking a member function35.Access specifier Way to control access of class members36.Composite data type Data type based on primitive datatypes37.User defined data type Data type created by the user38.Exception An anomalous situation encountered by the program39.Syntax error Programming language’s grammar rules violation error40.Compile time error Error that the compiler can find during compilation41.Run time error Error during program execution42.Accessor methods Methods used to obtain information about an object43.Java package Group of related classes and interfaces44.Fall through Execution of multiple cases after matching takes place in a

switch statement45.Global variable Class variable which is available to the entire class46.Local variable Variable declared inside a method or block47.Scope Region within which a variable/piece-of-code is accessible48.Selection statement Statement that allows to choose a set-of-instructions

for execution depending upon an expression49.Statement Instruction given to the computer to perform any kind of action50.Infinite loop A loop that never ends51.Iteration statement(Loop statement) Statement that allows a set of

instructions to be performed repeatedly

Page 17: Computers 2

52.Jump statement Statement that unconditionally transfers program control within a function

53.Nested loop A loop that contains another loop inside its body54.Array Collection of variables of the same type that are referenced by a

common name55.Base type Data type of array elements56.Index Also called subscript The number designating its position in array’s

ordering57.One dimensional array A list of finite number of homogeneous data

elements58.Two dimensional array An array in which each element is an array itself59.Unsized array An array in which first dimension is not specified at the time

of declaration60.Sorting Arranging elements of an array in a definite order(ascending

/descending)

Miscellaneous(Theory)

Declaration of variables

A declaration of a variable refers to the following:(i) Specification of the name of the variable(ii) Specification of the data type of the variable(iii) Specification of the scope of usage of the variable

Type Conversion

This covers the conversion of defined type variable into another type. This process of conversion of one data type to another type is called casting. The conversion into a smaller type results in the loss of data.

The Automatic or the Implicit type conversion is performed invisibly and are hence known as Automatic Conversion.

When two operands of different types are encountered in the same expression the lower-type variable is converted to the type of the higher-type variable automatically and is known as Type Promotion.

The Explicit type Conversion or Type Casting

It includes the conversion of data according to the specification by the user. It has the following syntax(type) expression.

Expression Evaluation

Expressions can either be pure expressions or mixed expressions. Pure expressions have all operands of same data types, contrary to mixed expressions that have operands of mixed datatypes.

Differences between constructors and functions

Page 18: Computers 2

Parameter Constructor Function

Purpose Creates an instance ofa class

Groups java statements

Return type Has no return type , not even void

Void or any valid return type

Name Same name as the class

Any name except the class name

Excecution Called at the time of object creation

Called when a function call for the specific method is encountered.

Control Flow (Q&A)

1. What are the control statements available in java?Ans: Java provides various control statements namely selection constructs and

iteration constructs.2. What role is played by selection control statement?Ans: Selection construct apply a condition that results true or false value. The

statements are executed selectively based on the result.3. What is the significance of a break statement in a switch-case construct?Ans: When a variable’s value matches the constant specified in case, the

statements within that case block are executed until a break is encountered. A break acts as a terminator for the execution of statements in a switch-case construct.

4. Distinguish the if-else construct from a switch-case construct.Ans: The switch statement differs from the if statement in that switch can only

test for equality whereas if can evaluate a relational or logical expression i.e. multiple conditions.The switch statement selects its branches by testing the value of same variable (against a set of constants) whereas the if-else construct lets you use a series of expressions that may involve unrelated variables and complex expressionsThe if-else is more versatile of the two statements. (If-else can handle ranges whereas switch cannot. Each switch case label must be a single valueThe if-else statement can handle floating point tests also apart from handling integer and character tests whereas switch cannot handle floating point tests

5. Define the following terms (i) Fall through (ii) Global variable (iii) Local variable (iv) Scope (v) Selection statement (vi) Statement

Ans: (i) Execution of multiple cases after matching takes place in a switch statement. (The fall of control to the following cases of matching case, is called Fall-through)

(ii) Class variable which is available to the entire class(iii) Variable declared inside a method or block(iv) Region within which a variable/piece-of-code is accessible(v) Statement that allows to choose a set-of-instructions for execution

depending upon an expression(vi) Instruction given to the computer to perform any kind of action.

Page 19: Computers 2

6. What is the problem of dangling-else? When does it arise? What is the default dangling-else matching and how it can be overridden?

Ans: The nested if-else statement introduces a source of potential ambiguity referred to as dangling-else problem. This problem arises when in a nested if statement, number of ifs is more than the number of else clauses. One method of overriding the default dangling-else matching is to place the last occurring unmatched if in a compound statement (Override the default dangling-else matching by using braces { }.

Constructor / Function Overloading (Programs)

1. Define a class Circle in Java with the following specificationsData membersradius, areaMember methodsCircle ( ) a parameterised constructor to accept an int value for radiusCircle ( ) a parameterised constructor to accept a double value for radiusfindArea ( ) a function to calculate the area of the circleshow ( ) a function to display the radius and the area of the circle

2. Define a class Addition in Java with the following specificationsData membersfirst, second, resultMember methodsAddition ( ) a parameterised constructor to accept two int argumentsAddition ( ) a parameterised constructor to accept one int & one double as argumentsAddition ( ) a parameterised constructor to accept one double & one int as argumentsAddition ( ) a parameterised constructor to accept two double as argumentsfindSum ( ) a function to find the sum of two operands and store the resultdisplay ( ) a function to display all the three data members

3. Define a class Cuboid in java with the following specificationsData memberslength, breadth, height, volMember methodsaccept ( ) a function to accept three integer argumentsaccept ( ) a function to accept two integer and one double valueaccept ( ) a function to accept one integer and two double valuescalc ( ) a function to calculate the volume of a cuboidshow ( ) a function to show all the four data members

4. Define a class Triangle with the following specificationsData membersbase, height, areaMember functionsgetData( ) a function to accept two int values as arguments for base and heightgetData ( ) a function to accept one int & one double as arguments for base and heightgetData ( ) a function to accept two double values as arguments for base and height

Page 20: Computers 2

calculate ( ) a function to compute the area of the triangleshow ( ) a function to display all the three data members

5. Define a class Trapezium with the following specificiationsData members: side1,side2,distance,area(double)Member functions: (i) A function to accept the parallel sides and distance between them(ii) A function to calculate the area of the trapezium (area=1/2(a+b) h,

where a and b are the sides of the trapezium, h is the height)(iii) A function to display the area of the trapezium

6. Define a class Rhombus with the following specificationsData members: diag1,diag2,area(double)Member functions:(i) A function to accept the diagonals of a rhombus(ii) A function to calculate the area of the rhombus(area=1/2 product of

the diagonals)(iii) A function to display the area of the rhombus

Programs on Input from keyboard (Console) (Class 11)

1. Write a program to accept the integer value and a choice (1 or 2) from the console. If the user enters choice as 1 calculate and display the area of a square, else if the user enters the choice as 2 calculate and display the perimeter of the square.

2. Write an interactive program to accept the choice from the user. If the user enter choice as 1 the program should ask the user to input values for length and breadth of the rectangle. Calculate and display the area. If the user enters choice as 2 the program should ask the user to input values for length, breadth, height of a cuboid. Calculate and display the volume of the cuboid.

3. Write a menu driven program to accept two integer values and an arithmetic operator. The program should perform the desired operation and display the resultant value.

4. Write a program to accept the name and marks in three subjects. Find the total and average. Print the result sheet in the following format:Name:English Marks:Computer Marks:Maths Marks:Total Marks:Percent:Grade:Assign grade to the student based on the following grade scalePercent<50 DPercent>=50 but <60 CPercent>=60 but<80 BPercent>=80 A

Loops (Application Programs)(Class 12)

Page 21: Computers 2

1. Write a program to read for a class of 10 students the marks in three subjects. Find and display the total and average of each of them.

2. An organization wants to know how many of its employees out of 10 are getting a basic pay of less than Rs.5000 per month. Input the basic pay of each employee.

3. Write a program to read the age of 10 employees and count the no. of persons in the following age groups:(i) 25-35(ii) 36-45(iii) 26-55

4. A teacher takes the daily attendance in a class for students numbering 25. He marks 0 if the student is absent and 1 if the student is present. Find the no. of students present or absent on a particular day.

5. Write a program to prepare a frequency distribution table of the % marks in Computer Studies of 60 students to be taken as inputs, into the following categoriesCategory Marks (%)Fail 0-34Pass 35-59Good 60-79Very Good 80 and above

6. A survey is conducted by a welfare organisation to count the no. of persons in favour and against the government policies. If he favours the policy he enters 1, if he is against it he enters 2 and if he has no opinion he enters 0. Write a program in java to count the no. of persons in each category. (Assume that the no. of persons under survey are 50)

7. A local club has 170 members of various ages from 12 to 21(both inclusive). A member below 15 is not eligible to vote for electing the SecretaryWrite a program to prepare a voter list containing the Serial no., Names of eligible voters and ages of voters. Also display the no. of voters eligible out of 170.

8. Write a class which has a method to find whether a no. is even, odd or prime. The user should be allowed to accept 10 numbers .

9. Write a program to accept the mode of transport undertaken by various sections of a society in commuting. Find and display the frequency for each category as mentioned.(1. Bus 2. Train 3. Auto 4. Others----------Assume that the no. of persons is 100)

10. Write a program that finds the temperature at which the temperature in degrees Celsius is equal to the temperature at Farenheit.

Page 22: Computers 2

Loops (Application Programs)

1. Write a program to print sum of negative numbers, sum of positive even numbers, sum of positive odd numbers from a list of numbers entered by the user. The list terminates when the number entered is zero.

2. A no. of answer scripts with scores 0 to 99 awarded after marking are to be searched for finding(i) Number of answer scripts marked(ii) % of candidates getting 85 and above(iii) % of candidates getting 39 or lessWrite a program to take the scores as inputs and then output the three quantities required.

3. Write a program to accept numbers from user till the user enters 0. Find out the maximum and minimum number entered and display it.

4. A computerised ticket counter of an underground metro rail station charges for each ride at the following rate:Age Amount/head18 or above Rs. 55 or above but below 18 Rs. 3Accompanying kids below 5 NilWrite a program which takes as input the no. of people of various age groups and prints a ticket. At the end of the journey, the program states the no. of passengers of different age groups who travelled and total amount received as collection of fares.

5. Write a program that takes as inputs monthly salaries of the employees of a company and then prints as outputs1) No. of employees2) Amount disbursed as salary in that month3) % of employees getting over 5000 rupees monthly salary. To terminate the program enter 0 as the first input item.

6. On a day, in order to make a survey of passengers using a particular train route, each passenger is asked to state the type of ticket he or she uses ----- a first or second class, day or monthly. This data is encoded for input to a computer. Write a program to obtain1) % of females travelling2) % of first class day passengers travelling on that day.

7. Write a program to calculate the fare for passengers travelling on a computerised bus. As each passenger enters the computer displays the prompt:

What distance do you intend travelling?On entering the distance at the keyboard the fare is printed out according to the table:Distance Fare

Page 23: Computers 2

Upto 12 Km Rs. 2.00Upto 20 Km Rs. 5.00Above 20 Km Rs. 7.50The computer keeps adding the fares as the distance is entered. The program ends when the distance entered is -99. It then prints the total no. of passengers who entered the bus and the total fare collected.

8. Write a program to input the code of a particular item, the quantity purchased and the rate. Then ask if any more items are to be purchased. If not then calculate the total purchase and print it along with the gifts to be presented. The gifts to customers are given in the following manner:Amount of purchase Gift1000 and above but less than 5000 A key ring5000 and above but less than 10000 A leather purse10000 and above A pocket calculator

9. The variables u, v and f are connected by the formula1/u + 1/v= 1/f

By using the formula and assuming that u and v can assume non-zero positive values only, write a program in Java which will ask the user to input non-zero values for u and v. The program will then print the values of f. The user should have the option of continuing as long as required.

10. Write a program to find the average of a list of numbers entered by the user through the keyboard. The program should stop when the user enters a negative number.Reasoning Programs(class 14)

1. Write a program to accept a number from the user. Find and display its factors.

2. Write a program to accept a number from the user. Find and display the sum of its factors.

3. Write a program to accept an integer value. Check whether the value entered is prime or composite and display an appropriate message.

4. Write a program to accept an integer value. Check whether the no. entered is perfect or not and display an appropriate message.

5. Write a program to accept an integer value. Find and display its factorial.

6. Write a program which uses a function power() to raise a number m to power n. The function takes int values for m and n returns the

Page 24: Computers 2

result correctly. Use a default value of 2 for n to make the function calculate squares when this argument is omitted.

7. Write a program to accept two integer values. Find and display their Highest common Factor(Greatest common divisor)

8. Write a program to accept two integer values. Find and display their Least common Multiple(LCM).

9. Write a program to find the no. of and sum of all integers greater than 100 and less than 200 that are divisible by 7.

10. Write a program to accept a number from the user. Find and display its even and odd factors.

Reasoning Programs

1. Write a program to accept an integer value. Find and display the sum of its digits.

2. Write a program to accept an integer value. Find and display its reverse.

3. Write a program to accept an integer value. Check whether the no. is palindrome or not and display an appropriate message.

4. Write a program to accept an integer value. Check whether the no. is Armstrong number(Narcisstic number) or not and display an appropriate message.

5. Write a program to accept an integer value. Check whether the entered value is an Automorphic no. or not and display an appropriate message.

6. Write a program to accept two integer values. Find and display their Highest Common Factor.

7. Write a program to accept one integer value from the user. Find and display its product.

8. Write a program to accept one integer value from the user. Find and display the no. of digits in the number entered.

9. Write a program to accept a number and a digit from the user. Find and display the no. of times the second digit appears in the given number.

Page 25: Computers 2

10. Write a program to accept an integer value. Find and display the prime digits in the number entered.More Programs On Reasoning

1. A no. with an even number of digits is called well ordered if the difference between the digits making up the first half and the numbers making up the second half is exactly equal to 1. Write a program that accepts a no. and checks whether it is well ordered or not.(Find all 4 digit ordered numbers).2. Write a program to calculate the sum of the products of pairs of digits at the same position in two numbers. Given that both the numbers have same no. of digits.Example: 1234 and 5678Output: 1*5+2*6+3*7+4*8=70

Nested Loops(application programs)

1. Write a program to display all the prime numbers between 1 and 100.

2. Write a program to display all the perfect numbers between 1 and 50.

3. Write a program to display all the Armstrong numbers between 200 and 500.

4. Write a program to check whether a no. is a magic no. or not and display an appropriate message.

5. Write a program to check whether a no. is a special no. or not and display an appropriate message.

6. Display all the prime fibonacii numbers upto the 15th term.

7. Two numbers are said to be amicable numbers when the sum of the factors of a is equal to b and the sum of the factors of b is equal to a. Write a program to accept two integer values ,check whether they are amicable or not and display an appropriate message.

8. A no. with an even number of digits is called well-ordered if the difference between the digits making up the first half and the digits making up the second half is exactly equal to 1. Write a program to display all the 4 digit well-ordered numbers.

9. Write a program to display all the palindrome numbers between 100 and 200.

10. Accept a four digit number from the user. Display all the possible combinations of the entered number.

Page 26: Computers 2

Programs on Series

1. Write a program to display the first twenty terms of the following series

1, 1, 2, 3, 5, ………………………………………..

2. Write a program to display the 45th term of the above series.

3. Write a program to compute the following series :

(a) s=2+4+6+8+10+………………………..+100(b) s=1x3+3x5+5x7+………………………+31x33(c) s=12+22+32+…………………..+352(d) s=1x3x5x………………………….x17(e) s=5+55+555+5555+…………………….n terms(f) s=1+12+123+1234+……………………+123……….n terms

4. Write a program to display the following series :

(a) 1, 4, 9, 16, ………………………………….. n terms(b) 1, 8, 27, 64, 125, ……………………….. n terms (c ) 0, 7, 26, 63, 124, …………………….. n terms(d) 3, 8, 15, 24, ………………………….. n terms

5. Write a program to compute the sum of the following series:

(a) s=1x2x3x4+2x3x4x5+3x4x5x6+4x5x6x7+5x6x7x8(b) s=(1+2)+(1+2+3)+(1+2+3+4)+ ………………….+ (1+2+3+4+…….10)(c ) s=1/(1+2) +1/(1+2+3) +1/(1+2+3+4)+ ….+ 1/(1+2+3+….n terms)(d) s=(1+2)/(1x2)+(1+2+3)/(1x2x3+) + ………+ (1+2+3+…..n terms)/ (1x2x3x…………… n terms)

Patterns1. Write a program to display the following patterns(i) 1 (ii) 111 12 111 123 1111 123411111 12345

(iii) 12345 (iv) 543211234 4321123 32112 211 1

(v) 1 (vi) 1

Page 27: Computers 2

13 2 3135 4 5 61357 7 8 9 1013579 11 12 13 14 15

(vii) 55555 (viii) 5555555554 5444455543 5433355432 5432254321 54321

(ix) 2345 (x) 1 11345 1 2 31245 1 2 3 61235 1 2 3 4 101234 1 2 3 4 5 15

(xi) 1 2 1 3 1 2 4 1 2 3 5 1 2 3 4

String handling

1. Write a program to print the number of vowels in the entered string.

2. Write a program to print the no. of words and blanks entered in a sentence.

3. Write a program to input any text and print the words in reverse order.

4. Write program to accept a String. Check whether the String entered is a palindrome or not and display an appropriate message.

5. Write a program to input a sentence. Find and display the longest word in the sentence.

6. Prepare an interactive program to accept a person’s first, middle and last names and to extract and display the initials.

7. Read the following String:Be Diligent, and you will Succeed.Write a program to output(a) No. of uppercase alphabets(b) No. of lowercase alphabets(c) No. of special characters.

8. Define a method to accept a String. Convert all the lowercase letters to uppercase and vice versa and display the modified String.

Page 28: Computers 2

9. Write a program to accept a word from the user and display it in the alphabetical order.

10. Write a program to input a word and print the next consecutive letter of each alphabet.

Input : EARTHOutput: FBSUI

More Programs on Strings

1. The value of a letter in the alphabet(A…..Z) is defined as the position of that letter in the alphabet. Thus A=1,B=2,C=3 and so on with Z=26. The worth of a word is defined as the sum of the value of each letter in that word. For example, the worth of the word CAB is 6.Write a program that will accept a word as input and compute its worth. Test your program with the words PRICELESS AND WORTHLESS

2. Write a program that inputs a sentence and prints out the no. of single, two, three, four and five letter words in it.

3. Write a program that prints out a table containing the ASCII code of all alphabetic characters,(both upper and lower case) and numeric characters and the corresponding character.

Arrays One dimensional(Programs)1. Write a program in Java to create a one dimensional array of size 10 to accept 10 integer values and display the elements of the array.

2. Write a program in Java to accept 10 integer values into a one dimensional array. Find and display the sum of all the elements of the array.

3. Write a program to accept 20 integer values into a one dimensional array. Display all the elements in the reverse order.

4. Write a program to accept 10 integer values into a one dimensional array. Find the sum of all even subscripted elements and product of all odd subscripted elements. Display both the values.

5. Write a program which initializes all the prime numbers between 1 and 20 to a one dimensional array . Display the elements of the array.

Page 29: Computers 2

6. Write a program to accept 10 integer values into a one dimensional array. Square each element of the array and store in another one dimensional array of same size. Display original value and its corresponding square.

7. Write a program to create two one dimensional arrays of size 10. Find and output the numbers that are common to both the arrays.(The numbers within each array are not repeated).

8. Write a program to assign the following scores to an single dimensional array. Find and print the frequency of the classes 0-25,26-50,51-75,76-100:35,19,47,0,93,20,68,29,12,80,82,26,70,42,84,18,34,8,76,98,2,38,64,92,30,54,62,10,24,6,74,42, 86, 50,8,54

9. Write a program to read all the numbers given below and print them out with all the 0’s to the extreme left. The sequence of numbers should not be disturbed.Input: 1,0,2,45,3,0,46,8,0,5Output: 0,0,0,1,2,45,3,46,8,5

10. Write a program to create two one dimensional arrays of size 10 to store the names and corresponding phone numbers. Ask the user to search any entered phone number and print the corresponding name. Also print an appropriate message if the phone number entered is not present in the list.11. Write a program to assign two character arrays with the following values.Char ch={‘a’,’b’,’c’,’d’,’e’}Char ch1={‘f’,’g’,’h’,’i’,’j’}Declare a third array to concatenate the values in both the arrays to form a new arrayChar ch2={‘a’,’b’,’c’,’d’,’e’,‘f’,’g’,’h’,’i’,’j’}

Programs

1. Define a class Time that has the following functions & data membersData membershrs,mins,total(int)Member functionsvoid accept( ) a function that accepts time in hours and minutesvoid convert ( ) a function that converts it into total minutesvoid display( ) a function that displays time in minutes

2. Define a class Distance that has the following specificationsData members inch,feet (int)cms(double)Member functions(1) a function to accept the inches and feet as parameters(2) a function to convert total distance into centimetres(3) a function to display the distance in centimetres

Page 30: Computers 2

3. Define a class Triangle that has the following specificationsData membersbase, height area(double)(1) a function to accept the base and height as parameters(2) a function to calculate the area of the triangle(3) a function to display the area

4. Define a class Shop to do the following tasks(1) A function to accept the no. of pencils sold and rate per pencil in a day(2) A function to calculate the total amount earned in a day(3) A function to display al the three quantities

5. Define a class Student with the following specificationsData membersname(String)marks1, marks2, marks3(double)avg(double)Member functionsaccept( ) a function to accept the name and marks of three subjectscalc ( ) a function to calculate the total and averagedisplay() a function to display the name and average.

Control Flow Statements

1. Write a conditional statement to check the value of character variable var as Y or y

2. Write a conditional statement to check the value of variable num lying in the range of numbers 1500 and 2200

3. Write a conditional statement to check whether the sum of a and b is greater than double of b

4. Write a conditional statement to check whether the sum of a and double of b is greater than the product of a and b and the difference of a and b is less than a/2

Programs

1. Take a number num as 495 and check its divisibility by 5.2. Write a java program to assign integer numbers 10 and 34 to variables x and y. Print the larger one

3. Write a program to assign integer numbers 10,34 and 9 to variables x,y and z. Print the largest

4. A voter is eligible to vote for the elections held in his city, if his age is at least 18 yrs. WAP to input his age and verify him as an eligible or not eligible voter.

Page 31: Computers 2

5. Write a program in java to accept the principal and time from the user. The rate of interest is as followsTime Rate<=1 5%>1 && <=3 10%>3 12%Calculate and display the Simple interest.7. WAP in java to accept a integer value. Check whether the value entered is

even or odd and display an appropriate message.

Control Flow Statements

1. A Supermarket shop offers gifts to the customers in the following manner :Amount of purchase (Rs.) GiftUpto 500 A carry bagAbove 500 but not above 1000 A pen-setAbove 1000 A cut glass tumbler

Write a program which will display the amount of purchase and the gift to be given for a customer. (Accept the amount as a parameter)

2. Write a program in Java to find the discounted price for purchases in a departmental shop offering discounts in the following manner:Amount of purchase (Rs) DiscountLess than 500 5%From 500 to 1000 7%Over 1000 8%(Accept the amount of purchase)

3. Write a program in Java to calculate the commission for a certain sale on the following basis:Commission is 2% for sale upto ten thousand rupees, 3% for over ten thousand rupees but not over fifty thousand rupees and 4% for sale over fifty thousand. (Accept the sale amount as a parameter)

4. Write a program in Java to accept the marks in three subjects from the user. Calculate the total and average. If the average is more than or equal to 75 display the message “Distinction”, if the average is more than or equal to 60 but less than 75 display the message “First class”, if the average is more than or equal to 50 but less than 60 display message “Second class” otherwise display the message “Work hard to stay in the race”

5. Write a program in Java to accept the monthly income of an employee. Find and display the income tax to be paid by the employee on his annual income using the following conditionsMonthly income rate10000 0%10001-50000 10%50001-100000 15%100001-500000 20%500001 and above 25%

Page 32: Computers 2

6. A shopkeeper offers “Puja Discount” to his/her customer according to the goods purchased as per given amountGoods purchased DiscountUpto Rs. 1000 5%>Rs. 1000 and upto Rs. 2000 10%>Rs. 2000 and upto Rs. 3000 15%>Rs. 3000 20%

Write a program in Java to calculate the discount for purchase of the goods, by customers.7. A cloth showroom has announced the following festival discounts on the purchase of items,based on the total cost of the items purchased:Total cost DiscountUpto Rs. 2000 5%Rs2001 to Rs. 5000 25%Rs.5001 to Rs. 10000 35%Above Rs. 10000 50%Write a program to input the total cost and to compute and display the amount to be paid by the customer after availing the discount.8. The equivalent resistance of a series and a parallel connection of two resistances is given by the formula:R1= r1+r2(Series)R2=r1.r2/r1+r2(Parallel)Write a program in java to enter the values of r1 and r2. Compare the magnitude of the equivalent resistances and display the result accordingly.9. Mr. Kumar is an LIC agent. He offers discounts to his policy holders on the annual premium. However, he also gets commission on the sum assured as per the given tariff:

Sum assured Annual Premium Discount CommissionRs. 50000 Rs 2450 5% 2%Rs. 50001-Rs. 200000 Rs. 4650 10% 3%More than 200000 Rs. 9500 15% 5%

Write a program in java to calculate the discount of the policy holder and the commission of the agent, taking the sum assured as an input.

10. Mr. Kuldeep Singh wants to deposit a sum of money under fixed deposit scheme in State Bank of India. The bank has provided the tariff of the scheme for a minimum deposit of Rs. 40,000 which is given below:

No. of days Rate of InterestUpto 400 days 7.5% p.a.401 to 600 days 8.5% p.a.601 to 800 days 9.5%p.a.

Write a program in java to calculate the maturity amount, taking the sum and number of days as inputs.

Control Flow Statements (switch.. case)

1. Write a program to enter one of the integers from 1 to 7 and then output the name of the day.

Page 33: Computers 2

2. Write a program to accept a digit from 0 to 9 and then output the digit in words.

3. Write a program to accept grade as a parameter and return corresponding message.Excellent for grade 1Good for grade 2Credit for grades 3, 4, 5Pass for grades 6, 7Fail for grades 8, 9

4. Write a program to accept an alphabet (letter) from the user. Check and display whether the alphabet entered is vowel or consonant.

5. Write a switch statement that prints ‘Yes’, ‘no’, ‘unknown’ according as a variable reply has a value ‘y’, ‘n’ or any other value.

6. Write a program which accepts two integer values and an arithmetic operator and calculates the result based on the operator passed. Display the corresponding result.

7. Write a program to accept a character from the user. Find and display an appropriate message. If the character entered is ‘I’ or ‘i’ the message “ICSE” should be displayed, for ‘c’ or ‘C’ the message “CBSE” should be displayed otherwise the message “State syllabus” has to be displayed.

8. Write a program to accept two character values into two parameters-charfirst, charsecond and display an appropriate messagecharfirst charsecond PriceC or c-(Compaq) D or d(Desktop) 25000L or l(Laptop) 28000Z or z-(Zenith) D or d(Desktop) 18000L or l(Laptop) 22000

9. Write a program to accept an integer value from the user (1,2,3) to display an apporpriate message, Developed country, Developing country or Under developed country accordingly.

10. Write a program to accept a character from the user and display an appropriate message as follows:E or e English MovieH or h Hindi MovieT or t Telugu Movie.

Control Flow(Practice programs)

1. A bank accepts fixed deposits for one year or more and the policy it adopts on interest is as follows :If a deposit is less than Rs. 2000 and for 2 years or more, the interest rate is 5 % compounded annually.

Page 34: Computers 2

If a deposit is Rs. 2000 or more but less than 6000 and for 2 years or more, the interest rate is 7% compounded annuallyIf a deposit is more than Rs.6000 and is for 1 year or more, the interest is 8% compounded annually.On all deposits for 5 years or more, interest is 10 % compounded annually.On all other deposits not covered by above conditions the interest is 3% compounded annuallyGiven the amount deposited and the number of years, write a program to calculate the money in customer’s account at the end of the specified time.

2. A computer dealer sells computers at the following rates :Rs. 35000 per computer for less than 20 computersRs.31000 per computer for 20 to 39 computersRs. 29000 per computer for 40 or more computersWrite a program to take the number of computers as input and display the bill. A customer gets a further discount if he is dealing with the dealer for more than 5 years.

3. Write a program to input values for a, b, c where a, b, c are the lengths of the sides of a triangle. Calculate the area depending on the following conditions :if the sum of any two sides of the triangle is lesser than the third side then print ‘ A triangle cannot be formed’.If a=b=c then print ‘It is an equilateral triangle’ and calculate the area as area= √3/2 a2If the sum of the squares of any two sides is equal to the square of the third side then print ‘ it is a right-angled triangle’ and calculate the area as area=1/2*product of the perpendicular sidesOtherwise calculate area as area=√s(s-a)(s-b)(s-c)Where s= a+b+c/2

4. Create a function to accept the sale, total produced for a class called Toys. Calculate the percentage sale of the toy and rate it as “Very good”, “Good”, “Average” and “Poor” depending upon the percentage sale(Percentage sale=sale/Totalproduced*100)

5. A cloth showroom has announced the following festival discounts on the purchase of items, based on the total cost of the items purchasedTotal cost Discount (in percentage)Less than Rs. 2000 5%Rs. 2001 to Rs. 5000 25%Rs.5001 to Rs.10000 35%Above Rs. 10000 50%

Write a program to input the total cost and to compute and display the amount to be paid by the customer after availing the discount.

6. Make a program to calculate the Gross pay of an employee when the Basic pay is given. The formula for gross pay is Grosspay=basicpay+hra(10% of basicpay)+da(150% of basicpay)The output should be shown as below:Enter name of Employee : : empnameEnter PF no. of the employee : : pfnoEnter Basic pay of the employee : : salaryName of the Employee: : : empname

Page 35: Computers 2

PF . No.: : : pfnoBasic Pay : : : salaryDearness Allowance : : : daHouse Rent allowance : : : hraGross salary of employee : : : grosspayAdmission to a professional course is subject to the following conditions:Marks in mathematics>=60Marks in physics>=50Marks in chemistry>=40Total in all three subjects>=200ORTotal in mathematics and physics>=150Given the marks in the three subjects, write a program to process the applications to list the eligible candidates

7. Rewrite each of the following without using compound relations:(a) if(grade<=59 && grade>=50)second=second+1;(b) if(number>100 || number<0)System.out.println(“Out of range”);elsesum=sum+number;(c) if((M1>60 && m2>60)||t>200)System.out.println(“admitted”);elseSystem.out.println(“Not admitted”);

8. The income tax of employee per month is computed on following criteria.Income TaxUpto Rs. 40000 NilNext Rs. 30000 20%Next Rs. 30000 30%Above Rs.100000 40%Write a program to accept name and income of an employee and print his name and income tax due.

Functions (Returning values)

1. Write a function that takes two char arguments and returns 0 if both the arguments are equal. The function returns -1 if the first argument is smaller than the second and returns 1 if the second argument is smaller than the first.2. Write a program in Java that has a function satisfy( ) to find whether four integers a,b,c,d passed as parameters satisfy the equationa3+b3+c3=d3 or notThe function returns true if the above equation is satisfied with the given four numbers otherwise it returns a value false

3. Write a program in java which has a function to accept the rainfall for three months (April, May and June). Declare and initialize a variable for the rainfall in each month. Calculate and return the average rainfall for three months.

Page 36: Computers 2

4. Write a program in Java which accepts a two digit number. If the no. entered is 13 return message “Unlucky”, if the no. entered is more than 99 return message “More than two digits” otherwise return “Number entered is less than two digits”5. Write a program to accept three integer values. Find and return the smallest.6. Write a program to accept an integer value. Find and return an appropriate message whether it is an even or odd no. Further your program should check if is positive or negative or 0.Example: Input:-5 Output: Negative odd7. Write a program to accept the costprice and sellprice of an article. Determine for the gain or loss and return the gain% or loss % accordingly.8. Write a program to accept a character from the user. If the character entered is ‘I’ or ‘i’ return the message “Indian”, if it is ‘P’ or ‘p’ return the message “Pakistani” otherwise return the message “Others”.9. Write a program to accept the side of a square and a character from the user. Find the area of the square if the character entered is ‘a’, perimeter of the square if the character entered is ‘p’ and return the resultant value. If any other character is entered return 0.10. Write a program to accept a four digit number from the user. Check and return a boolean value whether the year entered is a century leap year.Example: Input: 2000 Output: trueInput: 1997 Output: false

Menu Driven Programs (Console I/O)

1. Write a program using a function called area( ) to compute the area of:(i) circle(∏ r2 ) where ∏=3.14(ii) square(side*side)(iii) rectangle(length*breadth)Display the menu to output the area as per User’s choice

2. Using a menu driven program, calculate the area of three squares whose sides are x, y,(x+3y) respectively where x=2 km, y=5.5 km

3. Write a menu driven program to perform the following tasks:(i) Km to cm(ii) Hours to minutes(iii) Centigrade to Fahrenheit

4. Write a program that inputs experience and age of a person for experienced and his age is more than 35. Otherwise if the person is experienced and his age is more than 28 but less than 35 then the salary should be 4800 otherwise for the experienced person the salary should be 3000 and for inexperienced person the salary should be 2000. 5. Write an interactive program which allows the user to input the principal, time and rate from the user. Calculate and display the Simple Interest or the Compound Interest based on the user’s choice.

6. Write a program that offers a menu to choose from various categories of cinema hall tickets. After the user selects a category, ask for the number of tickets he/she wants to buy and then tell the total amount payable. The price list of various categories is as under:

1. Lower Stall Rs. 50

Page 37: Computers 2

2. Upper Stall Rs. 753. Balcony Rs. 90 4. Box Rs. 120

7. Write a program for a pathological laboratory that has the following information available about the type of anti-bodies present in a blood sample. Using this information, the blood groups are to be printed as per following specifications:

Anti – A Anti – B Blood GroupPresent Present OPresent Absent BAbsent Present AAbsent Absent AB

8. ‘ Kamani Centre ‘ is a Mega Shop and has five floors for shopping and entertainment.1. Ground Floor : Kids Wear2. First floor : Ladies Wear3. Second floor : Men’s Wear4. Third floor : Food court5. Fourth floor : MoviesWrite a program in java to allow the user to enter a choice and get the information regarding the shop under the above categories.9. Using a switch case statement, write a menu driven program to convert a given temperature from Fahrenheit to Celsius and vice-versa. For an incorrect choice, an appropriate message should be displayed.(Hint: c=5/9(f-32) and f=1.8c+32) (ICSE 2007)10. Write a program that outputs the results of the following evaluations based on the number entered by the user(a) Natural logarithm of the number(b) Absolute value of the number(c) Square root of the number(d) Random numbers between 0 and 1 (ICSE 2006)

Loops(Worksheet)1. How many times the following loop will be executed?(i) int s=0,i=0; (ii) int s=0,i=0;do while(i<5){ s=s+i;s=s+i; }while(i<5);

2. Write the output of the following program code :(i) class whileTest1 (ii) class Test{ {public static void main() public static void main(){ {int i=2; int i=1;while(i<15) while(i!=6){ {System.out.println(i); System.out.println(i);i=i*2; i=i+2;

Page 38: Computers 2

} }} }} }

(ii) class test (iv) class test{ {public static void main() public static void main(){ {for(int i=2;i<15;i=i+2) for(int i=2;i<15;i=i*2)System.out.println(i); System.out.println(i);} }} }(v) class test (vi) class test{ {public static void main() public static void main(){ {for(int i=2;i<15;i=i*2) for(int i=30;i>5;){ {System.out.println(i); System.out.println(i);i=i-1; i=i-5;} }} }} }

3. The following program is supposed to write out the integers 1,2,3,4. Decide what should go into the blanks.class counter{public static void main(){int count;count=-------------;while(count ______ 4){System.out,println(count);count=count+ ___________ ;}}}4. The following program is supposed to write out the integers 10,11,12,13,14 and 15. Decide what should go in the blanks.class counter2{public static void main(){int j;j= _________ ;while(j< ______ ){System.out.println(j);j=j+ _________ ;}}

Page 39: Computers 2

}

5. The following program is supposed to write out the integers 2,1,0,-1. Decide what should go in the blanksclass counter3{public static void main(){int count ____ ;while( count >= ____ ){System.out.println(count);count=count- ____ ;}}}

6. What is the output of the following code fragment ?(i) (ii)for(int j=5; j> -5;j--) for(int j=0;j<5;j++)System.out.print( j+ “ “); { System.out.print(j+ “ “);System.out.println(); j++;}7. Examine the following code :int count = 1;while(count<5){System.out.print(count+ “ “);}System.out.println();

8. Predict the output of the following programs(i) class Prediction1 (ii) class Prediction2{ {public static void main() public static void main(){ {int i; int i=5,a=5;for(i=-1;i<10;i++) while(i<=10){ {System.out.println(++i); a=a++ * i;} }} System.out.println(“The product=” +a);} } }

(ii) class Prediction3{public static void main(){int i=1,a=3;do{if(a%2==0)System.out.println(Math.pow(a,2));

Page 40: Computers 2

i++;a++;}while(i<=5);}}

9. Rewrite the program using do while: Given the following for loop:(i) class Series (ii) .{ .public static void main() .{ final int sz=25;int i,a=2,s=0; for(int i=0,s=0;i<sz;i++)for(i=1;i<=4;i++) sum+=i;{ System.out.println(s);s=s+a*a;a=a+2; Write an equivalent while loop for the above code} System.out.println(“the sum =”+s);}}

10. State the output of the following program segments(i) for(x=10;x--) (ii) int x=-10;boolean b=true;{ while(b)if(x==0) {break; if(x<0)System.out.print(x); { x++;} continue;}elsebreak;}System.out.println(x);

(ii) for(char ch=’A’;ch<=’E’;ch++) (iv) int a;char ch;{ for(ch=’A’;ch<=’E’;ch++)int a=ch; a=ch;System.out.println(ch+” “+a); System.out.print(ch+” “+a);}

Increment and Decrement Operators(Postfix- Prefix Operations)1. If p=5 find d=++p +5;2. If a=48 find a=a++ + ++a;3. If c=2 then find d=++c + c++ +4;4. If m=12 then find n=m++ *5 + --m;5. If y=14 then find z=++y *(y++ +5);6. If a=4, b=3 find the value of c=a++ *6 + ++b*5 +10;7. If a=8 find the value of a-=++a + a++ +4;8. If a=12, b=8 find the value of a*= ++a/6 + b++ %3;9. If x=4 find the value of x+=x++ * ++x%2;10. If a=48,b=13 find the value of a+=b++ * 5 /a++ + b;11. int a=7;int p=0; p=++a + --a;

Page 41: Computers 2

12. Evaluate the following expressions, if the values of the variables are p=7,q=9,r=11(a) P*(q++ % 4) * (++r) (b) (r-- )% 5 + (r++/5)*p(b) P+=(--p +5) *p++*(r/2) (d) q*=5+(--q)*(q++) +1013. Evaluate the following expressions, if the values of the variables are : int p,w;K=8,m=11,r=7;(a) P=m+(--r +k)+3*(m++)*m;(b) K+=(--m%5)*(m++ *(10+r++);(c) W=k*(m++/3)+(k+(--r +r++));(d) P=(r++%7)+(--m%5)+k*(++k-8);14. State the output of the following expressions(a) int a=7, b=5,c; (g) int m,p;m=5;p=0;c=++a*4 + b++; p=m-- + --m;System.out.println(“c=”+c); System.out.print(p);(b) int x=5, y=4,z;z=x*y++ + ++x/y; (h) int a=7;int p=0;int q=0;System.out.println(z); p=++a + --a;(c) int p=6;q=15; q-=p;int r; System.out.println(p);r=(p*q) +p/q; System.out.println(q);System.out.println(r);(d) int a=5,b=10; (i) if a=5, b=9 calculate the value of:a=a+ b++ + --b +b; a+=a++ - ++b +a;What will be the result of a and b after execution ?(e) int m=10,n=12,p;p=(m++ * n++)+ --n/2;System.out.println(p);(f) double c;int x,y,z;x=5;y=10;z=11;c=x*y+z/2;System.out.println(c);