Sie sind auf Seite 1von 77

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

1. Why JAVA known as other language.

platform-neutral

language? How JAVA is more secured than

A "platform" usually refers to an Operating System (OS), such as Windows or Mac. "Platform-independent" means that the same Java code can run on different platforms. This is achieved by using the Java Virtual Machine (VM) - a layer between the Java code and the OS. The VM takes a piece of Java code, translates it into the native code the OS can understand and feeds the code to the OS. Then it interprets the result or further request from the OS and passes it back to the Java component. Therefore, Java code is said to be "interpreted". Because of the extra steps involved, Java code runs slower than the native code of the OS. Plateform neutral or platform independence, means that programs written in the Java language must run similarly on any supported hardware/operating-system platform. One should be able to write a program once, compile it once, and run it anywhere. Java was designed to not only be cross-platform in source form like C, but also in compiled binary form. Since this is frankly impossible across processor architectures Java is compiled to an intermediate form called byte-code. A Java program never really executes natively on the host machine. Rather a special native program called the Java interpreter reads the byte code and executes the corresponding native machine instructions. Thus to port Java programs to a new platform all that is needed is to port the interpreter and some of the library routines. Even the compiler is written in Java. The byte codes are precisely defined, and remain the same on all platforms. Java is more secure than other programming languages because of it's use of a virtual machine on the host computer. Essentially, when you run a Java program on your computer, it runs on the JVM (Java Virtual Machine.) This JVM translates the code from the java file you downloaded into native machine code specific for your computer. Therefore, the JVM can control all aspects of how the code is executed, and is able to block any security breaches before they even reach your computer. This is much more secure than running a program directly on your computer, although there is a slight performance drop due to the fact that the Virtual Machine must run along with the java program.

2. What is multithreading? How does it improve the performance of java ? Ans from book:- In a multithreading environment, a thread is the smallest unit of dispatchable code. This means that a single program can perform two or more tasks simultaneously. For instance a text editor can format text at the same time that it is printing. The benefit of Java's multithreading is that the main loop/polling mechanism is eliminated. One thread can pause without stopping other parts of the program. For example, the idle time created when a thread reads data from a network or waits for user input can be utilized elsewhere. When a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run. Ans From Web:- Multithreading enables we to write programs that contain two or more separate paths of execution that can execute concurrently. Each path of

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


execution is called a thread. At its core, multithreading is a form of multitasking. There are two distinct types of multitasking: process-based and thread-based. Thus, process-based multitasking is the feature that allows your computer to run two or more programs concurrently. For example, it is process-based multitasking that allows you to download a file at the same time you are compiling a program or sorting a database. In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler. In a thread-based multitasking environment, the thread is the smallest unit of dispatch able code. Because a program can contain more than one thread, a single program can use multiple threads to perform two or more tasks at once. For instance, a browser can begin rendering a Web page while it is still downloading the remainder of the page. This is possible because each action is performed by a separate thread. Although Java programs make use of processbased multitasking environments, process-based multitasking is not under the direct control of Java. Multithreaded multitasking is.

The second reason that multithreading is important to Java relates to Javas eventhandling model. A program (such as an applet) must respond quickly to an event and then return. An event handler must not retain control of the CPU for an extended period of time. If it does, other events will not be handled in a timely fashion. This will make an application appear sluggish. It is also possible that an event will be missed. Therefore, if an event requires some extended action, then it must be performed by a separate thread.

3. Give difference between Java and C,C++. i. Java does not use pointers. ii. The goto keyword does not exist in Java (it's a reserved word, but currently unimplemented). iii. Java does not have template classes as in C++. iv. Java doesnt contain data types such as struct, union and enum. v. Java classes are singly inherited with some multiple inheritance features provided through interface.

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

Multithreading is important to Java for two main reasons. First, multithreading enables you to write very efficient programs because it lets you utilize the idle time that is present in most programs. Most I/O devices, whether they be network ports, disk drives, or the keyboard, are much slower than the CPU. Thus, a program will often spend a majority of its execution time waiting to send or receive information to or from a device. By using multithreading, your program can execute another task during this idle time. For example, while one part of your program is sending a file over the Internet, another part can be handling user interaction (such as mouse clicks or button presses), and still another can be buffering the next block of data to send.

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

All processes have at least one thread of execution, which is called the main thread, because it is the one that is executed when a program begins. From the main thread, you can create other threads. These other threads can also create threads, and so on.

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


vi. vii. viii. ix. x. xi. xii. Java does not have a preprocessor, and as such, does not have macros like # define. Constants can be created by using the final modifiers when declaring class and instances variables. In Java, all methods are tied to classes. Java does not support stand-alone methods. Java does not include the const keyword as present in C or the ability to pass by const reference explicitly. In Java strings are implemented as objects and not as an array of null-terminated characters. Java has some additional primitive data types like byte and Boolean. Data types in Java have a fixed size regardless of the operating system used. In Java, arrays are real objects because you can allocate memory using the new operator In Java, arrays are real objects because you can allocate memory using the new operator

Simple. Java's developers deliberately left out many of the unnecessary features of other high-level programming languages. For example, Java does not support pointer math, implicit type casting, structures or unions, operator overloading, templates, header files, or multiple inheritance. Object-oriented. Just like C++, Java uses classes to organize code into logical modules. At runtime, a program creates objects from the classes. Java classes can inherit from other classes, but multiple inheritance, wherein a class inherits methods and fields from more than one class, is not allowed. Statically typed. All objects used in a program must be declared before they are used. This enables the Java compiler to locate and report type conflicts. Compiled. Before you can run a program written in the Java language, the program must be compiled by the Java compiler. The compilation results in a "byte-code" file that, while similar to a machine-code file, can be executed under any operating system that has a Java interpreter. This interpreter reads in the byte-code file and translates the byte-code commands into machine-language commands that can be directly executed by the machine that's running the Java program. You could say, then, that Java is both a compiled and interpreted language. Multi-threaded. Java programs can contain multiple threads of execution, which enables programs to handle several tasks concurrently. For example, a multi-threaded program can render an image on the screen in one thread while continuing to accept keyboard input from the user in the main thread. All applications have at least one thread, which represents the program's main path of execution. Garbage collected. Java programs do their own garbage collection, which means that programs are not required to delete objects that they allocate in memory. This relieves programmers of virtually all memory-management problems. Robust. Because the Java interpreter checks all system access performed within a program, Java programs cannot crash the system. Instead, when a serious error is

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

4. Explain briefly features of Java language. 1.Simple 2. Object-oriented 4. Compiled 5. Multitreaded 7. Robust 8. Secure 10. Well understood

3. Statically typed 6. Garbage Collected 9. Extensible

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


discovered, Java programs create an exception. This exception can be captured and managed by the program without any risk of bringing down the system. Secure. The Java system not only verifies all memory access but also ensures that no viruses are hitching a ride with a running applet. Because pointers are not supported by the Java language, programs cannot gain access to areas of the system for which they have no authorization. Extensible. Java programs support native methods, which are functions written in another language, usually C++. Support for native methods enables programmers to write functions that may execute faster than the equivalent functions written in Java. Native methods are dynamically linked to the Java program; that is, they are associated with the program at runtime. As the Java language is further refined for speed, native methods will probably be unnecessary. Well-understood. The Java language is based upon technology that's been developed over many years. For this reason, Java can be quickly and easily understood by anyone with experience with modern programming languages such as C++.

In Procedural Programming language the execution of application can be step by step. That means the data can be executed ina sequential manner but in Object oriented languages the application executed according to the order we wrote in the program. That means there is no need to follow the order of execution on OOP.it depends on the object. Here some differences between procedure oriented programming (POP) and Object Oriented programming (OOP). In POP, importance is given to the sequence of things to be done i.e. algorithms and in OOP, importance is given to the data. In POP, larger programs are divided into functions and in OOP, larger programs are divided into objects. In POP, most functions share global data i.e data move freely around the system from function to function. In OOP mostly the data is private and only functions inside the object can access the data. POP follows a top down approach in problem solving while OOP follows a bottom up approach.

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

Object oriented programming is a method of implementation in which programs are organized as collection of objects, each of which represents an instance of some class and whose classes all members of a hierarchy of classes united in inheritance relationships. In an object oriented programming there is a class and the class contains member variables and member functions. Class arranges the method and variables. A class implements inheritance, abstraction, encapsulation, polymorphism and interface. It also implements function overloading, constructor overloading. An object is an instance of a class which is a physical entity. But class is a declaration or templates which are used to define the member function and variables. Object oriented programming implements modular approach for solving a problem. It breaks the problem into parts for easier solution of the problem. Object programming contains main method which is the starting point of any program.

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

5. What is object oriented programming? How it is different from the procedure oriented programming?

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

In POP, adding of data and function is difficult and in OOP it is easy.

In POP, there is no access specifier and in OOP there are public, private and protected specifier. In POP, operator cannot be overloaded and in OOP operator can be overloaded.

6. What are the advantages of object oriented programing.


Advantages of OOP: Reusability: Elimination of redundant code and use of existing classes through inheritance. Thus provides economy of expression. Modularity: Programs can be the built from standard working modules. Security: Principle of information hiding helps programmer to build secure programs. Easy mapping: Object in the problem domain can be directly mapped to the objects in the program. Scalability: Can be easily upgraded from small programs to large programs. Objectoriented systems are also resilient to change and evolve over time in a better way. Easy management: Easy management of software complexity.

A class defines the structure and behavior (data and method) that will be shared by a set of objects. Each object 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. A class is a logical construct. An object has physical reality. When you create a class, you will specify the code and data that will constitute that class. Collectively, these elements are called the members of the class. Specifically, the data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods, which define the use of the member variables. 8. Describe inheritance as applied to OOP. Inheritance is one of the OOPS concepts(the OOPS concepts are Abstraction, Encapsulation, Polymorphism and Inheritance). Java is purely a OOP language. Inheritance means a class of objects can inherit properties from another class of objects. A class that inherits the attributes from another class is called subclass or child class or derived class. The class from which the attributes are derived is called base class or super class or parent class. Derived class can modify the some or all attributes derived from the base class. Inheritance enables easy maintenance and reusability of code which saves time and efforts.

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

In an object-oriented program, a set of variables and functions used to describe an object constitutes a "class".

ito

rw

7. How are data and method organized in an object oriented program ? Illustrate the same for car object.

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Java supports two types of inheritance SINGLE inheritance and MULTILEVEL inheritance. "extends" is the keyword to inherit properties of the base class. All the derived classes having a single base class is termed as the single inheritance. for example Java supports two types of inheritance SINGLE inheritance and mULTILEVEL inheritance."extends" is the keyword to inherit properties of the base class.All the derived classes having a single base class is termed as the single inheritance.for example class A { ... } class B extends A { ... } public class C extends A { ... } this is single inheritance whereas, a class inherits the properties of another class, for example class A { ... } class B extends A { ... } public class C extends B { ... } java doesnot support multiple inheritance.However, a class can implement any number of interfaces(interface is a collections of methods with no definition(abstract methods))

9. Explain different access modifiers used in Java. Access to variables and methods in Java classes is accomplished through access modifiers. Access

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


modifiers define varying levels of access between class members and other objects. Access modifiers are declared immediately before the type of a member variable or the return type of a method. There are four access modifiers The default access modifier Public Protected Private The default access modifier specifies that only classes in the same file or package have access to a classs variables and methods. There is no actual keyword for declaring the default access modifier; it is applied by default in the absence of any other modifier. For example, in our MotorMain program all the variables and methods in the MotorCycle class had default access because no access modifiers were specified. The class MotorMain could however see and use all these variables and methods because the two classes are part of the same file (and hence the same default package). The public access modifier specifies that class variables and methods are accessible to anyone, both inside and outside the class. This means that public class members have global visibility and can be accessed by any other object. For example: if you declared the variable named x as public int x = 20; then the value of x will be visible to all the other classes of the same program. public int count; public Boolean isActive; The protected access modifier specifies that class members are accessible only to methods in that class and subclasses (dont worry we deal with subclasses later) of that class. This is same, as Public but it will give more protection than the public. If Protected is used then all the methods and attributes of the base class will be available to all its derived classes Protected int count; Protected Boolean isActive; The private access modifier is the most restrictive; it specifies that class members are accessible only by the class in which they are defined. this means that no other class has access to private class members. For example: private int y = 100; means the value of y will be visible only to the class it is defined. If you try to access the variable in other classes then the compiler will return an error. 10.What is inheritance? Show how subclass can invoke constructor of super class. With example Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class). Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object. The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself. A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. In other words same thing:- Inheritance is the core concept of Object oriented programing and Java programming Language. Since every subclass has exclusive rights to use the every resource of its superclass. Constructor of superclass holds important position in this regard. There are many functions a subclass can import by calling the constructor of its superclass. The call to the Superclass constructors can be made by using the ' super ' keyword. The main points to remembered in case of using super keyword are as follows:1.The default Constructor of the superclass is invoked even if the super() method is not called in the subclass.It is also invoked if you do not pass any arguments to super().If the default constrictor is not available,compiler generates an error. 2. You can invoke a special constructor of the superclass by passing arguments to the super method,if the constructor is overloaded in the superclass.

The Superclass class Car { Strring Name; int seats=4; Car(){ ..... }

Car(int seats,String Name){ .... } }

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

Lets take a look at following example:- The example illustrates how you can call a super class constructor.

ll P

DF

3. The super() method must be the first statement in the constructor of the subclass.

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Subclass which invokes the superclass constructor public class Subaru extends Car{ int wheels; public Subaru(){ super(4,"Subaru Impreza"); wheels=4; } } Here the constructor of superclass is invoked by the method call super(4,"Subaru Impreza") and you can call the default constructor by placing your call super().By following the way you can invoke the superclass constructor which can be helpful in many tasks in your application.

You can use the continue statement in the while, do-while, and for statements but not in the switch statement. Use of continue statements is illustrated in the following program. //The program displays all even numbers between 1 and 20. Class EvenNum20 { public static void main(String args[]) { int j, k; for(j=1, k=0; j<=20; j++) { k=j%2; If(k!=0)

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

The continue statement is written as continue;.

Fi

ll P

If the user enters an incorrect password, the counter variable in the program is incremented and the control is returned to the start of the loop statement. This saves time because the remaining statements in the loop will not be executed. For this purpose, Java provides the continue statement. The 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.

DF

Ed

ito

rw

ith

Fr ee

In certain situations, it may be necessary for the flow of control to exit a loop statement and start the next iteration of the loop statement. An example of such a situation is a password verification program where the user is given three chances to enter the correct password.

rit

er an d

11.Explain continue and break statements in Java with an example

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


//specify the continue statement below this line. continue; else System.out.println(j+ is an even number.); } } } The continue statement causes the flow of control to move to the condition part of the while and do-while loops. In the case of the for statement, the continue statement causes the flow of control to move to the update expressions part of the for statement before moving to the test condition part. Break statement in Java: By using break, we can force immediate termination of loop, by passing 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. Class Breakloop { public static void main(string args[ ]) { for(int i=0; i<00; i++) { if (i == 10) break; system.out.println(i =:+i); } system.out.prinln(loop complete); } }

In several instances, such as an error or incorrect input from the user, it may be necessary for the flow of control to exit from a loop statement. To accomplish this, Java provides a jump statement called break. The break statement forces the control to come out from a: switch statement while loop do-while loop for loop

12.

What is typecasting? Why is it required in programming? Explain with an example.

10

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


Type Casting refers to changing an entity of one datatype into another. This is important for the type conversion in developing any application. If we will store a int value into a byte variable directly, this will be illegal operation. For storing your calculated int value in a byte variable we ll have to change the type of resultant data which has to be stored. Type casting means treating a variable of one type as though it is another type. When up casting primitives as shown below from left to right, automatic conversion occurs. But if you go from right to left, down casting or explicit casting is required. Casting in Java is safer than in C or other languages that allow arbitrary casting. Java only lets casts occur when they make sense, such as a cast between a float and an int. However we cant cast between an int and a String (is an object in Java). byte -> short -> int -> long -> float -> double int i = 5; long j = i; //Right. Up casting or implicit casting byte b1 = i; //Wrong. Compile time error Type Mismatch. byte b2 = (byte) i ; //Right. Down casting or explicit casting is required. Other example: Long a=99L Int b=a; //Wrong, needs a cast Int b=(int) a //OK

Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands. They are summarized in the following table: OPERATOR RESULT ~ Bitwise unary NOT or Bitwise complement & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR >> Shift right >>> Shift right zero fill << Shift left

The ~ Operator (NOT)

11

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

Bit manipulation operations, including logical and shift operations, perform low-level operation directly on the binary representations used in integers. These operations are not often used in enterprise-type systems but might be critical in graphical, scientific, or control systems. The ability to operate directly on binary might save large amounts of memory, might enable certain computations to be performed very efficiently, and can greatly simplify operations on collections of bits, such as data read from or written to parallel I/O ports.

ll P

DF

Ed

ito

rw

ith

13. Explain the Bit-wise operators available in JAVA with an example to each.

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


General result = ~operand; Usage:

The ~ operator is called an unary operator, because it takes only one argument. The arguments of an operator are also called the operands. Other operators, for instance, the & operator, require two operands, thus they are called binary operators. Operators that require three operands are called ternary operators... By using ~, you can calculate the bitwise complement of a value. The bitwise complement of a value is the value with the opposite bit states: means if the operands bit is 1 the result is 0 and if the operand bit is 0 the result is 1. Example: ~00110010 = 11001101

General Usage: result = operand1 & operand2;

Another example,

public class ExampleBitwiseAND { public static void main(String[] args) { int operand1 = 13; int operand2 = 12; System.out.println("Operand1 : " + Integer.toBinaryString(operand1)); System.out.println("Operand2 : " + Integer.toBinaryString(operand2)); //calculates the bitwise AND result int result = operand1 & operand2;

12

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

The result of operation of 42 and 15 00101010 42 &00001111 15 -----------00001010 10

Fi

ll P

DF

Ed

ito

This operator is used to combine two values by ANDing their bits at each position. The bit state of the resulting value at a specific position is only 1, if the states of the bits at that position of operand1 AND operand2 are 1:

rw

ith

Fr ee

As we can see, the & operator is a binary operator, because it takes two operands.

rit

er an d

To

The & Operator (AND)

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

System.out.println("Result : " + Integer.toBinaryString(result)); } } /* The output of this example will be: Operand1 : 1101 Operand2 : 1100 Result : 1100 */ The | Bitwise inclusive or Operator A bitwise OR takes two bit patterns of equal length, and produces another one of the same length by matching up corresponding bits (the first of each; the second of each; and so on) and performing the logical inclusive OR operation on each pair of corresponding bits. In each pair, the result is 1 if the first bit is 1 OR the second bit is 1 OR both bits are 1, and otherwise the result is 0. For example: 0101 (decimal 5) OR 0011 (decimal 3) = 0111 (decimal 7) The ^ Bitwise exclusive or

Bit Shifts The bit shifts are sometimes considered bitwise operations, since they operate on the binary representation of an integer instead of its numerical value; however, the bit shifts do not operate on pairs of corresponding bits, and therefore cannot properly be called bit-wise operations. In this operation, the digits are moved, or shifted, to the left or right. Registers in a computer processor have a fixed number of available bits for storing numerals, so some bits will be "shifted out" of the register at one end, while the same number of bits are "shifted in" from the other end; the differences between bit shift operators lie in how they compute the values of those shifted-in bits. The Left-Shift Operator<< The operator << performs a left shift. The result of this shift is that the first operand is multiplied by two raised to the number specified by the second operand ; for example:

13

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

0101 XOR 0011 = 0110

Fi

ll P

DF

Ed

A bitwise exclusive or takes two bit patterns of equal length and performs the logical XOR operation on each pair of corresponding bits. The result in each position is 1 if the two bits are different, and 0 if they are the same. For example:

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

128 << 1 returns 128*21 = 256 16 << 2 returns 16*22= 64 The Right Shift operators >> and Right Shift Unsigned>>> The java programming language provides two right-shift operators. The operator >> performs an arithmetic or signed right shift. The result of this shift is that the first operand is divided by 2 raised to the number of times specified by the second operand . For example : 128 >> 1 returns 128/21 = 64 256 >>4 returns 256/24 = 16 -256 >>4 returns -256/24 = -16 The logical or unsigned right shift operator >>> works on the bit pattern rather than the arithmetic meaning of a value and always places 0s in the most significant bits; for example 1010..>> 2 gives 1111010.. 1010>>> 2 gives 001010..

o o

Declare a variable of class type. This variable does not define an object instead it is a simply a variable that can refer to an object. Physical copy of the object is created and assigned to that variable.

14

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

Creating an object is referred to as instantiating an object. The creating object to a class is two-step process:

DF

Ed

An object in java is a block of memory that contains a space to store all the instance variables. As with real-world objects, software objects have state and behavior. In programming terms the state of an object is determined by its data (variables); the behavior by its methods. Thus a software object combines data and methods into one unit.

ito

rw

ith

Fr ee

14.What are the objects? How are they created using classes? How do you assign values to data members of class? Explain with an example

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Classes don't only define properties of Objects; they also define operations that may be performed by those Objects. Such operations are called methods in object-oriented languages like Java

15.What is function overloading? What are the two rules apply to overloaded methods? Illustrate the same with example. Function overloading is the process of using the same name for two or more functions in the same class. Each time the same function name is used it must be used with different types of parameters, sequence of parameters or number of parameters. The type of parameter, sequence of parameter or number of parameter is called the function signature. When the name of the function is same then the compiler identifies the function based on the parameters.

15

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

On the right, we have two actual Tree Objects. These are Trees, and they were created based on the blueprint provided by the Tree class. These Objects are said to be instances of the Tree class, and the process of creating them is called instantiation. Thus, we can say that by instantiating the Tree class twice, we have created two instances of the Tree class, two Objects based on the Tree class, or just two Trees. Notice that in creating these Objects we have assigned a value to their height property. The first Tree is 2 meters high and the second is 5 meters high. Although the values of these properties differ, this does not change the fact that both objects are Trees. They are simply Trees with different heights.

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

On the left we have a class called Tree. This class defines a type of Java Object -- a Tree -- that will serve as the blueprint from which all Tree Objects will be created. The class itself is not a Tree; it is merely a description of what a Tree is, or what all Trees have in common. In this example, our Tree class indicates that all Trees have a property called 'height'.

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Two rules apply to overloaded methods: 1. The return types of method can be different, but the argument lists of overloaded methods must differ. 2. The argument lists of the calling statement must differ enough to allow unambiguous determination of the proper method to call. Example :-

void show(int x)

void show(int a,int b) { int c = a*b; System.out.println(The value is +c); } public static void main(String args[ ]) { Overload over = new Overload( ); over.show(50); over.show(60,70); }

16

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

System.out.println(The value is +x);

DF

Ed

ito

rw

class Overload

ith

Fr ee

rit

er an d

To

ols

In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism. If you have never used a language that allows the overloading of methods, then the concept may seem strange at first. But as you will see, method overloading is one of Javas most exciting and useful features. When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. Here is a simple example that illustrates method overloading:

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


} Output The value is 50 The value is 4200 16.What is a constructor? What are its special properties? What are the different types of constructors? Explain with an example. A constructor is a special type of method that is invoked when an object of a class is created. A constructor is used to initialize the members of a class. Properties of a constructor: The name of the constructor is same as the name of the class. Constructor does not have any return type. Constructor cannot be inherited. Constructor can be of various kinds. Java provides us with default constructor, parameterized constructor and subclass constructor. When any constructor is not defined for a class then java provides us with a default constructor without any parameter. A subclass can invoke the constructor of super class using the keyword super(). Example of different kinds of constructors: //Default Constructor class Test { void TestFunction() { String name = "RAJ"; System.out.println(name); } public static void main(String[] args) { System.out.println("Default constructor is invoked"); Test t = new Test();// default constructor is invoked t.TestFunction(); } } // Parameterized constructor class Test { public Test() { System.out.print("Constructor is called without any arguments"); } public Test(int x) { System.out.println(" "); System.out.print("constructor is called with one arguments." + " "); System.out.print("Passed argument is" + " " + x);

17

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


} public Test(String FirstName, String LastName) { System.out.println(" "); System.out.print("constructor is called with two arguments." + " "); System.out.print("Passed argument is" + " " + FirstName + " " + "and" + " " + LastName); System.out.println(" "); } public static void main(String[] args) { Test t0 = new Test();//Calling the default constructor. Test t1 = new Test(100);//Calling the constructor with one argument; Test t2 = new Test("RAJ", "SINGH");//Calling the constructor with one argument; } } //Calling the Base class constructor using derived class. class Base { public Base() { System.out.println("Base class constructor is called usingderived class"); } public Base(String FirstName, String LastName) { System.out.println(FirstName + " " + LastName); } } class Derived extends Base { public Derived() { super(); } public Derived(int x, int y) { super("RAJ", "SINGH"); System.out.println(x); System.out.println(y); } public static void main(String[] args) { Derived d = new Derived(); Derived d1 = new Derived(10, 20); } }

18

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


17.What is a class? How does it accomplish data hiding? How do you create objects from the class? Class is a template, declaration or a blueprint that can be used to classify the objects. A class contains variables and functions. A class uses encapsulation and abstraction for accomplishing data hiding. Abstraction is the process of providing only the relevant information means it provides us with that information what we are looking for. Encapsulation is the process of enclosing one or more items within a physical or logical package. It prevents access to non essential details. A class uses access modifiers for implementing encapsulation which defines the scope of a member variable and function of a class. Different types of access modifiers are Default, public, private and protected. Default: A variable, method or class has default accessibility if no any access modifier is defined for them. It is accessible anywhere within the same class and same package. Public: A variable or method marked as public is accessible any where in the same class, same package, subclass and different class.

Protected: Protected variables and methods are accessible anywhere in the same class, same package and derived class but it is not accessible to the different class.

18.What is an array? Why arrays are easier to use compared to bunch orelated variables? An array is a sequence of logically related data items. It is a kind of row made of boxes, with each box holding a value. The number associated with each box is the index of the item. Each box can be accessed by, first box, second box, third box, and so on, till the nth box. The first box, or the lowest bound of an array is always zero, which means, the first item in an array is always at position zero of that array. Position in an array is called index. So the third item in an array would be at index 2 (0, 1,2). An array is a sequence of logically related data items. It is a kind of row made of boxes, with each box holding a value. Arrays have following advantages over bunch of related variables: o o o Arrays of any type can be created. They can have one or more dimensions. Any specific element can be indexed in an array by its index. All like type variables in an array can be referred by a common name. What is an exception? Explain with a program. Ans: An exception is an erroneous situation that occurs during the execution of a program. When an exception occurs in an application then java throws an error. The error is handled through the exception handler. When error occurs, runtime creates an exception object and sends it to the program. The exception object contains information about the error. Java use try and catch for handling exceptions. The part of the program which is likely to throw exceptions is kept with try and each try is at least preceded by one catch blocks. There can be any number of catch for a try block.

19

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

Private: A private variable or method is accessible only by the methods and variable of the same class.

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


Example of exception: class Test { int x = 10; int y = 0; public void ExceptionTest() { try { int result = x / y; System.out.println("Result=" + "" + result); } catch (Exception e) { System.out.println("Number cannot be divided by zero"); System.out.println(e); } } public static void main(String[] args) { Test t = new Test(); t.ExceptionTest(); } }

What is array:-A array in Java is like a fixed number of slots, each slot holds a item, and all of them the same type. Or In other word An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. i.e. the length of an array cannot be increased or decreased. Why Array use:we might come across a situation where we need to store similar type of values for a large number of data items. For e.g. To store the marks of all the students of a university, you need to declare thousands of variables. In addition, each variable name needs to be unique. To avoid such situations, we can use arrays. Syntax to declare a one-dimensional array type array_name []; //type is the datatype of the array. For e.g. int anArray[]; // anArray is name of the array.

20

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

19.What is an array? How elements are stored in a memory? Explain how do you create array of objects?

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


Allocating Memory to Arrays The new operator is used to allocate memory to an array. Syntax to allocate memory array_name = new type[size]; For e.g. anArray = new int[10]; //size of the array is 10. Alternatively, we can use the shortcut syntax to create and initialize an array: int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};

Creating an Array of Objects To create an array of objects means that every element in an array is an object, or instance of another class. For example, if you wanted to make an array filled with Circle objects (suppose we have Circle class), we would do it in the following way: Circle[] c = new Circle[5]; The above statement has created an array called c, with 5 Circle elements. At the moment, each object is null. You have just created the following:

21

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. Two-dimensional Arrays In additions to one-dimensional arrays, we can create two-dimensional arrays. To declare two-dimensional arrays, we need to specify multiple square brackets after the array name. Syntax to declare a two dimensional array type array_name = new type[rows][cols]; For e.g. int multidim[] = new int[3][];

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


To create the 5 Circle objects, you must use the new operator for each element as such: for (int i = 0; i < 5; i++) c[i] = new Circle(); Visually, this gives:

20.Bring out the differences between overloading and over riding. Overloading: The methods with the same name but it differs by types of guments and number of arguments. Overloading: Methods name same but signatures is different in the class. Example: class b{ public void add(int i int j){ int n i+j; System.out.println(n); } public void add(int i int j int k){ int n i+j+k; System.out.println(n); } public void add(int i int j int k int l){ int n i+j+k+l; System.out.println(n); } public static void main(String []aa){ b b1 new b(); b1.add(1 2 5); } } output: 8 Overriding: The methods with the same name and same number of arguments and types but one is in base class and second is in derived class. Overriding:To redefine the base class method in the derived class is called overriding. Example: class a{

22

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


public void display(){ System.out.println( it is a firest class method ); } } class overiding extends a{ public void display(){ System.out.println( it is a Second class method ); } public static void main(String []anil){ overiding obj new overiding(); obj.display(); } } output: it is a Second class method

Overriding methods It allows a subclass to re-define a method it inherits from it's superclass overriding methods: 1. It appears in subclasses 2. They have the same name as a superclass method 3. They have the same parameter list as a superclass method 4. They have the same return type as as a superclass method 5. They have the access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method If the superclass method is public, the overriding method must be public If the superclass method is protected, the overriding method may be protected or public If the superclass method is package, the overriding method may be packagage, protected, or public If the superclass methods is private, it is not inherited and overriding is not an issue

21.

Explain final keyword with suitable example.

Any field that you never expect to be changed should generally be declared final. In the Java programming language, the final keyword is used in several different contexts to define an entity which cannot later be changed. Final classes:- A final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final, for

23

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

Overloading methods 1.They appear in the same class or a subclass 2.They have the same name but, have different parameter lists, and can have different return types. An example of an overloaded method is print() in the java.io.PrintStream class

rit

er an d

To

Some more differences:

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


example java.lang.System and java.lang.String. All methods in a final class are implicitly final. Example: public final class MyFinalClass {...}

Final Method:- A final method cannot be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.[1] Example: public class MyClass { public final void myFinalMethod() {...} }

public class Physics {

Blank Final Variables:- A blank final variable is a final variable that is not initialize in its declaration. The initialization is delayed. A blank final instance variable must be assigned in a constructor, but it can be set once only. public class customer { private final long custid; public customer() { custid=createid(); } public long getid() { return custid; }

24

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

public static final double c = 2.998E8;

Ed

ito

rw

Fields that are both final, static, and public are effectively named constants. For instance a physics program might define Physics.c, the speed of light as

ith

Fr ee

Final Variables:- we can also declare fields to be final. This is not the same thing as declaring a method or class to be final. When a field is declared final, it is a constant which will not and cannot change. It can be set once (for instance when the object is constructed, but it cannot be changed after that.) Attempts to change it will generate either a compile-time error or an exception (depending on how sneaky the attempt is).

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


private long createid{ return//generate new id } //more declarations }

22. What is stream? List out the different stream classes in java, explain how input or output is handled in java?
A stream is a sequence of data. A stream is in Java is a path along which data flows. It has a source of data and a destination for the data. Both the source and the destination may be physical devices or programs or other streams in same program. Java uses the concept of streams to represent the ordered sequence of data, a common characteristic shared by all the input/output devices as stated above. A stream presents a uniform, easy-to-use, object-oriented interface between the program and the input/output devices. Java includes a particularly rich set of I/O classes in the core API, mostly in the java.io packages. These packages support several different styles of I/O. One distinction is between byte-oriented I/O, which is handled by input and output streams, and character-I/O, which is handled by readers and writers. These all have their place and are appropriate for different needs and use cases. All classes are basically divided into two types of categories: 1. Byte Stream classes 2. Character stream classes 1. Byte Stram classes:- Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. Each of these abstract classes has severalconcrete subclasses, that handle the differences between various devices, such as disk files, network connections, and even memory buffers. The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ), which, respectively, read and write bytes of data. Both methods are declared as abstract inside InputStream and OutputStream. They are overridden by derived stream classes. 2. Character Stream Classes:- Character streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer. These abstract classes handle Unicode character streams. Java has several concrete subclasses of each of these. The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important methods are read( ) and write( ), which read and write characters of data, respectively. These methods are overridden by derived stream classes. Handling the input or output in Java: Java provide java.io package to handle input and output of any type of data. There are two classes based on data which these classes can handle. The name of the classes

25

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


are Byte stream class that handle I/O operations on bytes and Character streams that handle I/O operation on charcter Reading Character: To read a character from the BufferReader use read(). The version of read is int read() throws IOException. Whenever the read() is called it reads a character from the input stream and returns an integer value. If the value is -1 it means the end of stream. Reading String: To read a string from the keyboard use the version of readline() that is member of the BufferReader class. Its general form is String readLine() throws IOException. Writing Console Output: console output is accomplished by print() and println(). These methods are defined by the PrintStream. PrintStream is an output stream derived from OutputStream, it also implements low level method write(). Write() can be used to write to the console.

23.What is an exception? Explain with a program. An exception is an erroneous situation that occurs during the execution of a program. When an exception occurs in an application then java throws an error. The error is handled through the exception handler. When error occurs, runtime creates an exception object and sends it to the program. The exception object contains information about the error. Java use try and catch for handling exceptions. The part of the program which is likely to throw exceptions is kept with try and each try is at least preceded by one catch blocks. There can be any number of catch for a try block. Example of exception: class Test { int x = 10; int y = 0; public void ExceptionTest() { try { int result = x / y; System.out.println("Result=" + "" + result); } catch (Exception e) { System.out.println("Number cannot be divided by zero"); System.out.println(e); } } public static void main(String[] args) { Test t = new Test(); t.ExceptionTest();

26

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


} }

24.

Explain if else statement with syntax and with an examples.

The syntax of if else statement is given below. If (test expression) { True block statement(s) } else { False block statement(s) } In if else statement if the condition given in test expression evaluates to true then immediately true block statement is executed otherwise the false block statement is executed. There can be number of if else in a if else statement. //program to find the greatest of two numbers public class Greater { public static void main(String [ ] args) { int x=10,y=20; if (x > y) { System.out.println(x + is greater than + y); } else { System.out.println(y + is greater than + x); } System.out.println( ); } 25.List the eight basic data types used in java given examples. I. Boolean: Logical values are represented using the Boolean data types The Boolean data type has two values either true or false. Example: boolean truth=true II. Char: Single characters are represented by using the char data type. A char represents a 16-bit unsigned Unicode character. A char is enclosed within a single quote. Example: char a=A III. String: A sequence of characters are stored using String data type. A String is enclosed within double quote marks. Example: happy IV. Byte: The length of Byte data type is 8 bits and it ranges between -27 to 27-1. Example of Byte data type is 2. V. Short: The length of Short data type is 16 bits and it ranges between -215 to 215-1. Example of Srt data type is -62699. VI. Long: The length of Long data type is 64 bits and it ranges between -263 to 263-1. Example of Long data type is 775, 808L1L. VII. Int: The length of int data type is 32 bits and it ranges between -231 to 231-1. Example of int data type is 147. VIII. Float: The length of Float data type is 32 bits used to store values to the right of decimal point. Example of float data type is 99F.

27

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ] 26. Explain arithmetic operators and arithmetic operations in Java with examples.
The arithmetic operators are a set of one or more characters that is used for computation or comparisions. There are five basic arithmetic operators in java: addition (+), subtraction (-), multiplication (*), division (/) and modulus (%). Java performs arithmetic operation only with int, long, float and double. When we perform any calculation on given set of operands using the arithmetic operator then it is called arithmetic operation. Examples of arithmetic operation: Operator Explanation Example + Adds two number X=1+2=3 Subtracts two number X=7-5=2 * Multiply two number X=5*5=25 / Divides two number X=21/3=7 % Return the remainder of X=5%2=1 division

In java a program is created inside a class. All the member variable and function are declared inside the class. First of all a class is defined and a name is given to it. Then after declaring the class required member variable and function are created. After that main method is created in which object of a class is created and by using that object the function are called. Then we compile the program using javac and if the program is compiled then we execute it by typing the command java filename. class Division { int i; int sum = 0; void calculate() { for (i = 50; i <= 100; i++) { if (i % 9 == 0) { sum = sum + i; } } System.out.println("The sum is " + " " + sum); } public static void main(String[] args) { Division d = new Division(); d.calculate(); } }

28

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

27. Explain with a simple example how to crate, compile and run a program in Java

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ] 28. Explain thread priority with simple program?

The thread is controlled by their priority. Java executes threads based on their priority. Only one thread is executed at one time. The thread which are in runnable state waits for their chance to be executed by the CPU. Java uses setPriority property for setting the priority of a thread and getPriority to get the priority of a thread. import java.io.*; class Test extends Thread { public void FirstThread() { for (int T = 0; T < 11; T++) { for (int cnt = 0; cnt < 100; cnt++) { System.out.print("."); } System.out.print(T); } } public void SecondThread() { for (int T = 11; T < 20; T++) { for (int cnt = 0; cnt < 100; cnt++) { System.out.print("."); } System.out.print(T); } } public static void main(String[] args) { Test t = new Test(); t.FirstThread(); t.SecondThread(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t1.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.MAX_PRIORITY); t1.start(); t2.start(); } }

29.

What is scope of a variable?

29

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


The area of the program where the variable is accessible (i.e., usable) is called its scope. Java variables are actually classified into three kinds:

Instance Variables Class variables Local variables Instance and class variables are declared inside a class. Instance variables are created when the objects are instantiated and therefore they are associated with the objects. They take different values for each object. On the other hand, class variables are global to a class and belong to the entire set of objects that the class creates. Variables declared and used inside methods are called local variables. They are called so because they are not available for use outside the method definition. Local variables can also be declared inside program blocks that are defined between an opening brace '{' and a closing brace '}'. These 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.

case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break;

30

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

case 2: System.out.println("February"); break;

Fi

ll P

DF

public class SwitchDemo { public static void main(String[ ] args) { int month = 8; switch (month) { case 1: System.out.println("January"); break;

Ed

ito

rw

ith

Fr ee

An 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. Also, the value provided to each case statement must be unique.

rit

er an d

30. Explain in what ways does a switch statement with example.

statement differ from an if

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

case 9: System.out.println("September"); break;

case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; }

31.

Describe the structure of a typical Java program

Documentation Section

rw

ith

A Java program may contain one or more sections as shown in the following figure: Suggested

Package Statement

DF

Ed

ito

Fr ee

A Java program may contain many classes of which only one class defines a main method. Classes contain data members and methods. Methods of a class operate on the data members of the class. Methods may contain data type declarations and executable statements. To write a Java program, we first define classes and then put them together.

rit

Import Statements Interface Statements

PD

Fi

ll P

Class Definitions Main Method class { Main Method Definition }

31

Solved by: - Rajesh & Ashish [ AshuRaj ]

er an d

Optional

Optional Optional

Essential

Essential

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


General Structure Of a Java program Documentation Section The documentation section comprises a set of comment lines giving the name of the program, the author and other details. Java also uses the comment /**...*/ known as documentation comment. Package Statement The first statement allowed in a Java file is a package statement. This statement declares a package name and informs the compiler that the classes defined here belong to this package. Example: package student; Import Statement The next thing after a package statement (but before any class definitions) may be a number of import statements. This is similar to the #include statement in C++. Example: import student.test; This statement instructs the interpreter to load the test class contained in the package student.

Class Definitions

Main Method Class Since every Java stand-alone program requires a main method as its starting point, this class is the essential part of a Java program. A simple Java program may contain only this part. The main method creates objects of various classes and establishes communications between them.

32. What is inheritance and how one can achieve code reusability? Explain with an example.
Inheritance refers to the properties of a class being available to other classes as well. The original class is called Base Class and Derived classes are classes created from the existing class (Base Class). It will have all the features of the Base class. The concept of inheritance is very important in object-oriented programming languages. It

32

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

A Java program may contain multiple class definitions. Classes are the primary and essential elements of a Java program.

Fi

ll P

DF

Ed

An interface is like a class but includes a group of method declarations. This is also an optional section and is used only when we wish to implement the multiple inheritance feature in the program.

ito

rw

ith

Interface Statements

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


simplifies code writing thus making programs easier to maintain and debug. It allows reusability of the code A subclass is defined as follows: class subclass extends superclass { Variables declaration; Methods declaration; } The keyword extends signifies that the properties of the superclass are extended to the subclass. The subclass will now contain its own variables and methods as well those of the superclass. This kind of situation occurs when we want to add some more properties to existing class without actually modifying it.

example.

o o o

Default constructor. If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans). Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created. Differences between methods and constructors. There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value. There is no return statement in the body of the constructor. The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.

33

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Constructor name is class name. A constructors must have the same name as the class its in.

Fi

ll P

DF

Sometimes in a few classes you may have to initialize a few of the variables to values apart from their predefined data type specific values. If java initializes variables it would default them to their variable type specific values. For example you may want to initialize an integer variable to 10 or 20 based on a certain condition, when your class is created. In such a case you cannot hard code the value during variable declaration. such kind of code can be placed inside the constructor so that the initialization would happen when the class is instantiated.

Ed

ito

rw

ith

Fr ee

A constructor creates an Object of the class that it is in by initializing all the instance variables and creating a place in memory to hold the Object. It is always used with the keyword new and then the Class name. For instance, new String(); constructs a new String object.

rit

er an d

To

33. What is a constructor & parameterized constructor? Explain its usage with an

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do.

this(...) - Calls another constructor in same class. Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class. super(...). Use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the superclass, there is no need to make a call to it because it will be supplied automatically.

parameterized constructors can be invoked just by inserting parameteers into the object create statement i.e for example

{ system.out.println( the value of a is + a);

} this can be called by calling

Below is an another example of a cube class containing 2 constructors. (one default and one parameterized constructor). public class Cube1 { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube1() { length = 10; breadth = 10;

34

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

Test t1 new Test(a);

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

Test(int a)

To

ols

class Test{

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


height = 10; } Cube1(int l, int b, int h) { length = l; breadth = b; height = h; } public static void main(String[] args) { Cube1 cubeObj1, cubeObj2; cubeObj1 = new Cube1(); cubeObj2 = new Cube1(10, 20, 30); System.out.println(Volume of Cube1 is : + cubeObj1.getVolume()); System.out.println(Volume of Cube1 is : + cubeObj2.getVolume()); } }

Polymorphism: It is a key concept in object-oriented programming. Poly means many, morph means change (or 'form'). Polymorphism (from the Greek, meaning many forms) is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. Consider a stack (which is a last-in, first-out list). You might have a program that requires three types of stacks. One stack is used for integer values, one for floating-point values, and one for characters. The algorithm that implements each stack is the same, even though the data being stored differs. More generally, the concept of polymorphism is often expressed by the phrase one interface, multiple methods. This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compilers job to select the specific action (that is, method) as it applies to each situation. You, the programmer, do not need to make this selection manually. You need only remember and utilize the general interface. A simple crude example for polymorphism in real-world could be ... 1. Every dog has a nose . Dog is a system. Nose is the interface of the system to detect smell. Based on the kind of smell, dog (system) reacts differently..may be it will bark at you, wag its tail, chase you etc., So eventhough dog-system has a single nose-interface, it behaves differently based on the smell (or data/parameters fed to the interface). You can consider one another a computer-systems related example... 2. Every ATM has a single interface(slot) to login to the bank-system by feeding in the ATM-card(data). But based on what sort of account user holds, a different screen is

35

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

34. What is polymorphism? Explain method overriding with example and prove that it is a polymorphism.

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


probably presented to the user, or his navigation experience might be different. Also if the customer withdraws some money from his account, then the computation going behind differs based on the type of account he/she holds.

Method overriding :-In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden. overridden methods allow Java to support run-time polymorphism. Polymorphism is essential to object-oriented programming for one reason: it allows a general class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods. Overridden methods are another way that Java implements the one interface, multiple methods aspect of polymorphism The following program creates a superclass called Figure that stores the dimensions of various two-dimensional objects. It also defines a method called area( ) that computes the area of an object. The program derives two subclasses from Figure. The first is Rectangle and the second is Triangle. Each of these subclasses overrides area( ) so that it returns the area of a rectangle and a triangle, respectively. // Using run-time polymorphism. class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } double area() { System.out.println("Area for Figure is undefined."); return 0; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } }

36

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class FindAreas { public static void main(String args[]) { Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); figref = f; System.out.println("Area is " + figref.area()); } } The output from the program is shown here: Inside Area for Rectangle. Area is 45 Inside Area for Triangle. Area is 40 Area for Figure is undefined. Area is 0

Through the dual mechanisms of inheritance and run-time polymorphism, it is possible to define one consistent interface that is used by several different, yet related, types of objects. In this case, if an object is derived from Figure, then its area can be obtained by calling area( ). The interface to this operation is the same no matter what type of figure is being used. 35. List and explain different types of loops in Java Loop is the control statement of any language in which whenever you want to perform the repetitious work then you use the Loop control statement. There are mainly three types of loops. Loop repeats a statement or a process multiple times according to the specified conditions. It allows the multiple statements or process to be run for the specified time or it also follows the certain conditions. Loop makes our program readable, flexible and reliable. Three loops in java these are while,do while and for

37

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


The while Loop: A while loop is a control structure that allows you to repeat a task a certain number of times. Syntax: The syntax of a while loop is: while(Boolean_expression) { //Statements } When executing, if the boolean_expression result is true then the actions inside the loop will be executed. This will continue as long as the expression result is true. Here key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

public class Test { public static void main(String args[]){ int x= 10; while( x < 20 ){ System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } }

This would produce following result: value value value value value value value value value value of of of of of of of of of of x x x x x x x x x x : : : : : : : : : : 10 11 12 13 14 15 16 17 18 19

38

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

Example:

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


The do...while Loop: A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax: The syntax of a do...while loop is: do { //Statements }while(Boolean_expression); Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

public class Test { public static void main(String args[]){ int x= 10; do{ System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } }

This would produce following result: value value value value value value value value value value of of of of of of of of of of x x x x x x x x x x : : : : : : : : : : 10 11 12 13 14 15 16 17 18 19

39

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

Example:

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


The for Loop: A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated. Syntax: The syntax of a for loop is: for(initialization; Boolean_expression; update) { //Statements }

public class Test { public static void main(String args[]){ for(int x = 10; x < 20; x = x+1){ System.out.print("value of x : " + x ); System.out.print("\n"); } } } This would produce following result: value value value value of of of of x x x x : : : : 10 11 12 13

40

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

Example:

ll P

DF

1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. 2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop. 3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression. 4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the for loop terminates.

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

Here is the flow of control in a for loop:

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


value value value value value value of of of of of of x x x x x x : : : : : : 14 15 16 17 18 19

36.

Explain the various control of statements of Java programming language with syntax and an example for each.
A programming language uses control statements to cause the flow of execution to advance and branch based on changes to the state of a program. Javas program control statements can be put into the following categories: selection, iteration, and jump. Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). Jump statements allow your program to execute in a nonlinear fashion. All of Javas control statements are examined here.

Selection statements:

Syntax: if(conditional_expression){ <statements>; ...; ...; } Example: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to 0 so if block is executed. Hence "This is even number" is printed on the screen. int n = 10; if(n%2 = = 0){ System.out.println("This

41

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

1. If Statement: This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed .

Ed

ito

rw

ith

Fr ee

1- Selection Statements :- (if-then, if-then-else and switch) 2- Repetition or iteration Statements:- while, do-while and for 3- Branching or jupm Statements :- break, continue and return

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ] is even number"); }

2. If-else Statement: The "if-else" statement is an extension of if statement that provides another option when 'if' statement evaluates to "false" i.e. else block is executed if "if" statement is false. Syntax: if(conditional_expression){ <statements>; ...; ...; } else{ <statements>; ....; ....; }

System.out.println("This is even number"); } else{ System.out.println("This is not even number"); }

42

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

if(n%2 = = 0){

ll P

DF

int n = 11;

Ed

ito

Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that is not equal to 0 so else block is executed. So "This is not even number" is printed on the screen.

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ] 3. Switch Statement: This is an easier implementation to the if-else statements. The keyword "switch" is followed by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression that creates labels for the case must be unique. The switch expression is matched with each case label. Only the matched case is executed ,if no case matches then the default statement (if present) is executed. Syntax: switch(control_expression){ case expression 1: <statement>; case expression 2: <statement>; ... ... case expression n: <statement>; default: <statement>; }//end switch

switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thrusday"); break; case 5: System.out.println("Friday"); break; case 6:

43

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

int day = 5;

Ed

ito

Example: Here expression "day" in switch statement evaluates to 5 which matches with a case labeled "5" so code in case 5 is executed that results to output "Friday" on the screen.

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ] System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Invalid entry"); break; } Repetition Statements: 1. while loop statements: This is a looping or repeating statement. It executes a block of code or statements till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control comes out of loop. Syntax: while(expression){ <statement>; ...; ...; }

Example: Here expression i<=10 is the condition which is checked before entering into the loop statements. When i is greater than value 10 control comes out of loop and next statement is executed. So here i contains value "1" which is less than number "10" so control goes inside of the loop and prints current value of i and increments value of i. Now again control comes back to the loop and condition is checked. This procedure continues until i becomes greater than value "10". So this loop prints values 1 to 10 on the screen. int i = 1; //print 1 to 10 while (i <= 10){ System.out.println("Num " + i); i++; }

44

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

2. do-while loop statements: This is another looping statement that tests the given condition past so you can say that the do-while looping statement is a past-test loop statement. First the do block statements are executed then the condition given in while statement is checked. So in this case, even the condition is false in the first attempt, do block of code is executed at least once. Syntax: do{ <statement>; ...; ...; }while (expression);

3. for loop statements: This is also a loop statement that provides a compact way to iterate over a range of values. From a user point of view, this is reliable because it executes the statements within this block repeatedly till the specified conditions is true . Syntax: for (initialization; condition; increment or decrement){ <statement>; ...; ...; } initialization: The loop is started with the value specified.

45

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

}while(i <= 10);

Fi

ll P

i++;

DF

Ed

System.out.println("Num: " + i);

ito

rw

ith

do{

Fr ee

int i = 1;

rit

Example: Here first do block of code is executed and current value "1" is printed then the condition i<=10 is checked. Here "1" is less than number "10" so the control comes back to do block. This process continues till value of i becomes greater than 10.

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ] condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated. increment or decrement: After each iteration, value increments or decrements. Example: Here num is initialized to value "1", condition is checked whether num<=10. If it is so then control goes into the loop and current value of num is printed. Now num is incremented and checked again whether num<=10.If it is so then again it enters into the loop. This process continues till num>10. It prints values 1 to10 on the screen. for (int num = 1; num <= 10; num++){ System.out.println("Num: " + num); } Branching Statements:

46

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Example: When if statement evaluates to true it prints "data is found" and comes out of the loop and executes the statements just following the loop.

Fi

ll P

DF

Syntax: break; // breaks the innermost loop or switch statement. break label; // breaks the outermost loop in a series of nested loops.

Ed

ito

rw

ith

1. Break statements: The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for) . It also terminates the switch statements.

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Example:

47

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

Syntax: continue;

ith

Fr ee

2. Continue statements: This is a branching statement that are used in the looping statements (while, do-while and for) to skip the current iteration of the loop and resume the next iteration .

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Syntax: return; return values;

return; //This returns nothing. So this can be used when method is declared with void return type. return expression; //It returns the value evaluated from the expression. Example: Here Welcome() function is called within println() function which returns a String value "Welcome to roseIndia.net". This is printed to the screen.

48

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

3. Return statements: It is a special branching statement that transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. the returned value type must match the return type of method.

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

37.

Define programming. What are the types of programming? Explain.


Programming is the art and science of translating a set of ideas into a program - a list of instructions a computer can follow. The person writing a program is known as a programmer (also a coder). The exact form the instructions take depend on the Programming Language used. Languages run the spectrum from very low level like Machine Language or Assembly, to a very high level like Java. Lower level languages are more closely tied to the platform they are targeted for, while Higher level languages abstract an increasing amount of the platform from the programmer. In other words, low level programming languages represent the instructions in a manner that resembles more closely the way the computer actually works. High level languages do resemble more the way the human mind works. Each type is a good fit depending on the particular case. Whenever speed and resource consumption are important, low level languages can provide an advantage since they cause much less "translation" and are less generic, thus causing less load on the computer[1]. High level languages have much more abstraction and thus are better suited for tasks where maintenance and complex design is required. After a programmer has finished writing the program, it must be executed. Traditionally, some languages (like Basic) are interpreted, while others (like C) are compiled prior to execution. Interpreted languages are executed "on the fly" at run time, while compiled languages have a separate compilation step that must be completed prior to running. Compilers are able to make certain optimizations that are unavailable to interpreters. The program may fail to compile or execute due to syntax errors. These are errors caused by doing something that is unknown or illegal according to the language they have used. These errors have to be corrected before the program will execute.

49

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

If the program runs, the programmer must then verify that the program is working as they intended it to. When things don't go as the programmer intended, the error is said to be a bug. To eliminate bugs, the programmer goes through a process called debugging, where he tries to isolate and fix the source of the problem. Types of Programming Language:- Since from the invention of computers many programming approaches have been tried for various applications. These include techniques such as I. II. III. IV. Unstructured programming, Procedural programming, Modular programming Object-oriented programming. Unstructured Programming Usually, people start learning programming by writing small and simple programs consisting only of one main program. Here main program stands for a sequence of commands or statements, which modify data, which is global throughout the program. We can illustrate this as shown in Fig.A

Fig A: Unstructured programming. The main program directly operates on global data Procedural Programming Languages Procedural programming specifies a list of operations that the program must complete to reach the desired state. This one of the simpler programming paradigms, where a program is represented much like a cookbook recipe. Each program has a starting state, a list of operations to complete, and an ending point. This approach is also known as imperative programming. Integral to the idea of procedural programming is the concept of a procedure call.

50

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

Program

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

51

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Modular Programming With modular programming procedures of a common functionality are grouped together into separate modules. A program therefore no longer consists of only one single part. It is now divided into several smaller parts which interact through

Ed

ito

rw

ith

Two of the most popular procedural programming languages are FORTRAN and BASIC.

Fr ee

Procedures, also known as functions, subroutines, or methods, are small sections of code that perform a particular function. A procedure is effectively a list of computations to be carried out. Procedural programming can be compared to unstructured programming, where all of the code resides in a single large block. By splitting the programmatic tasks into small pieces, procedural programming allows a section of code to be re-used in the program without making multiple copies. It also makes it easier for programmers to understand and maintain program structure.

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


procedure calls and which form the whole program

Object-Oriented Programming In object oriented programming, a complex system is decomposed in accordance to the key abstractions of the problem. Rather than decomposing the problems into steps, we identify objects, which are delivered directly from the vocabulary of the problem domain. we view the world (problem domain) as a set of autonomous agents that collaborate to perform some higher level behavior. Each object in the solution embodies its own unique behavior and each one models some object in the real world. The object is simply a tangible entity that exhibits some well defined behavior. Objects do things we

52

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

Each module can have its own data. This allows each module to manage an internal state, which is modified by calls to procedures of this module. However, there is only one state per module and each module exists at most once in the whole program.

DF

Ed

ito

The main program coordinates calls to procedures in separate modules and hands over appropriate data as parameters.

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


ask them to perform what they do by sending the messages. OOP paradigm helps us to organize the inherent complexities of software systems. Definition It is a method of implementation in which programs are organized as co-operative collection of objects, each of which represents an instance of some class and whose classes all members of a hierarchy of classes united in inheritance relationships.

38. What is JVM ? How does it help to achieve platform independence? If JVM is available for windows then can we run program written on Unix platform ?

53

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system Yes we can run program of written in unix plateform in windows plateform. because

Acronym for Java Virtual Machine. An abstract computing machine, or virtual machine, JVM is a platform-independent execution environment that converts Java bytecode into machine language and executes it. Most programming languages compile source code directly into machine code that is designed to run on a specific microprocessor architecture or operating system, such as Windows or UNIX. A JVM -- a machine within a machine -- mimics a real Java processor, enabling Java bytecode to be executed as actions or operating system calls on any processor regardless of the operating system.

54

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

JRE (Java Runtime Environment)

Ed

Difference between JRE AND JVM A Java Virtual Machine (JVM) is a set of computer software programs and data structures that use a virtual machine model for the execution of other computer programs and scripts. The model used by a JVM accepts a form of computer intermediate language commonly referred to as Java bytecode. This language conceptually represents the instruction set of a stack-oriented, capability architecture. As of 2006, there are an estimated four billion JVM-enabled devices worldwide.

ito

rw

ith

Fr ee

rit

er an d

It is the principal component of Java architecture that provides the cross platform functionality and security to Java. This is a software process that converts the compiled Java byte code to machine code. Byte code is an intermediary language between Java source and the host system. Most programming language like C and Pascal translate the source code into machine code for one specific type of machine as the machine language vary from system to system. So most complier produce code for a particular system but Java compiler produce code for a virtual machine. The translation is done in two steps. First the programs written in Java or the source code translated by Java compiler into byte code and after that the JVM converts the byte code into machine code for the computer one wants to run So the programs files written in Java are stored in .java files and the .java files are compiled by the Java compiler into byte code that are stored in .class file. The JVM later convert it into machine code. In fact the byte code format is same on all platforms as it runs in thesame JVM and it is totally independent from the operating system and CPU architecture. JVM is a part of Java Run Time Environment that is required by every operating system requires a different JRE. JRE consists of a number of classes based on Java API and JVM, and without JRE, it is impossible to run Java. So its portability really made it possible in developing write once and run anywhere software.

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ] For example, establishing a socket connection from a workstation to a remote machine involves an operating system call. Since different operating systems handle sockets in different ways, the JVM translates the programming code so that the two machines that may be on different platforms are able to connect. Ans from Book of this Question:All language compilers translate source code into machine code for a specific computer. Java compiler

produces an intermediate code known as bytecode for a machine that does not exist. This machine is called the Java Virtual Machine and it exists only inside the computer memory. The following Figure 3.4 illustrates the process of compiling a Java program into bytecode which is also referred to as virtual machine code.

The virtual machine code is not machine specific. This machine specific code ( known as machine code) is generated by the Java interpreter by acting as an intermediary between the virtual machine and the real machine as shown in the Figure3.5. Interpreter is different for different machines

55

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ] SOME PROGRAMS:1. Write a java programs to sum of two matrices.
class Test { int[][]A={{2,2,1},{3,1,3},{4,2,2}}; int[][]B={{2,4,6},{1,2,3},{1,3,1}}; int[][]C=new int [3][3]; void OperateMatrix() { System.out.println("The first Matrix is"); for (int a = 0; a < 3; a++) { System.out.println(""); for (int b = 0; b < 3; b++) { System.out.print(A[a][b] + "\t"); } } System.out.println(""); System.out.println(""); System.out.println("The Second Matrix is"); for (int c = 0; c < 3; c++) { System.out.println(""); for (int d = 0; d < 3; d++) { System.out.print(B[c][d] + "\t"); } } System.out.println(""); System.out.println(""); System.out.println("The Sum of two Matrix is"); for (int e = 0; e < 3; e++) { System.out.println(""); for (int f = 0; f < 3; f++) { C[e][f] = A[e][f] + B[e][f]; System.out.print(C[e][f] + "\t"); } } System.out.println(""); } public static void main(String[] args) { Test t = new Test(); t.OperateMatrix();

56

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


} }

2. Write a Java programm to implement recursive binary search.


Ans:

3. Write a program in Java to implement Binary Search.


Ans:
class Binary_Search { int[] a ={ 2, 4, 6, 8, 10, 12, 14, 16, 18 }; int k = 16; void Search() { int low = 0; int high = 8; while (low <= high) {

57

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

class RecursiveBinary { static int[] a ={ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; public void BinarySearch(int[] a, int k, int low, int high) { if (low <= high) { int mid = (low + high) / 2; if (a[mid] == k) { System.out.println(k + " " + "is found at index" + " " + mid); } else if (k < a[mid]) { BinarySearch(a, k, low, mid - 1); } else { BinarySearch(a, k, mid + 1, high); } } } public static void main(String[] args) { RecursiveBinary r = new RecursiveBinary(); r.BinarySearch(a, 14, 0, 9); } }

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


int mid = (low + high); if (k == a[mid]) { System.out.println(k + " is found at index " + mid); break; } else if (k < a[mid]) { high = mid - 1; } else { low = mid + 1; } } } public static void main(String[] args) { Binary_Search binary = new Binary_Search(); binary.Search(); } }

4. In inventory management, the economic order quality for a single item is given by 2*demand rate*setup costs EOQ =Holding cost per item per unit time and the optimal time between order 2*setup costs TBO =demand rate*holding cost per unit time Write a program to compute EOQ and TBQ and TBO, given demand rate (item per unit time) setup costs (per order), and the holding cost (per item per unit time). 15 Marks Ans:
import java.io.*; class InventoryManagement { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); double EOQ; double TBO; double DemandRate; double SetupCosts; double HoldingCost; public void getdata() { try { System.out.println("Enter the Demand rate(Items per unit time)"); DemandRate=Double.parseDouble(br.readLine());

58

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


System.out.println("Enter the setup costs(per order)"); SetupCosts=Double.parseDouble(br.readLine()); System.out.println("Enter the holding costs(per item per unit time)"); HoldingCost=Double.parseDouble(br.readLine()); } catch(Exception e) { } } void Calculate() { try { EOQ=Math.sqrt((2*DemandRate*SetupCosts)/HoldingCost); System.out.println("EOQ:"+" "+EOQ); TBO=Math.sqrt((2*SetupCosts)/(DemandRate*HoldingCost)); System.out.println("TBO:"+" "+TBO); } catch(Exception e) {

Ans: class Test { public void BubbleSort() { try { int length; String temp; String[] array; System.out.println("Enter the size of array"); length = Integer.parseInt(br.readLine()); array = new String[length]; System.out.println("Enter the element for the array"); for (int i = 0; i < length; i++) {

59

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

5. Write a Java program to sort a list strings using bubble sort technique. //may be some error plz check

Fi

ll P

DF

Ed

} } public static void main(String[]args) { InventoryManagement IM=new InventoryManagement(); IM.getdata(); IM.Calculate(); } }

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


array[i] = br.readLine(); } for (int pass = 1; pass < length; pass++) { for (int c = 0; c < length - pass; c++) { if (array[c].compareTo(array[c + 1]) > 0) { temp = array[c]; array[c] = array[c + 1]; array[c + 1] = temp; } } } System.out.println("The sorted String is"); for (int s = 0; s < length; s++) { System.out.println(array[s]); } } catch (Exception e) { System.out.println(e); } } public static void main(String[] args) { Test t = new Test(); t.BubbleSort(); } }

6. Write a Java programme to find sum of even and odd numbers in the given array?
Ans: import java.io.*; class Test { int[] a ; int length; int sumeven = 0; int sumodd = 0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); void Addition() { try {

60

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


System.out.println("enter the length of array"); length = Integer.parseInt(br.readLine()); a = new int[length]; System.out.println("Enter the array elements"); for (int p = 0; p < length; p++) { a[p] = Integer.parseInt(br.readLine()); } for (int q = 0; q < length; q++) { if (a[q] % 2 == 0) { sumeven = sumeven + a[q]; } else { sumodd = sumodd + a[q]; } } System.out.println("Sumeven:" + " " + sumeven); System.out.println("Sumodd:" + " " + sumodd); } catch (Exception e) { System.out.println(e); }

7. Write a Java programme to sort a list of numbers.


Ans: import java.io.*; class Sort { int length; int[] a;// BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public void Sorting() { try { System.out.println("Enter the length of array"); length = Integer.parseInt(br.readLine()); a = new int[length];

61

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

} public static void main(String[] args) { Test t = new Test(); t.Addition(); }

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


System.out.println("enter the elements of array"); for (int r = 0; r < length; r++) { a[r] = Integer.parseInt(br.readLine()); } for (int i = 0; i < length; i++) { int j = i; for (int k = i + 1; k < length; k++) { if (a[k] < a[j]) { j = k; } } int temp = a[i]; a[i] = a[j]; a[j] = temp; } System.out.println("The sorted element is"); for (int t = 0; t < length; t++) { System.out.println(a[t]); } } catch (Exception e) { System.out.println(e); }

public static void main(String[] args) { Sort s = new Sort(); s.Sorting(); } } 8. Write a class box with the variable width, depth and height and constructor to assigning the values of these variables and a method to find the volume of the box and also write the main program, which creates the box object, and find the volume of the box. Print the result on the screen. Ans: class Box { double width; double height; double depth;

62

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


public Box() { width = 10; height = 10; depth = 10; } public void Volume() { double result = width * height * depth; System.out.println("The volume of the box is " + " " + result); } public static void main(String args[]) { Box b = new Box(); b.Volume(); } } 9. Write a Java programme to find whether the given string is palindrome or not. Ans: import java.io.*; class Test { String str; boolean Test; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public void PalinTest() { try { System.out.println("Enter the string"); str = br.readLine(); int startindex = 0; int lastindex = str.length() - 1; while (startindex < lastindex) { if (str.charAt(startindex) == str.charAt(lastindex)) { Test = true; startindex++; lastindex--; } else { Test = false; System.out.println(str + " " + "is not a palindrome"); return; } } if (Test == true) {

63

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


System.out.println(str + " " + "is a palindrome"); } } catch (Exception e) { } } public static void main(String[] args) { Test t = new Test(); t.PalinTest(); } }. 10.Write a Java program to find sum of integer numbers from 50 to 100 which are divisible by 9. class Division { int i; int sum = 0; void calculate() { for (i = 50; i <= 100; i++) { if (i % 9 == 0) { sum = sum + i; } } System.out.println("The sum is " + " " + sum); } public static void main(String[] args) { Division d = new Division(); d.calculate(); } } 11.Write a program with minimum number of if statements. A cloth showroom has announced the following seasonal discounts on purchase of items Discount Purchase amount Millcloth Handloom items 0 -100 0% 5.0 % 101-200 5.0 % 7.5 % 201-300 7.5 % 10.0 % Above 300 10.0 % 15.0 % Ans: import java.io.*; class Test

64

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


{ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); public void DiscountTest() { try { double PurchaseAmount; double MillDiscount, HandloomDiscount; String Choice, Item; System.out.println("Enter the purchase amount"); PurchaseAmount = Float.parseFloat(br.readLine()); System.out.println("Enter the Item type"); Item = br.readLine(); if (PurchaseAmount <= 100) { if (Item.equals("Millcloth")) { MillDiscount = (PurchaseAmount * 0) / 100; System.out.println("MillDiscount:" + " " + MillDiscount); } else { HandloomDiscount = (PurchaseAmount * 5) / 100; System.out.println("HandloomDiscount:" + " " + HandloomDiscount); } } else if (PurchaseAmount > 100) { if (PurchaseAmount <= 200) { if (Itemequals("Millcloth")) { MillDiscount = (PurchaseAmount * 5) / 100; System.out.println("MillDiscount:" + " " + MillDiscount); } else { HandloomDiscount = (PurchaseAmount * 7.5) / 100; System.out.println("HandloomDiscount:" + " " + HandloomDiscount); } } } else if (PurchaseAmount > 200) { if (PurchaseAmount <= 300) {

65

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


if (Itemequals("Millcloth")) { MillDiscount = (PurchaseAmount * 7.5) / 100; System.out.println("MillDiscount:" + " " + MillDiscount); } else { HandloomDiscount = (PurchaseAmount * 10) / 100; System.out.println("HandloomDiscount:" + " " + HandloomDiscount); } } } else if (PurchaseAmount > 300) { if (Itemequals("Millcloth")) { MillDiscount = (PurchaseAmount * 10) / 100; System.out.println("MillDiscount:" + " " + MillDiscount); } else { HandloomDiscount = (PurchaseAmount * 15) / 100; System.out.println("HandloomDiscount:" + " " + HandloomDiscount); } } } catch (Exception e) { System.out.println(e); } } public static void main(String[] args) { Test t = new Test(); t.DiscountTest(); } }

12.
Ans:

Write a java program to concatenate two strings. 7 Marks

class Test { void MyFunction() {

66

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


String FirstName = "Raj"; String LastName = "Singh"; String FullName = FirstName + " " + LastName; System.out.println("My Name is" + " " + FullName); } public static void main(String[] args) { Test t = new Test(); t.MyFunction(); } }

13. Write a program to create a thread by extending the thread class. 8 Marks
class MyThread extends Thread { public void run() { for (int i = 0; i <= 5; i++) { System.out.println("Raj"); } } public static void main(String[] args) { MyThread t = new MyThread(); t.start(); } }

SOME SHORT EXPLANATION:-

1. Explain the methods


Trim- The Trim method returns a copy of the invoking string from which any leading and trailing white space are removed. The general form of Trim method is String.trim(). Example of trim method: class Test { String str="Rajesh kumar"; void TrimTest() { str=str.trim(); System.out.println(str); }

67

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


public static void main(String[]args) { Test t=new Test(); t.TrimTest(); } } The trim( ) method is quite useful when we process user commands. For example, the following program prompts the user for the name of a state and then displays that states capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user. import java.io.*; class UseTrim { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter 'stop' to quit."); System.out.println("Enter State: "); do { str = br.readLine(); //str = str.trim(); // remove whitespace if(str.equals("India")) System.out.println("Capital is Delhi."); else if(str.equals("Bihar")) System.out.println("Capital is Patna."); else if(str.equals("Goa")) System.out.println("Capital is Panji."); // ... } while(!str.equals("stop")); } }

Substring we can extract a substring using substring( ). It has two forms. The first is String substring(int startIndex) Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string. The second form of substring( ) allows you to specify both the beginning and ending index of the substring: String substring(int startIndex, int endIndex) Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.

68

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

class Test { String str="Rajesh kumar"; void SubStringTest() { str=str.substring(0,7); System.out.println(str); } public static void main(String[]args) { Test t=new Test(); t.SubStringTest(); } } Length. Length : The number of character contained in a string is called the length of the string. Java uses length() method to know the length of a string. The general form of length method is String.length(). class Test { String str="Kalpana Kumari"; void LengthTest() { int j=str.length(); System.out.println(j); } public static void main(String[]args) { Test t=new Test(); t.LengthTest(); } }

OOP Language :- OOPL The use of a class of programming languages and techniques based on the concept of an "object" which is a data structure (abstract data type) encapsulated with a set of routines, called "methods", which operate on the data. Operations on the data can __only__ be performed via these methods, which are common to all objects that are instances of a particular "class". Thus the interface to objects is well defined, and allows the code implementing the methods to be changed so long as the interface remains the same.Each class is a separate module and has a position in a "class

69

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


hierarchy". Methods or code in one class can be passed down the hierarchy to a subclass or inherited from a superclass. This is called "inheritance".

[2] Explain following statements with their syntax:


if _else and switch: if statement is a powerful decision making statement and is used to control the execution of statements. It is basically two way decision making statement. The general form of ifelse statement is if(test expression) { True block statement(s) } else { False block statement(s) } If the test expression is true then the statements in the true blocks are executed and if the test expression is false then the statement in false block is executed. Switch: A switch statement allows us to test the value of an expression and depending on the value control of the program executes. The expression must be an integer or character value. It cannot be a string or a real number. The position to jump is marked with case constant. This marks the computer to jump to a given case when the expression evaluates to the given constant. A switch statement provides default case which is optional. There is a break statement in each switch case which is optional. The breaks statement is used to jump out of the switch statement. If a break statement is left then computer executes all the cases. The syntax of switch statement: switch(expression) { case 1: Statement 1 break; case 2: statement 2 break; default: break; } go to and continue: go to: java doesnt uses the goto keyword but it is reserved keyword for the future use. Go to statement specifies the completion of a task. Continue: The continue statement is used in a situation when statements in the loop are not to be executed depending on a condition. The continue statement stops the current iteration and starts the next iteration of the same loop. Continue

70

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


statements take the control back to the loop. The keywords used to declaring continue statement is continue. Example of continue statement: class Test { public static void main(String[]args) { for(int i=0;i<10;i++) { if (i == 8) { continue; } System.out.println(i+.+rAJ); } } }

While and do while While: While statement consists of a condition and a loop body. The condition is enclosed within the parenthesis. All the variables used in condition of while loop should be initialized before the while loop begins. The value of variables used in condition must change in the loop body. Otherwise condition will always remains true causing loop to run infinitely. Single or multiple statements can be written within the loop body. Multiple statements should be enclosed within braces. Otherwise the code may generate an unexpected output. Condition is evaluated first if the condition holds true then only the loop body is executed. After loop body is executed condition is evaluated again. The process of evaluating condition and executing loop body continues until the condition becomes false. Syntax of while loop is While (Test Condition) { body of the loop};. Do While: Do while loop performs certain repetitive action depending on a condition. All the variables used in condition of while loop should be initialized before the while loop begins. The value of variables used in condition must change in the loop body. Otherwise condition will always remains true causing loop to run infinitely. Single or multiple statements can be written within the loop body. Multiple statements should be enclosed within braces. Otherwise the code may generate an unexpected output. In do while loop the loop body is executed at least once regardless of condition being true or false. After loop body is executed the condition is checked. If the condition evaluates

71

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


true then loop body is executed repeatedly until condition becomes false. Syntax of do while is do { loop body} while (Condition);

While and for


While: While statement consists of a condition and a loop body. The condition is enclosed within the parenthesis. All the variables used in condition of while loop should be initialized before the while loop begins. The value of variables used in condition must change in the loop body. Otherwise condition will always remains true causing loop to run infinitely. Single or multiple statements can be written within the loop body. Multiple statements should be enclosed within braces. Otherwise the code may generate an unexpected output. Condition is evaluated first if the condition holds true then only the loop body is executed. After loop body is executed condition is evaluated again. The process of evaluating condition and executing loop body continues until the condition becomes false. Syntax of while loop is While (Test Condition) { body of the loop};. For: For loop is used to perform a function depending on a condition. A for loop begins with the keyword for. For loop has three elements enclosed within parentheses. The first element is the initialization expression. The initialization expression is an assignment statement. The assignment is done only once before the statement begins execution. The second element is test condition which is evaluated before each iteration of for statement. The test condition decides whether the loop should continue or terminates. Update expression is third element. This element changes the value of variables used in test condition. Update expression is executed at the end of each iteration after loop body is executed. The elements are separated by semicolons. Syntax of for loop is for (initialization exp; test condition; update exp) {loop body}

Break and continue Break: Break statement is used to force immediate end of loop by passing 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. Continue: The continue statement stops the current iteration of the loop and immediately starts the next iteration of the same loop on a conditional expression. When a continue statement is encountered inside a loop the statement after continue is not executed.

72

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]

Distinguish between the following terms:


Objects and classes Data abstraction and data encapsulation Inheritance and polymorphism Dynamic binding and message passing

Ans.

Objects and classes: Object is a physical entity which represents

Data abstraction and data encapsulation: Abstraction - the act or process of leaving out of consideration one or more qualities of a complex object so as to attend to others. Solving a problem with objects requires you to build the objects tailored to your solution. We choose to ignore its inessential details, dealing instead with the generalized and idealized model of the object. Encapsulation - The ability to provide users with a well-defined interface to a set of functions in a way, which hides their internal workings. In object-oriented programming, the technique of keeping together data structures and the methods (procedures) which act on them. The easiest way to think of encapsulation is to reference phones. There are many different types of phones, which consumers can purchase today. All of the phones used today will communicate with each other through a standard interface. For example, a phone made by GE can be used to call a phone made by Panasonic. Although their internal implementation may be different, their public interface is the same. This is the idea of encapsulation.

Inheritance and polymorphism: Inheritance in object-oriented programming means that a class of objects can inherit properties from another class of objects. When inheritance occurs, one class is then referred as the 'parent class' or 'superclass' or 'base class'. In turn, these serve as a pattern for a 'derived class' or 'subclass'. Inheritance is an important concept since it allows reuse of class definition without requiring major code changes. Inheritance can mean just reusing code, or can mean that you have used a whole class of object with all its variables and functions. Polymorphism: It is a key concept in object-oriented programming. Poly means many, morph means change (or 'form').

73

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

a person, vehicle or a conceptual entity (thing in existence) like bank account, company etc. A set of variables and functions used to describe an object is a "class". A class defines the structure and behavior (data and code) that will be shared by a set of objects. Each object 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. A class is a logical construct. An object has physical reality. When you create a class, you will specify the code and data that will constitute that class. Collectively, these elements are called the members of the class. Specifically, the data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods, which define the use of the member variables.

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


Polymorphism is simply a name given to an action that is performed by similar objects. Polymorphism allows a common data-gathering message to be sent to each class and allows each subclass object to respond to a message format in an appropriate manner to its own properties. Polymorphism encourages something we call 'extendibility'. In other words, an object or a class can have its uses extended.

Thread states

Execution of a thread To execute a thread, the thread is first created and then the start() method is invoked on the thread. Eventually the thread would execute and the run method would be invoked. The example below illustrates the two methods of thread creation. You should note that the run method should not be invoked directly. public class ThreadExample extends Thread { public void run() { System.out.println("Thread started"); } public static void main(String args[]) { ThreadExample t = new ThreadExample(); t.start(); }

74

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Threads A thread is in process in execution within a program. Within a program each thread defines a separate path of execution. Creation of a thread A thread can be created in two ways a) By implementing the Runnable interface. The Runnable interface consists of only one method - the run method. The run method has a prototype of public void run(); b) By extending the class Thread.

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

Write a short note on:

rit

er an d

Dynamic binding and message passing: Dynamic binding in java is the mechanism by which compiler cannot determine which method implementation to use in advance. Based on the class of the object, the runtime system selects the appropriate method at runtime. Dynamic 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 (when needed) by the Java runtime system. Loaded classes are then dynamically linked with existing classes to form an integrated unit. The lengthy link-and-load step required by third-generation programming languages is eliminated. Message Passing: In an object based world the only way for anything to happen is by objects communicating with each other and acting on the results. This communication is called message passing and involves one object sending a message to another and (possibly) receiving a result.

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


} Example - Creation of Thread by extending the Thread class.

When the run method ends, the thread is supposed to "die". The next example shows the creation of thread by implementing the Runnable interface. public class ThreadExample2 implements Runnable { public void run() { .../* Code which gets executed when thread gets executed. */ } public static void main(String args[]) { ThreadExample2 Tt = new ThreadExample2(); Thread t = new Thread(Tt); t.start(); } }

Example - Creating thread by implementing Runnable

States of thread A thread can be in one of the following states - ready, waiting for some action, running, and dead. These states are explained below. Running State A thread is said to be in running state when it is being executed. This thread has access to CPU. Ready State A thread in this state is ready for execution, but is not being currently executed. Once a thread in the ready state gets access to the CPU, it gets converted to running state. Dead State A thread reaches "dead" state when the run method has finished execution. This thread cannot be executed now. Waiting State In this state the thread is waiting for some action to happen. Once that action happens, the thread gets into the ready state. A waiting thread can be in one of the following states - sleeping, suspended, blocked, waiting for monitor. These are explained below. Yielding to other processes A CPU intensive operation being executed may not allow other threads to be executed for a "large" period of time. To prevent this it can allow other threads to execute by invoking the yield() method. The thread on which yield() is invoked would move from running state to ready state. Sleep state of a thread A thread being executed can invoke the sleep() method to cease executing, and free up the CPU. This thread would go to the "sleep" state for the specified amount of time, after which it would move to the "ready" state. The sleep method has the following prototypes. public static void sleep (long millisec)

75

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

DF

Ed

ito

rw

ith

Fr ee

rit

er an d

To

ols

[ JAVA SOLUTION OF PREV YEARS 2006-JUN 2009 ]


throws InterruptedException; public static void sleep (long millisec, int nanosec) throws InterruptedException; Synchronized state A code within the synchronized block is "atomic". This means only one thread can execute that block of code for a given object at a time. If a thread has started executing this block of code for an object, no other thread can execute this block of the code (or any other block of synchronized code) for the same object. public synchronized void synchExample() { /* A set of synchronized statements. Assume here that x is a data member of this class. */ if(x == 0) x = 1; }

Packages:-

Declare the package at the beginning of a file using the package keyword. package <package_name> Define the class that is to be put into the package and declare it public. Create the subdirectory under the directory where the main source file is stored. Store the listing as the class_name.java file in the subdirectory.

Exception handling:An exception is a run time error. Most of the computer languages do not support exception handling. Errors must be checked and handled manually. This is cumbersome and troublesome. Java provides the facility of exception handling and avoids the above problems. By this run time error management becomes easy. A Java exception is an object that describes an error condition that has occurred in a piece of code. When an error or an exceptional condition arises, an object representing that exception is created and is 'thrown' in the method that caused the error. The method may handle the exception itself or pass it on. In this way, the

76

Solved by: - Rajesh & Ashish [ AshuRaj ]

PD

Fi

ll P

The procedure to create you own package is:

DF

Classes contained in packages of other programs can be reused. Two classes in two different packages can have the same name. Packages provide a way to hide classes. Designing is separated from coding by the use of packages.

Ed

ito

rw

ith

Packages are Java's way of grouping a variety of classes and/or interfaces together. The grouping is done according to functionality. By organizing the classes into packages, we get the following benefits:

Fr ee

Packages are containers for classes that can be shared by Java programs. Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.

rit

er an d

To

ols

PD Fi ll P DF Ed ito rw ith Fr ee W rit er an d

To

ols

Das könnte Ihnen auch gefallen