java sample questions

23
1. Give the features of Java. Java as a language has features that make it unique from other languages. The following are the notable features of java; Portable: The java feature write once run everywhere make java portable. This is seen in that a program can be written in a windows system and it runs on linux or mac systems incase java virtual machine is present.Futher more under portability size and behavior of basic datatypes is defined that is to say the sizes of primitive datatypes are always the same. It should also be noted that java libraries define portable interfaces. Secure: with java it has been noted that it is secure due to the fact that restrictions can be forced(using public ,private). With public any class can access that particular class while with private no other class can access and use the specified class. Java in addition to restrictions java is secure because of extensive compile time- checking and runtime checking. Furthermore being able to manage memory automatically make java more stable Robust: java has a strong memory allocation and automatic garbage collection mechanisms. These features make java stable in that it provides type checking mechanism and powerful exception handling. Here the compiler checks if there are any errors in the program well as the interpreter checks if there any runtime errors and makes the system more secure from crashes.

Upload: sean-eldrin

Post on 19-Nov-2014

106 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java sample questions

1. Give the features of Java.

Java as a language has features that make it unique from other languages. The following are the notable features of java;

Portable: The java feature write once run everywhere make java portable. This is seen in that a program can be written in a windows system and it runs on linux or mac systems incase java virtual machine is present.Futher more under portability size and behavior of basic datatypes is defined that is to say the sizes of primitive datatypes are always the same. It should also be noted that java libraries define portable interfaces.

Secure: with java it has been noted that it is secure due to the fact that restrictions can be forced(using public ,private). With public any class can access that particular class while with private no other class can access and use the specified class. Java in addition to restrictions java is secure because of extensive compile time- checking and runtime checking. Furthermore being able to manage memory automatically make java more stable

Robust: java has a strong memory allocation and automatic garbage collection mechanisms. These features make java stable in that it provides type checking mechanism and powerful exception handling. Here the compiler checks if there are any errors in the program well as the interpreter checks if there any runtime errors and makes the system more secure from crashes.

Simple: there are various features that make java simple. first its programs are easy to write and debug because in java pointers are not used explicitly. Secondly java makes it harder to write programs that make the system crash hence making it simple since programmer does not have to worry of writing a program capable of crashing the system. Furthermore due to its memory management java provides a bug free system.

Dynamic: this is another important feature 0f java under this feature when executing file the user can get the required files dynamically from the local drive or from another computer far away from the user by simply connecting to the internet.

Object oriented: in order for java to be called object oriented it has been noted that java has the following: inheritance-this is the process of creating new classes and using the behaviors of existing classes by extending them just to reuse existing code and adding additional features. Polymorphism-it is a way of providing different functionally to a function having the same name. Under this there can be one name with multiple forms. Encapsulation- this is a way of

Page 2: Java sample questions

combining information one on top of the other. Dynamic binding- under this when writing we don’t have knowledge of objects about their specific type thus dynamic binding come in as a way of providing maximum functionality to a program about the specific type at runtime

Platform independent: java is considered platform independent because of the concept of write-once run anywhere (also known as architecture neutral) is another important feature that make java a powerful programming language. Under this the program written on one platform can be run on any platform having a java virtual machine

Distributed: today protocols like HTTP and FTP are developed in java. Because of this many internet programmers can call functions on these protocols and get access to file from any remote machine on the internet rather than writing codes on their local machines.

Performance: this is another additional feature of java that makes it standout. under this java uses native code usage and light weight processes called threads. Java uses adaptive and just in time compilation techniques these improve on performance.

Multithreaded: this is another feature of java. First multithreading is when a single program has multiple threads executing independently at the same time. Multithreading is a very interesting concept in java in that in multithreaded programs not even a single thread disturbs the other in execution.

Page 3: Java sample questions

2. What do you mean by the statement: System.out.println(“”);

This statement is used to give the output of the value that the program will give

This here means the following System- will tell the compiler to access the class (not it begins with a capital just like class name), out- this tell the compiler that the value will be printed onto the screen after execution of the program. Println this will inform the compiler that the next output from the program will be printed on a new line. . the parenthesis (“”) is used to give the compiler the variable that will hold the final value after execution has been complete. The (“;”) this usually come at the end andis used to notify the compiler that the execution has come to an end.

Page 4: Java sample questions

3.What are the different types of control statements in Java?Control statements are used to control the flow of program execution. The order of execution however will depend on the supplied data and the conditional logic. Basically control statements include: a. Decision making statements and under decision making we have the following;

- If statement- this decision making statement executes a block of code when a given condition is true and if its false it skips the if block and executes the rest of the code in the program

- If –else statement- this is an extension of the if statement that provides another option if the “if” statement is false that is to say when the “if” statement is false the else block is executed.

- Switch- this is a simplification of the nested if statement because sometimes nested if are lengthy and become cumbersome. The switch statement is followed by an expression that should evaluate to byte, short, char or int primitive data types. In the switch there are one or more labeled cases and the expression that created the cases is unique. Also the switch expression is matched with the case label and only those that match are executed. If no case matches then the default statement is executed if it is present.

b. looping statements under this we have:

- For loop- this looping statement provides the concept of iteration. Iteration is basically repetition of similar tasks and this is done without any errors. With this the specified condition is repeated until it is trueIts syntax is for (initialization; condition; increment/decrement); with initialization the loop is started with specifying a value, condition determines whether its true or false if false if false the loop is terminated, increment or decrement here after each iteration the value is increased or decreased

- While loop- the while keeps executing a block of statements as long as a particular condition is true. With this loop it continues testing the condition and continues executing block of code. when the condition is false control comes out of loopSyntax while (expression) {

<Statement>;…………;………….;

Page 5: Java sample questions

}- do while loop- with the do while loop it first executes then later checks the condition.

Here first the “do” block of statement are executed the the condition given in the “while” statement is checked. Here even if the condition is false the block code is executed at least once

Syntax: do

{

<statement>;

…………..;

…………..;

} while (expression);

c. Branching statements: this is another group of control statement. in this category we have the following:

- break statement- this is used for breaking the execution of a loop(while, do- while and for). it also terminates switch statements. The break statement contains two form labeled and unlabeled .break unlabeled breaks the innermost loop or switch statement while labeled breaks the outermost loop in a series of nested loops.

- continue statement- this is used to skip the current iteration of the loop and go to the iteration. This is used in the following while, do- while , for

- return statements-with return statements they are used to return a value to the caller method and terminates the execution of the method. Return statements are of two form those that return a value and those that do not.

Page 6: Java sample questions

4.List out the functions provided by StringBuffer class in Java.

Stringbuffer class is used to implement a string of mutable characters that can be modified.

With string buffer classes at any point of time they contain a particular sequence of characters

but the length and content of a sequence can be changed thrpugh certain method call. String

buffer has a number of functions it provides these include:

- capacity()- this is used to know about the current characters kept that is to say the

capacity of the characters for example: number of characters+6

- append()- this is another function provided by the stringbuffer class. Here this is used

to concatenate the string in the buffer. Append() is better used for dynamic string

concatenation. This function it should be noted that it works as a simple string

concatenation such as ‘string str1= str1+”the added string;”’

- insert()- this function is used to insert or put in any string or character at a specified

position in the given string.

- setCharAt()-this is used to replace a particular character within the same string

- charAt()- this function is used to get the character at a specified position of the given

string. it returns the character at a specified index within then string in which the first

character has index 0.

- delete()- this is used to delete multiple character from say position a to position b in

the buffered string. in this case position a and b are set by the user or the programmer

Page 7: Java sample questions

- length()- this function returns the character length of the string or in short is used to

find the length of the buffered string

- deleteCharAt()- this function is used for deleting the specific character from the

buffered string by mentioning the position of that specific character

- substring()- this function is used to give the sub string of the buffered string from the

initial position to the end position the initial and end positions are specified by the

user.

- reverse()- its used to reverse the string present in the buffered string. It plays its

function by reversing all the characters in the string.

Page 8: Java sample questions

5.What are the rules for overriding a method in Java?

In java when a method is the subclass has the same name and type signature then the

method in the subclass is said to override the one in the superclass. This procedure of

overriding follows some rules. The following are the rules followed in java when

overriding a method;

- the signature including the number and type of arguments for the overriding method

should be the same

- the return type of the subclass should be the same as the superclass or should be co-

variant return

- furthermore another rule of method overriding is that the overriding method should

not throw exceptions other than those thrown by the method in the superclass

- the access modifier of the overriding method in the subclass should not be more

limiting than the superclass method that is to say it should be the same or less or less

restrictive an example is say when the superclass contains protected the subclass

should be protected or public

- another rule for method overriding is that the constructor cannot be overridden

- furthermore with method overriding the final method cannot be overridden

- another notable rule to method overriding is that once a method is declared as private

it cannot be overridden as it is not visible outside the class

Page 9: Java sample questions

- Furthermore with method overriding any unchecked exception are thrown.

- Finally with method overriding in the case of checked exceptions we can throw fewer

or narrow checked exceptions

Page 10: Java sample questions

6. What is bytecode? Explain.

In java bytecode is a highly optimized set of instructions which are designed to be

executed by the java runtime system also known as the java virtual machine. In java

when we write a program it will be known as source code. This is then converted to byte

code by the compiler which generates the bytecode which is then converted to

machinecode or deployed by the interpreter. It should be noted that the bytecode is

machine independent that’s why it is run on different machines with java virtual machine.

The name bytecode rises from instruction sets which have one-byte op codes

followed by optional parameters. Bytecodes may be used to reduce hardware and

operating system dependence by allowing the same code to run on different platforms.

Also bytecode may be often either directly executed on a virtual machine (i.e.

interpreter) or it may be further compiled into machinecode for better performance.

Furthermore bytecodes are compact numeric codes, constants and references

(normally numeric addresses) which encode the result of parsing and semantic

analysis of things like type, scope and nesting depths of program objects. They

therefore allow much better performance than direct interpretation of sourcecode.

Page 11: Java sample questions

7. How do you compile a Java program?

With this case I shall presume that the jdk (java development kit) was already installed

and set to run on the system. So first we shall open the command prompt which can be

located on the start menu.

Next type the following “cd c:\ foldername” (in the command prompt panel) - the

folder name in this case is the default folder which was set to store all the java programs

created. For this specific example we shall use javaprograms thus we shall type it as “cd

c:\javaprograms” the press ENTER to proceed to the next step

On the next line of the command prompt which appears as c:\javaprogram> not that

javaprograms is our foldername we declared. Type the following “javac Classname.java”

in this case when we save our programs we give it a name usually its class here the

classname shall be Add.java thus it shall appear as “javac Add.java” and then press

ENTER

Next :

Case 1

type “java classname in this case we shall type “ java Add”. This is done when the

value are declared in the program. And press ENTER ,the result of the add will be

declared

Case 2

When you have to pass the values using command line arguments type the following

“java class name value1 value 2” then press ENTER the values will be displayed

after the addition has been done.

Page 12: Java sample questions

Syntaxes

- cd c:\foldername (javaprograms)

- Javac classname.java( Add.java)

- Java classname (without using command line arguments) or java classname value 1

value 2(using command line arguments).

Page 13: Java sample questions

8. Write a Java program to print the address of the study center.

class Address

{

public static void main(String arg[])

{

String name="SIKKIM MANIPAL UNIVERSITY OF HEALTH,MEDICAL AND

TECHNOLOGICAL SCIENCES";

String center="international school of business and technology(ISBAT)";

String detail="Ganesh plaza,plot 24-26 entebbe road p.o box 28220";

String tel="256-041-237525/237525 kampala uganda";

System.out.println(name);

System.out.println(center);

System.out.println(detail);

System.out.println(tel);

}

}

Page 14: Java sample questions

9. List out various String comparison functions in Java.

Java has various string comparison functions these include the following;

a. Equal()- with this function we examine the text content or value of the two string

variables. Here two objects may be different but they have the same value. The equals

operator however is case sensitive for example “abc” and “ABC” returns false however

when “abc” and “abc” the return value is true.

b. equalsIgnoreCase()- this function is almost the same as above only that it ignores if the

two stings are uppercase or lower case thus in this case taking “abc” and “ABC” will

always return true as its output.

c. regionMatches()- this function this compares a specific region in one string with another

specific region in another string. The result is usually true when these substrings represent

identical character sequences. It has the following format regionMatches(int toffset, String

str, into offset, int len). Where toffset shows the starting offset of the substring in this

region, str represents the string arguments, ooffset shows starting offset of the substring in

this region, len shows the number of characters to compare. It always returns true if the

specified subregion of this string exactly matches the specified subregion of the string

argument, otherwise its false.

d. startsWith()- this function tests if a string starts with a specific prefix beginning a specific

index. This awalys returns true if if the character sequence represented by the argument if

a prefix of the substring of the object starting at index toffset otherwise it gives false. It

has this syntax startsWith(string Prefix).

Page 15: Java sample questions

e. endsWith()- this function tests if a string nds with a specific prefix. It always returns true

when the condition is met otherwise it returns false. This is its syntax endsWith(string

suffix)

f. compareTo()- this serves this purpose when we want to know if one string is greater than,

equal to or less than the other. A string is greater than the other if it comes after the other

in a dictionary. It has the following form int compareTo( String str). Here str is the string

compared with the invoking string. This function is case sensitive thus if say “Then” and

“then” are compared Now will come first since it has the lower ASCII value than now.

Page 16: Java sample questions

10. What are the uses of interfaces?

Interfaces in java are a list of methods that must be defined by any class that implements

that interface. Interfaces have their uses in java for example;

In java it is impossible to implement multiple inheritance however with interface this can

be possible. In java a class can only inherit from one class but can implement more than one

class. This means that if a variable is declared to be the type of an interface, its value can

reference any object that is instantiated from any class that implements the interface.

Furthermore interfaces can be used in java to prevent a class from inheriting from unrelated

classes just to get the required functionality.

Also interfaces in java can be used to ensure that a class adheres to the contract of the

interface that you specified, this further makes java interfaces nice and clean. Thus an interface

can be used to enforce these contracts.