Top Banner
Technical Aptitude SAMBHRAM INSTITUTE OF TECHNOLOGY “TECHNICAL APTITUDE ” Department of Master of Computer Applications Prepared by Namratha K Asst. Professor By: Namratha K, Asst. Prof., Sambhram Institute of Technology Page 1
91

Technical Aptitude · Web viewSAMBHRAM INSTITUTE OF TECHNOLOGY “ TECHNICAL APTITUDE ” Department of Master of Computer Applications Prepared by Namratha K Asst. Professor Contents:

Feb 01, 2021

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

Technical Aptitude

Technical Aptitude

SAMBHRAM INSTITUTE OF TECHNOLOGY

“TECHNICAL APTITUDE ”

Department of Master of Computer Applications

Prepared by Namratha K Asst. Professor

Contents:

1. Programming with C3

2. Object Oriented Programming Using C++28

3. Programming with Java 36

Chapter 1: Programming with C

(1) What will be output if you will compile and execute the following c code? struct marks{int p:3;int c:3;};void main(){struct marks s={2,-6};printf(“%d %d”,s.p,s.c);}

(a) 2 -6(b) 2 1(c) 2 2(d) Compiler error

Ans:cExp: Binary value of 2: 00000010 (Select three two bit)Binary value of 6: 00000110Binary value of -6: 11111001+1=11111010(Select last three bit)

(2) What will be output if you will compile and execute the following c code? #includevoid main(){int i;float a=5.2;char *ptr;ptr=(char *)&a;for(i=0;i<=3;i++)printf(“%d “,*ptr++);}

(a)0 0 0 0(b)Garbage Garbage Garbage Garbage(c)102 56 -80 32(d)102 102 -90 64

Ans: bExp: *ptr++ will increment the address every time so we cant guess the value present in that address

(3) What will be output if you will compile and execute the following c code?#includeVoid main(){printf(“%s”,”c” “question” “bank”);} (a) c question bank(b) c(c) bank(d) cquestionbank

Ans :dExp: In c string constant “xy” is same as “x” “y”

(4) What will be output if you will compile and execute the following c code?#includeint main(){char *str=”c-pointer”;printf(“%*.*s”,10,7,str);return 0;}

(a) c-pointer(b) cpointer(c) cpointer null null(d) c-point

Answer: (d) Explanation: Meaning of %*.*s in the printf function:First * indicates the width i.e. how many spaces will take to print the string and second * indicates how many characters will print of any string.

(5) What will be output if you will compile and execute the following c code?#includeint main(){int a=-12;a=a>>3;printf(“%d”,a);return 0;} (a) -4 (b) -2 (c) -3 (d) -96

Answer :(b) Explanation:Binary value of 12 is: 00000000 00001100-12 is 2’s com of 12 =>11111111 11110100While performing 3 left shift value becomes => 111111 111110 => -2

(6) What will be output if you will compile and execute the following c code?#include#includeint main(){printf(“%d %d”,sizeof(“string”),strlen(“string”));return 0;} (a) 7 6(b) 7 7(c) 6 7(d) 6 6

Answer: (a) Explanation: char has memory of 1 byte so sizeof(“string”)=>7 including null char; strlen(“string”)=>6 which is the length.

(7) What will be output if you will compile and execute the following c code?#includeint main(){int a=1,2;int b=(1,2);printf(“%d %d”,a,b);return 0;} (a)1,1(b)1,2(c)2,1(d)2,2Ans:bExp:1,2 will think as array and a[0]which is same as a will be assigned as 1(1,2) comma operator will lead to right most one so it returns 2

(8) What will be output if you will compile and execute the following c code?#includeint main(){int i=0;if(i==0){i=((5,(i=3)),i=1);printf(“%d”,i);}elseprintf(“equal”);} (a) 5(b) 3(c) 1(d) equalAns :c Exp: refer previous exp

(9) What will be output if you will compile and execute the following c code?

#include#define message “union is\power of c”int main(){printf(“%s”,message);return 0;} (a) union is power of c(b) union ispower of c(c) union isPower of c(d) Compiler errorAns:bExp: If you want to write macro constant in new line the end with the character \.

(10) What will be output if you will compile and execute the following c code?

#include#define call(x) #xint main(){printf(“%s”,call(c/c++));return 0;} (a)c(b)c++(c)#c/c++(d)c/c++Answer: (d)Exp:the macro call() will return the string as it is

(11) What will be output if you will compile and execute the following c code?#includeint main(){if(printf(“cquestionbank”))printf(“I know c”);elseprintf(“I know c++”);return 0;} (a) I know c(b) I know c++(c) cquestionbankI know c(d) cquestionbankI know c++Answer: (c)Exp: printf() always returns true if it prints somethink

(12) What will be output if you will compile and execute the following c code?int main(){int i=10;static int x=i;if(x==i)printf(“Equal”);else if(x>i)printf(“Greater than”);elseprintf(“Less than”);return 0;} (a) Equal(b) Greater than(c) Less than(d) Compiler errorAnswer: (d)Exp: we cant allocate value for a static variable dynamically

(13) What will be output if you will compile and execute the following c code?#includeint main(){printf(“%s”,__DATE__);return 0;} (a) Current system date(b) Current system date with time(c) null(d) Compiler errorAnswer: (a)

(14) What will be output if you will compile and execute the following c code?#include#define var 3int main(){char *cricket[var+~0]={“clarke”,”kallis”};char *ptr=cricket;printf(“%c”,*++ptr);return 0;}Choose all that apply: (A) a(B) r(C) l(D) Compilation errorAnswer: (C)Exp: in the above code cricket[0] will be “clarke” and cricket[1] will be “kallis”so *ptr=cricketthis will Asian cricket[0] value to *ptrand *++ptr denotes the second character in the string that is ‘l’

(15) What will be output if you will compile and execute the following c code?#includeint main(){int i=5,j;j=++i+++i+++i;printf(“%d %d”,i,j);return 0;}(A) 7 21(B) 8 21(C) 7 24(D) 8 24Answer: (D)Exp: where j=++i + ++i + ++i;++ operator have high priority than + so all ++ operator will perform first after that it will likej=8+8+8;so j=24

(16)What will be output of the following c program?#includeint main(){int class=150;int public=25;int private=30;class = class >> private – public;printf(“%d”,class);return 0;} (A) 1(B) 2(C) 4(D) Compilation errorAnswer: (C)Exp:Keyword of c++ can be used in c

(17) What will be output if you will compile and execute the following c code?#includeint main(){int i=2,j=2;while(i+1?–i:j++)printf(“%d”,i);return 0;} (A)1(B)2(C)3(D)4Answer: (A) Exp:where i+1 will return 3 but still i is 2rule: any number other that 0 will be considered as TRUE so the return of 2 will be considered as true and the left expression to ‘:’ will execute to bring it as i=1

(18) What will be output if you will compile and execute the following c code?#includeint main(){int i,j;i=j=2;while(–i&&j++)printf(“%d %d”,i,j);return 0;}(A) 2 3(B) 0 3(C) 1 3(D)Infinite loopAnswer: (c)Exp: in while loopfirst time (1 && 2)so it accepts the first time and print 1 3second timein the while loop(0 && 3)0 will be considered as falseso it will stops

(19)The size of generic pointer in c is 2? a)true b)falseAnswer: a

(20)Int aaaaaaaaa; is a legal variable namea)true b)falseans:a

21.    void main(){            int  const * p=5;            printf("%d",++(*p));}

Answer:Compiler error: Cannot modify a constant value. Explanation:    p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".

21.    main(){            char s[ ]="man";            int i;            for(i=0;s[ i ];i++)            printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);}

Answer:                        mmmm                       aaaa                       nnnnExplanation:s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally  array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the  case of  C  it is same as s[i].

23.      main(){            float me = 1.1;            double you = 1.1;            if(me==you)printf("I love U");else                        printf("I hate U");}

Answer: I hate U

Explanation:For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value  represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double.Rule of Thumb: Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) . 

24.      main()            {            static int var = 5;            printf("%d ",var--);            if(var)                        main();            }

Answer:5 4 3 2 1

Explanation:When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively. 

25.      main(){             int c[ ]={2.8,3.4,4,6.7,5};             int j,*p=c,*q=c;             for(j=0;j<5;j++) {                        printf(" %d ",*c);                        ++q;     }             for(j=0;j<5;j++){printf(" %d ",*p);++p;     }} Answer:                        2 2 2 2 2 2 3 4 6 5

Explanation: Initially pointer c is assigned to both p and q. In the first loop, since only q is incremented and not c , the value 2 will be printed 5 times. In second loop p itself is incremented. So the values 2 3 4 6 5 will be printed.

26.      main(){            extern int i;            i=20;printf("%d",i);} Answer:  Linker Error : Undefined symbol '_i'Explanation:                         extern storage class in the following declaration,                                    extern int i;specifies to the compiler that the memory for i is allocated in some other program and that address will be given to the current program at the time of linking. But linker finds that no other variable of name i is available in any other program with memory space allocated for it. Hence a linker error has occurred .

27.      main(){            int i=-1,j=-1,k=0,l=2,m;            m=i++&&j++&&k++||l++;            printf("%d %d %d %d %d",i,j,k,l,m);}

Answer:                        0 0 1 3 1

Explanation :Logical operations always give a result of 1 or 0 . And also the logical AND (&&) operator has higher priority over the logical OR (||) operator. So the expression  ‘i++ && j++ && k++’ is executed first. The result of this expression is 0    (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for ‘0 || 0’ combination- for which it gives 0). So the value of m is 1. The values of other variables are also incremented by 1.

28.      main(){            char *p;            printf("%d %d ",sizeof(*p),sizeof(p));} Answer:                         1 2

Explanation:The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2.

29.      main(){            int i=3;            switch(i)             {                default:printf("zero");                case 1: printf("one");                           break;               case 2:printf("two");                          break;              case 3: printf("three");                          break;              }  }

Answer :three

Explanation :The default case can be placed anywhere inside the loop. It is executed only when all other cases doesn't match.

30.      main(){              printf("%x",-1<<4);}

Answer: fff0

Explanation :-1 is internally represented as all 1's. When left shifted four times the least significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be printed as a hexadecimal value.

31.      main(){            char string[]="Hello World";            display(string);}void display(char *string){            printf("%s",string);}

Answer:Compiler Error : Type mismatch in redeclaration of function display 

Explanation :In third line, when the function display is encountered, the compiler doesn't know anything about the function display. It assumes the arguments and return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs.

32.      main(){            int c=- -2;            printf("c=%d",c);}

Answer:                                    c=2;

Explanation:Here unary minus (or negation) operator is used twice. Same maths  rules applies, ie. minus * minus= plus.Note: However you cannot give like --2. Because -- operator can  only be applied to variables as a decrement operator (eg., i--). 2 is a constant and not a variable.

33.      #define int charmain(){            int i=65;            printf("sizeof(i)=%d",sizeof(i));}

Answer:                        sizeof(i)=1

Explanation:Since the #define replaces the string  int by the macro char

34.      main(){int i=10;i=!i>14;Printf ("i=%d",i);}

Answer:i=0

Explanation:In the expression !i>14 , NOT (!) operator has more precedence than ‘ >’ symbol.  ! is a unary logical operator. !i (!10) is 0 (not of true is false).  0>14 is false (zero).

35.      #includemain(){char s[]={'a','b','c','\n','c','\0'};char *p,*str,*str1;p=&s[3];str=p;str1=s;printf("%d",++*p + ++*str1-32);}

Answer:77        

Explanation:p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. Now performing (11 + 98 – 32), we get 77("M"); So we get the output 77 :: "M" (Ascii is 77).3

36.      #includemain(){int a[2][2][2] = { {10,2,3,4}, {5,6,7,8}  };int *p,*q;p=&a[2][2][2];*q=***a;printf("%d----%d",*p,*q);}

Answer:SomeGarbageValue---1

Explanation:p=&a[2][2][2]  you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.

37.      #includemain(){struct xx{      int x=3;      char name[]="hello"; };struct xx *s;printf("%d",s->x);printf("%s",s->name);}

Answer:Compiler Error

Explanation:You should not initialize variables in declaration

38.      #includemain(){struct xx{int x;struct yy{char s;            struct xx *p;};struct yy *q;};}

Answer:Compiler Error

Explanation:The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.

39.      main(){printf("\nab");printf("\bsi");printf("\rha");}

Answer:hai

Explanation:\n  - newline\b  - backspace\r  - linefeed

40.      main(){int i=5;printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);}

Answer:45545

Explanation:The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the  evaluation is from right to left, hence the result.

41.      #define square(x) x*xmain(){int i;i = 64/square(4);printf("%d",i);}

Answer:64

Explanation:the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64

42.      main(){char *p="hai friends",*p1;p1=p;while(*p!='\0') ++*p++;printf("%s   %s",p,p1);}

Answer:ibj!gsjfoet

Explanation:                        ++*p++ will be parse in the given orderØ  *p that is value at the location currently pointed by p will be takenØ  ++*p the retrieved value will be incremented Ø  when ; is encountered the location will be incremented that is p++ will be executedHence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by executing ++*p and pointer moves to point, ‘a’ which is similarly changed to ‘b’ and so on. Similarly blank space is converted to ‘!’. Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches ‘\0’ and p1 points to p thus p1doesnot print anything.

43.      #include #define a 10main(){#define a 50printf("%d",a);}

Answer:50

Explanation:The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.

44.      #define clrscr() 100main(){clrscr();printf("%d\n",clrscr());}

Answer:100

Explanation:Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input  program to compiler looks like this :                        main()                        {                             100;                             printf("%d\n",100);                        }            Note:   100; is an executable statement but with no action. So it doesn't give any problem

45.   main(){printf("%p",main);}

Answer:                        Some address will be printed.

Explanation:            Function names are just addresses (just like array names are addresses).main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers.

46.       main(){clrscr();}clrscr();            Answer:No output/error

Explanation:The first clrscr() occurs inside a function. So it becomes a function call. In the second clrscr(); is a function declaration (because it is not inside any function).

47.       enum colors {BLACK,BLUE,GREEN} main(){   printf("%d..%d..%d",BLACK,BLUE,GREEN);    return(1);}

Answer:0..1..2

Explanation:enum assigns numbers starting from 0, if not explicitly defined.

48.       void main(){ char far *farther,*farthest;   printf("%d..%d",sizeof(farther),sizeof(farthest));    }

Answer:4..2  

Explanation:            the second pointer is of char type and not a far pointer

49.       main(){ int i=400,j=300; printf("%d..%d");}

Answer:400..300

Explanation:printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values. If more number of assignments given in the program, then printf will take garbage values.

50.       main(){ char *p; p="Hello"; printf("%c\n",*&*p);}

Answer:H 

Explanation:* is a dereference operator & is a reference  operator. They can be    applied any number of times provided it is meaningful. Here  p points to  the first character in the string "Hello". *p dereferences it and so its value is H. Again  & references it to an address and * dereferences it to the value H.

51.       main(){    int i=1;    while (i<=5)    {       printf("%d",i);       if (i>2)              goto here;       i++;    }}fun(){   here:     printf("PP");}

Answer:Compiler error: Undefined label 'here' in function main

Explanation:Labels have functions scope, in other words The scope of the labels is limited to functions . The label 'here' is available in function fun() Hence it is not visible in function main.

52.       main(){   static char names[5][20]={"pascal","ada","cobol","fortran","perl"};    int i;    char *t;    t=names[3];    names[3]=names[4];    names[4]=t;     for (i=0;i<=4;i++)            printf("%s",names[i]);}

Answer:Compiler error: Lvalue required in function main

Explanation:Array names are pointer constants. So it cannot be modified.

53.     void main(){            int i=5;            printf("%d",i++ + ++i);}

Answer:Output Cannot be predicted  exactly.

Explanation:Side effects are involved in the evaluation of   i

54.       void main(){            int i=5;            printf("%d",i+++++i);}

Answer:Compiler Error 

Explanation:The expression i+++++i is parsed as i ++ ++ + i which is an illegal combination of operators.

55.       #includemain(){int i=1,j=2;switch(i) { case 1:  printf("GOOD");                break; case j:  printf("BAD");               break; }}

Answer:Compiler Error: Constant expression required in function main.

Explanation:The case statement can have only constant expressions (this implies that we cannot use variable names directly so an error).            Note:Enumerated types can be used in case statements.

56.    main(){int i;printf("%d",scanf("%d",&i));  // value 10 is given as input here}

Answer:1

Explanation:Scanf returns number of items successfully read and not 1/0.  Here 10 is given as input which should have been scanned successfully. So number of items read is 1.

57.       #define f(g,g2) g##g2main(){int var12=100;printf("%d",f(var,12));            }

Answer:100

58.      main(){int i=0; for(;i++;printf("%d",i)) ;printf("%d",i);}

Answer:            1

Explanation:before entering into the for loop the checking condition is "evaluated". Here it evaluates to 0 (false) and comes out of the loop, and i is incremented (note the semicolon after the for loop).

59.       #includemain(){  char s[]={'a','b','c','\n','c','\0'};  char *p,*str,*str1;  p=&s[3];  str=p;  str1=s;  printf("%d",++*p + ++*str1-32);}

Answer:M

Explanation:p is pointing to character '\n'.str1 is pointing to character 'a' ++*p meAnswer:"p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10. then it is incremented to 11. the value of ++*p is 11. ++*str1 meAnswer:"str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. both 11 and 98 is added and result is subtracted from 32. i.e. (11+98-32)=77("M");

60.       #includemain(){  struct xx   {      int x=3;      char name[]="hello";   };struct xx *s=malloc(sizeof(struct xx));printf("%d",s->x);printf("%s",s->name);}

Answer:Compiler Error

Explanation:Initialization should not be done for structure members inside the structure declaration

61.       #includemain(){struct xx {              int x;              struct yy               {                 char s;                 struct xx *p;               };                         struct yy *q;            };            }

Answer:Compiler Error

Explanation:in the end of nested structure yy a member have to be declared

62.       main(){ extern int i; i=20; printf("%d",sizeof(i));}

Answer:Linker error: undefined symbol '_i'.

Explanation:extern declaration specifies that the variable i is defined somewhere else. The compiler passes the external variable to be resolved by the linker. So compiler doesn't find an error. During linking the linker searches for the definition of i. Since it is not found the linker flags an error.

63.       main(){printf("%d", out);}

int out=100;Answer:Compiler error: undefined symbol out in function main.

Explanation:The rule is that a variable is available for use from the point of declaration. Even though a is a global variable, it is not available for main. Hence an error.

Chapter 2: Object Oriented Programming Using C++

1. You can use C++ as a procedural, as well as an object-oriented, language

A.

True

B.

False

Answer: Option A

 

2. 

A default catch block catches

A.

all thrown objects

B.

no thrown objects

C.

any thrown object that has not been caught by an earlier catch block

D.

all thrown objects that have been caught by an earlier catch block

Answer: Option C

 

3. 

Adding a derived class to a base class requires fundamental changes to the base class

A.

True

B.

False

Answer: Option B

4. 

Format flags may be combined using

A.

the bitwise OR operator (|)

B.

the logical OR operator (||)

C.

the bitwise AND operator (&)

D.

the logical AND operator (&&)

Answer: Option A

 

5. 

The use of the break statement in a switch statement is

A.

optional

B.

compulsory

C.

not allowed. It gives an error message

D.

to check an error

E.

None of the above

Answer: Option A

6. 

When you omit parameters from a function call, values can be provided by

A.

formal parameters

B.

reference parameters

C.

overloaded parameters

D.

default parameters

Answer: Option D

 

7. 

The first element in a string is

A.

the name of the string

B.

the first character in the string

C.

the length of the string

D.

the name of the array holding the string

Answer: Option B

 

8. 

Variables declared outside a block are called _____

A.

Global

B.

universal

C.

Stellar

D.

external

Answer: Option A

 

9.

The compiler converts your C++ instructions into _____

A.

edited code

B.

object code

C.

source code

D.

translated code

Answer: Option B

 

10. 

A fundamental type such as int or double is a _____

A.

programmer-defined type

B.

complex type

C.

nonscalar type

D.

scalar type

Answer: Option D

11. 

The last statement in a function is often a(n) _____

A.

Return

B.

goodbye

C.

Finish

D.

endfunction

Answer: Option A

 

12. 

When the function int someFunction(char c) throw( ) is executed, _____

A.

it can throw anything

B.

it may throw an integer

C.

it may throw a character

D.

it may not throw anything

Answer: Option D

 

13. 

The two statements that can be used to change the flow of control are

A.

if and switch

B.

if and while

C.

switch and do-while

D.

break and continue

E.

None of the above

Answer: Option A

 

14. 

If p and q are assigned the values 2 and 3 respectively then the statement p = q++

A.

gives an error message

B.

assigns a value 4 to p

C.

assigns a value 3 to p

D.

assigns a value 5 to p

E.

None of the above

Answer: Option C

15. 

Which of the following is the insertion operator?

A.

>>

B.

<<

C.

//

D.

/*

E.

both (a) and (b)

Answer: Option B

16. 

You typically initialize a String variable to _____

A.

an asterisk

B.

a space enclosed in single quotes

C.

the number 0

D.

a zero-length string

Answer: Option D

17. 

The set of instructions for how to tie a bow is an example of the _____ structure

A.

Control

B.

repetition

C.

Selection

D.

Sequence

E.

switching

Answer: Option D

18. 

If no exception is thrown ________

A.

a catch block will cause an error

B.

the first catch block coded will execute

C.

the last catch block coded with execute

D.

any catch blocks coded with be bypassed

Answer: Option D

19. 

A program that predicts the exact sequence in which events will take place is said to be ________

A.

Compiled

B.

interpreted

C.

procedural

D.

object-oriented

Answer: Option C

 

20. 

A blueprint for creating an object in C++ is called _____

A.

a class

B.

an instance

C.

a map

D.

a pattern

E.

a sketch

Answer: Option A

Chapter 3: Programming with JAVA

1. 

Which four options describe the correct default values for array elements of the types indicated?

1. int -> 0

2. String -> "null"

3. Dog -> null

4. char -> '\u0000'

5. float -> 0.0f

6. boolean -> true

A.

1, 2, 3, 4

B.

1, 3, 4, 5

C.

2, 4, 5, 6

D.

3, 4, 5, 6

Answer: Option B

(1), (3), (4), (5) are the correct statements.

(2) is wrong because the default value for a String (and any other object reference) is null, with no quotes.

(6) is wrong because the default value for boolean elements is false.

2. 

Which one of these lists contains only Java programming language keywords?

A.

class, if, void, long, Int, continue

B.

goto, instanceof, native, finally, default, throws

C.

try, virtual, throw, final, volatile, transient

D.

strictfp, constant, super, implements, do

E.

byte, break, assert, switch, include

Answer: Option B

All the words in option B are among the 49 Java keywords. Although goto reserved as a keyword in Java,goto is not used and has no function.

Option A is wrong because the keyword for the primitive int starts with a lowercase i.

Option C is wrong because "virtual" is a keyword in C++, but not Java.

Option D is wrong because "constant" is not a keyword. Constants in Java are marked static and final.

Option E is wrong because "include" is a keyword in C, but not in Java.

3. 

Which will legally declare, construct, and initialize an array?

A.

int [] myList = {"1", "2", "3"};

B.

int [] myList = (5, 8, 2);

C.

int myList [] [] = {4,9,7,0};

D.

int myList [] = {4, 3, 7};

Answer: Option D

The only legal array declaration and assignment statement is Option D

Option A is wrong because it initializes an int array with String literals.

Option B is wrong because it use something other than curly braces for the initialization.

Option C is wrong because it provides initial values for only one dimension, although the declared array is a two-dimensional array.

4. 

Which is a reserved word in the Java programming language?

A.

method

B.

native

C.

subclasses

D.

reference

E.

array

Answer: Option B

The word "native" is a valid keyword, used to modify a method declaration.

Option A, D and E are not keywords. Option C is wrong because the keyword for subclassing in Java is extends, not 'subclasses'.

5. 

Which is a valid keyword in java?

A.

interface

B.

string

C.

Float

D.

unsigned

Answer: Option A

interface is a valid keyword.

Option B is wrong because although "String" is a class type in Java, "string" is not a keyword.

Option C is wrong because "Float" is a class type. The keyword for the Java primitive is float.

Option D is wrong because "unsigned" is a keyword in C/C++ but not in Java.

6. 

What will be the output of the program?

class PassA

{

public static void main(String [] args)

{

PassA p = new PassA();

p.start();

}

void start()

{

long [] a1 = {3,4,5};

long [] a2 = fix(a1);

System.out.print(a1[0] + a1[1] + a1[2] + " ");

System.out.println(a2[0] + a2[1] + a2[2]);

}

long [] fix(long [] a3)

{

a3[1] = 7;

return a3;

}

}

A.

12 15

B.

15 15

C.

3 4 5 3 7 5

D.

3 7 5 3 7 5

Answer: Option B

Output: 15 15

The reference variables a1 and a3 refer to the same long array object. When the [1] element is updated in the fix() method, it is updating the array referred to by a1. The reference variable a2 refers to the same array object.

So Output: 3+7+5+" "3+7+5

Output: 15 15 Because Numeric values will be added

7. 

What will be the output of the program?

class Test

{

public static void main(String [] args)

{

Test p = new Test();

p.start();

}

void start()

{

boolean b1 = false;

boolean b2 = fix(b1);

System.out.println(b1 + " " + b2);

}

boolean fix(boolean b1)

{

b1 = true;

return b1;

}

}

A.

true true

B.

false true

C.

true false

D.

false false

Answer: Option B

The boolean b1 in the fix() method is a different boolean than the b1 in the start() method. The b1 in thestart() method is not updated by the fix() method.

8. 

What will be the output of the program?

class PassS

{

public static void main(String [] args)

{

PassS p = new PassS();

p.start();

}

void start()

{

String s1 = "slip";

String s2 = fix(s1);

System.out.println(s1 + " " + s2);

}

String fix(String s1)

{

s1 = s1 + "stream";

System.out.print(s1 + " ");

return "stream";

}

}

A.

slip stream

B.

slipstream stream

C.

stream slip stream

D.

slipstream slip stream

Answer: Option D

When the fix() method is first entered, start()'s s1 and fix()'s s1 reference variables both refer to the same String object (with a value of "slip"). Fix()'s s1 is reassigned to a new object that is created when the concatenation occurs (this second String object has a value of "slipstream"). When the program returns tostart(), another String object is created, referred to by s2 and with a value of "stream".

8.

What will be the output of the program?

class BitShift

{

public static void main(String [] args)

{

int x = 0x80000000;

System.out.print(x + " and ");

x = x >>> 31;

System.out.println(x);

}

}

A.

-2147483648 and 1

B.

0x80000000 and 0x00000001

C.

-2147483648 and -1

D.

1 and -2147483648

Answer: Option A

Option A is correct. The >>> operator moves all bits to the right, zero filling the left bits. The bit transformation looks like this:

Before: 1000 0000 0000 0000 0000 0000 0000 0000

After: 0000 0000 0000 0000 0000 0000 0000 0001

Option C is incorrect because the >>> operator zero fills the left bits, which in this case changes the sign of x, as shown.

Option B is incorrect because the output method print() always displays integers in base 10.

Option D is incorrect because this is the reverse order of the two output numbers.

9. 

What will be the output of the program?

class Equals

{

public static void main(String [] args)

{

int x = 100;

double y = 100.1;

boolean b = (x = y); /* Line 7 */

System.out.println(b);

}

}

A.

true

B.

false

C.

Compilation fails

D.

An exception is thrown at runtime

Answer: Option C

The code will not compile because in line 7, the line will work only if we use (x==y) in the line. The == operator compares values to produce a boolean, whereas the = operator assigns a value to variables.

Option A, B, and D are incorrect because the code does not get as far as compiling. If we corrected this code, the output would be false.

1. 

What will be the output of the program?

public class Foo

{

public static void main(String[] args)

{

try

{

return;

}

finally

{

System.out.println( "Finally" );

}

}

}

A.

Finally

B.

Compilation fails.

C.

The code runs with no output.

D.

An exception is thrown at runtime.

Answer: Option A

If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances:

1. An exception arising in the finally block itself.

2. The death of the thread.

3. The use of System.exit()

4. Turning off the power to the CPU.

I suppose the last three could be classified as VM shutdown.

9. 

What will be the output of the program?

try

{

int x = 0;

int y = 5 / x;

}

catch (Exception e)

{

System.out.println("Exception");

}

catch (ArithmeticException ae)

{

System.out.println(" Arithmetic Exception");

}

System.out.println("finished");

A.

finished

B.

Exception

C.

Compilation fails.

D.

Arithmetic Exception

Answer: Option C

Compilation fails because ArithmeticException has already been caught. ArithmeticException is a subclass of java.lang.Exception, by time the ArithmeticException has been specified it has already been caught by the Exception class.

If ArithmeticException appears before Exception, then the file will compile. When catching exceptions the more specific exceptions must be listed before the more general (the subclasses must be caught before the superclasses).

10. 

What will be the output of the program?

public class X

{

public static void main(String [] args)

{

try

{

badMethod();

System.out.print("A");

}

catch (Exception ex)

{

System.out.print("B");

}

finally

{

System.out.print("C");

}

System.out.print("D");

}

public static void badMethod()

{

throw new Error(); /* Line 22 */

}

}

A.

ABCD

B.

Compilation fails.

C.

C is printed before exiting with an error message.

D.

BC is printed before exiting with an error message.

Answer: Option C

Error is thrown but not recognised line(22) because the only catch attempts to catch an Exception andException is not a superclass of Error. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java.lang.Error).

11. 

What will be the output of the program?

public class X

{

public static void main(String [] args)

{

try

{

badMethod();

System.out.print("A");

}

catch (RuntimeException ex) /* Line 10 */

{

System.out.print("B");

}

catch (Exception ex1)

{

System.out.print("C");

}

finally

{

System.out.print("D");

}

System.out.print("E");

}

public static void badMethod()

{

throw new RuntimeException();

}

}

A.

BD

B.

BCD

C.

BDE

D.

BCDE

Answer: Option C

A Run time exception is thrown and caught in the catch statement on line 10. All the code after the finally statement is run because the exception has been caught.

12. 

What will be the output of the program?

public class RTExcept

{

public static void throwit ()

{

System.out.print("throwit ");

throw new RuntimeException();

}

public static void main(String [] args)

{

try

{

System.out.print("hello ");

throwit();

}

catch (Exception re )

{

System.out.print("caught ");

}

finally

{

System.out.print("finally ");

}

System.out.println("after ");

}

}

A.

hello throwit caught

B.

Compilation fails

C.

hello throwit RuntimeException caught after

D.

hello throwit caught finally after

Answer: Option D

The main() method properly catches and handles the RuntimeException in the catch block, finally runs (as it always does), and then the code returns to normal.

A, B and C are incorrect based on the program logic described above. Remember that properly handled exceptions do not cause the program to stop executing.

13. 

Which is true about an anonymous inner class?

A.

It can extend exactly one class and implement exactly one interface.

B.

It can extend exactly one class and can implement multiple interfaces.

C.

It can extend exactly one class or implement exactly one interface.

D.

It can implement multiple interfaces regardless of whether it also extends a class.

Answer: Option C

Option C is correct because the syntax of an anonymous inner class allows for only one named type after the new, and that type must be either a single interface (in which case the anonymous class implements that one interface) or a single class (in which case the anonymous class extends that one class).

Option A, B, D, and E are all incorrect because they don't follow the syntax rules described in the response for answer Option C.

14. 

class Boo

{

Boo(String s) { }

Boo() { }

}

class Bar extends Boo

{

Bar() { }

Bar(String s) {super(s);}

void zoo()

{

// insert code here

}

}

which one create an anonymous inner class from within class Bar?

A.

Boo f = new Boo(24) { };

B.

Boo f = new Bar() { };

C.

Bar f = new Boo(String s) { };

D.

Boo f = new Boo.Bar(String s) { };

Answer: Option B

Option B is correct because anonymous inner classes are no different from any other class when it comes to polymorphism. That means you are always allowed to declare a reference variable of the superclass type and have that reference variable refer to an instance of a subclass type, which in this case is an anonymous subclass of Bar. Since Bar is a subclass of Boo, it all works.

Option A is incorrect because it passes an int to the Boo constructor, and there is no matching constructor in the Boo class.

Option C is incorrect because it violates the rules of polymorphism—you cannot refer to a superclass type using a reference variable declared as the subclass type. The superclass is not guaranteed to have everything the subclass has.

Option D uses incorrect syntax.

15. 

Which is true about a method-local inner class?

A.

It must be marked final.

B.

It can be marked abstract.

C.

It can be marked public.

D.

It can be marked static.

Answer: Option B

Option B is correct because a method-local inner class can be abstract, although it means a subclass of the inner class must be created if the abstract class is to be used (so an abstract method-local inner class is probably not useful).

Option A is incorrect because a method-local inner class does not have to be declared final (although it is legal to do so).

C and D are incorrect because a method-local inner class cannot be made public (remember-you cannot mark any local variables as public), or static.

16. 

Which statement is true about a static nested class?

A.

You must have a reference to an instance of the enclosing class in order to instantiate it.

B.

It does not have access to nonstatic members of the enclosing class.

C.

It's variables and methods must be static.

D.

It must extend the enclosing class.

Answer: Option B

Option B is correct because a static nested class is not tied to an instance of the enclosing class, and thus can't access the nonstatic members of the class (just as a static method can't access nonstatic members of a class).

Option A is incorrect because static nested classes do not need (and can't use) a reference to an instance of the enclosing class.

Option C is incorrect because static nested classes can declare and define nonstatic members.

Option D is wrong because it just is. There's no rule that says an inner or nested class has to extend anything.

17. 

Which constructs an anonymous inner class instance?

A.

Runnable r = new Runnable() { };

B.

Runnable r = new Runnable(public void run() { });

C.

Runnable r = new Runnable { public void run(){}};

D.

System.out.println(new Runnable() {public void run() { }});

Answer: Option D

D is correct. It defines an anonymous inner class instance, which also means it creates an instance of that new anonymous class at the same time. The anonymous class is an implementer of the Runnable interface, so it must override the run() method of Runnable.

A is incorrect because it doesn't override the run() method, so it violates the rules of interface implementation.

B and C use incorrect syntax.

18. 

What is the value of "d" after this line of code has been executed?

double d = Math.round ( 2.5 + Math.random() );

A.

2

B.

3

C.

4

D.

2.5

Answer: Option B

The Math.random() method returns a number greater than or equal to 0 and less than 1 . Since we can then be sure that the sum of that number and 2.5 will be greater than or equal to 2.5 and less than 3.5, we can be sure that Math.round() will round that number to 3. So Option B is the answer.

19. 

Which of the following would compile without error?

A.

int a = Math.abs(-5);

B.

int b = Math.abs(5.0);

C.

int c = Math.abs(5.5F);

D.

int d = Math.abs(5L);

Answer: Option A

The return value of the Math.abs() method is always the same as the type of the parameter passed into that method.

In the case of A, an integer is passed in and so the result is also an integer which is fine for assignment to "int a".

The values used in B, C & D respectively are a double, a float and a long. The compiler will complain about a possible loss of precision if we try to assign the results to an "int".

20. 

Which of the following are valid calls to Math.max?

1. Math.max(1,4)

2. Math.max(2.3, 5)

3. Math.max(1, 3, 5, 7)

4. Math.max(-1.5, -2.8f)

A.

1, 2 and 4

B.

2, 3 and 4

C.

1, 2 and 3

D.

3 and 4

Answer: Option A

(1), (2), and (4) are correct. The max() method is overloaded to take two arguments of type int, long, float, or double.

(3) is incorrect because the max() method only takes two arguments.

21. 

public class Myfile

{

public static void main (String[] args)

{

String biz = args[1];

String baz = args[2];

String rip = args[3];

System.out.println("Arg is " + rip);

}

}

Select how you would start the program to cause it to print: Arg is 2

A.

java Myfile 222

B.

java Myfile 1 2 2 3 4

C.

java Myfile 1 3 2 2

D.

java Myfile 0 1 2 3

Answer: Option C

Arguments start at array element 0 so the fourth arguement must be 2 to produce the correct output.

22. 

You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access that accomplishes this objective?

A.

public

B.

private

C.

protected

D.

transient

Answer: Option C

Access modifiers dictate which classes, not which instances, may access features.

Methods and variables are collectively known as members. Method and variable members are given access control in exactly the same way.

private makes a member accessible only from within its own class

protected makes a member accessible only to classes in the same package or subclass of the class

default access is very similar to protected (make sure you spot the difference) default access makes a member accessible only to classes in the same package.

public means that all other classes regardless of the package that they belong to, can access the member (assuming the class itself is visible)

final makes it impossible to extend a class, when applied to a method it prevents a method from being overridden in a subclass, when applied to a variable it makes it impossible to reinitialise a variable once it has been initialised

abstract declares a method that has not been implemented.

transient indicates that a variable is not part of the persistent state of an object.

volatile indicates that a thread must reconcile its working copy of the field with the master copy every time it accesses the variable.

After examining the above it should be obvious that the access modifier that provides the most restrictions for methods to be accessed from the subclasses of the class from another package is C - protected. A is also a contender but C is more restrictive, B would be the answer if the constraint was the "same package" instead of "any package" in other words the subclasses clause in the question eliminates default.

23. 

public class Outer

{

public void someOuterMethod()

{

//Line 5

}

public class Inner { }

public static void main(String[] argv)

{

Outer ot = new Outer();

//Line 10

}

}

Which of the following code fragments inserted, will allow to compile?

A.

new Inner(); //At line 5

B.

new Inner(); //At line 10

C.

new ot.Inner(); //At line 10

D.

new Outer.Inner(); //At line 10

Answer: Option A

Option A compiles without problem.

Option B gives error - non-static variable cannot be referenced from a static context.

Option C package ot does not exist.

Option D gives error - non-static variable cannot be referenced from a static context.

24. 

interface Base

{

boolean m1 ();

byte m2(short s);

}

which two code fragments will compile?

1. interface Base2 implements Base {}

2. abstract class Class2 extends Base { public boolean m1(){ return true; }}

3. abstract class Class2 implements Base {}

4. abstract class Class2 implements Base { public boolean m1(){ return (7 > 4); }}

5. abstract class Class2 implements Base { protected boolean m1(){ return (5 > 7) }}

A.

1 and 2

B.

2 and 3

C.

3 and 4

D.

1 and 5

Answer: Option C

(3) is correct because an abstract class doesn't have to implement any or all of its interface's methods. (4) is correct because the method is correctly implemented ((7 > 4) is a boolean).

(1) is incorrect because interfaces don't implement anything. (2) is incorrect because classes don't extend interfaces. (5) is incorrect because interface methods are implicitly public, so the methods being implemented must be public.

25. 

Which three form part of correct array declarations?

1. public int a [ ]

2. static int [ ] a

3. public [ ] int a

4. private int a [3]

5. private int [3] a [ ]

6. public final int [ ] a

A.

1, 3, 4

B.

2, 4, 5

C.

1, 2, 6

D.

2, 5, 6

Answer: Option C

(1), (2) and (6) are valid array declarations.

Option (3) is not a correct array declaration. The compiler complains with: illegal start of type. The brackets are in the wrong place. The following would work: public int[ ] a

Option (4) is not a correct array declaration. The compiler complains with: ']' expected. A closing bracket is expected in place of the 3. The following works: private int a []

Option (5) is not a correct array declaration. The compiler complains with 2 errors:

']' expected. A closing bracket is expected in place of the 3 and

expected A variable name is expected after a[ ] .

26. 

public class Test { }

What is the prototype of the default constructor?

A.

Test( )

B.

Test(void)

C.

public Test( )

D.

public Test(void)

Answer: Option C

Option A and B are wrong because they use the default access modifier and the access modifier for the class is public (remember, the default constructor has the same access modifier as the class).

Option D is wrong. The void makes the compiler think that this is a method specification - in fact if it were a method specification the compiler would spit it out.

27. 

public void foo( boolean a, boolean b)

{

if( a )

{

System.out.println("A"); /* Line 5 */

}

else if(a && b) /* Line 7 */

{

System.out.println( "A && B");

}

else /* Line 11 */

{

if ( !b )

{

System.out.println( "notB") ;

}

else

{

System.out.println( "ELSE" ) ;

}

}

}

A.

If a is true and b is true then the output is "A && B"

B.

If a is true and b is false then the output is "notB"

C.

If a is false and b is true then the output is "ELSE"

D.

If a is false and b is false then the output is "ELSE"

Answer: Option C

Option C is correct. The output is "ELSE". Only when a is false do the output lines after 11 get some chance of executing.

Option A is wrong. The output is "A". When a is true, irrespective of the value of b, only the line 5 output will be executed. The condition at line 7 will never be evaluated (when a is true it will always be trapped by the line 12 condition) therefore the output will never be "A && B".

Option B is wrong. The output is "A". When a is true, irrespective of the value of b, only the line 5 output will be executed.

Option D is wrong. The output is "notB".

28 

switch(x)

{

default:

System.out.println("Hello");

}

Which two are acceptable types for x?

1. byte

2. long

3. char

4. float

5. Short

6. Long

A.

1 and 3

B.

2 and 4

C.

3 and 5

D.

4 and 6

Answer: Option A

Switch statements are based on integer expressions and since both bytes and chars can implicitly be widened to an integer, these can also be used. Also shorts can be used. Short and Long are wrapper classes and reference types can not be used as variables.

29. 

public void test(int x)

{

int odd = 1;

if(odd) /* Line 4 */

{

System.out.println("odd");

}

else

{

System.out.println("even");

}

}

Which statement is true?

A.

Compilation fails.

B.

"odd" will always be output.

C.

"even" will always be output.

D.

"odd" will be output for odd values of x, and "even" for even values.

Answer: Option A

The compiler will complain because of incompatible types (line 4), the if expects a boolean but it gets an integer.

30. 

public class While

{

public void loop()

{

int x= 0;

while ( 1 ) /* Line 6 */

{

System.out.print("x plus one is " + (x + 1)); /* Line 8 */

}

}

}

Which statement is true?

A.

There is a syntax error on line 1.

B.

There are syntax errors on lines 1 and 6.

C.

There are syntax errors on lines 1, 6, and 8.

D.

There is a syntax error on line 6.

Answer: Option D

Using the integer 1 in the while statement, or any other looping or conditional construct for that matter, will result in a compiler error. This is old C Program syntax, not valid Java.

A, B and C are incorrect because line 1 is valid (Java is case sensitive so While is a valid class name). Line 8 is also valid because an equation may be placed in a String operation as shown.

31. 

Suppose that you would like to create an instance of a new Map that has an iteration order that is the same as the iteration order of an existing instance of a Map. Which concrete implementation of the Map interface should be used for the new instance?

A.

TreeMap

B.

HashMap

C.

LinkedHashMap

D.

The answer depends on the implementation of the existing instance.

Answer: Option C

The iteration order of a Collection is the order in which an iterator moves through the elements of theCollection. The iteration order of a LinkedHashMap is determined by the order in which elements are inserted.

When a new LinkedHashMap is created by passing a reference to an existing Collection to the constructor of aLinkedHashMap the Collection.addAll method will ultimately be invoked.

The addAll method uses an iterator to the existing Collection to iterate through the elements of the existing Collection and add each to the instance of the new LinkedHashMap.

Since the iteration order of the LinkedHashMap is determined by the order of insertion, the iteration order of the new LinkedHashMap must be the same as the interation order of the old Collection.

32. 

Which class does not override the equals() and hashCode() methods, inheriting them directly from class Object?

A.

java.lang.String

B.

java.lang.Double

C.

java.lang.StringBuffer

D.

java.lang.Character

Answer: Option C

java.lang.StringBuffer is the only class in the list that uses the default methods provided by classObject.

33. 

Which collection class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized?

A.

java.util.HashSet

B.

java.util.LinkedHashSet

C.

java.util.List

D.

java.util.ArrayList

Answer: Option D

All of the collection classes allow you to grow or shrink the size of your collection. ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayList functionality and has synchronized methods; it is slower than ArrayList.

34. 

You need to store elements in a collection that guarantees that no duplicates are stored and all elements can be accessed in natural order. Which interface provides that capability?

A.

java.util.Map

B.

java.util.Set

C.

java.util.List

D.

java.util.Collection

Answer: Option B

Option B is correct. A set is a collection that contains no duplicate elements. The iterator returns the elements in no particular order (unless this set is an instance of some class that provides a guarantee). A map cannot contain duplicate keys but it may contain duplicate values. List and Collection allow duplicate elements.

Option A is wrong. A map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order (ascending key order); others, like the HashMap class, do not (does not guarantee that the order will remain constant over time).

Option C is wrong. A list is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements.

Option D is wrong. A collection is also known as a sequence. The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements.

35. 

Which interface does java.util.Hashtable implement?

A.

Java.util.Map

B.

Java.util.List

C.

Java.util.HashTable

D.

Java.util.Collection

Answer: Option A

Hash table based implementation of the Map interface.

36. 

What is the name of the method used to start a thread execution?

A.

init();

B.

start();

C.

run();

D.

resume();

Answer: Option B

Option B is Correct. The start() method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Option A is wrong. There is no init() method in the Thread class.

Option C is wrong. The run() method of a thread is like the main() method to an application. Starting the thread causes the object's run method to be called in that separately executing thread.

Option D is wrong. The resume() method is deprecated. It resumes a suspended thread.

37. 

Which two are valid constructors for Thread?

1. Thread(Runnable r, String name)

2. Thread()

3. Thread(int priority)

4. Thread(Runnable r, ThreadGroup g)

5. Thread(Runnable r, int priority)

A.

1 and 3

B.

2 and 4

C.

1 and 2

D.

2 and 5

Answer: Option C

(1) and (2) are both valid constructors for Thread.

(3), (4), and (5) are not legal Thread constructors, although (4) is close. If you reverse the arguments in (4), you'd have a valid constructor.

38. 

Which three are methods of the Object class?

1. notify();

2. notifyAll();

3. isInterrupted();

4. synchronized();

5. interrupt();

6. wait(long msecs);

7. sleep(long msecs);

8. yield();

A.

1, 2, 4

B.

2, 4, 5

C.

1, 2, 6

D.

2, 3, 4

Answer: Option C

(1), (2), and (6) are correct. They are all related to the list of threads waiting on the specified object.

(3), (5), (7), and (8) are incorrect answers. The methods isInterrupted() and interrupt() are instance methods of Thread.

The methods sleep() and yield() are static methods of Thread.

D is incorrect because synchronized is a keyword and the synchronized() construct is part of the Java language.

39 

class X implements Runnable

{

public static void main(String args[])

{

/* Missing code? */

}

public void run() {}

}

Which of the following line of code is suitable to start a thread ?

A.

Thread t = new Thread(X);

B.

Thread t = new Thread(X); t.start();

C.

X run = new X(); Thread t = new Thread(run); t.start();

D.

Thread t = new Thread(); x.run();

Answer: Option C

Option C is suitable to start a thread.

40. 

Which cannot directly cause a thread to stop executing?

A.

Calling the SetPriority() method on a Thread object.

B.

Calling the wait() method on an object.

C.

Calling notify() method on an object.

D.

Calling read() method on an InputStream object.

Answer: Option C

Option C is correct. notify() - wakes up a single thread that is waiting on this object's monitor.

By: Namratha K, Asst. Prof., Sambhram Institute of TechnologyPage 2

Technical Aptitude

Chapter 1: Programming with C

(1) What will be output if you will compile and execute the following c code? struct marks{int p:3;int c:3;};void main(){struct marks s={2,-6};printf(“%d %d”,s.p,s.c);}

(a) 2 -6(b) 2 1(c) 2 2(d) Compiler error

Ans:cExp: Binary value of 2: 00000010 (Select three two bit)Binary value of 6: 00000110Binary value of -6: 11111001+1=11111010(Select last three bit)

(2) What will be output if you will compile and execute the following c code? #includevoid main(){int i;float a=5.2;char *ptr;ptr=(char *)&a;for(i=0;i<=3;i++)printf(“%d “,*ptr++);}

(a)0 0 0 0(b)Garbage Garbage Garbage Garbage(c)102 56 -80 32(d)102 102 -90 64

Ans: bExp: *ptr++ will increment the address every time so we cant guess the value present in that address

(3) What will be output if you will compile and execute the following c code?#includeVoid main(){printf(“%s”,”c” “question” “bank”);} (a) c question bank(b) c(c) bank(d) cquestionbank

Ans :dExp: In c string constant “xy” is same as “x” “y”

(4) What will be output if you will compile and execute the following c code?#includeint main(){char *str=”c-pointer”;printf(“%*.*s”,10,7,str);return 0;}

(a) c-pointer(b) cpointer(c) cpointer null null(d) c-point

Answer: (d) Explanation: Meaning of %*.*s in the printf function:First * indicates the width i.e. how many spaces will take to print the string and second * indicates how many characters will print of any string.

(5) What will be output if you will compile and execute the following c code?#includeint main(){int a=-12;a=a>>3;printf(“%d”,a);return 0;} (a) -4 (b) -2 (c) -3 (d) -96

Answer :(b) Explanation:Binary value of 12 is: 00000000 00001100-12 is 2’s com of 12 =>11111111 11110100While performing 3 left shift value becomes => 111111 111110 => -2

(6) What will be output if you will compile and execute the following c code?#include#includeint main(){printf(“%d %d”,sizeof(“string”),strlen(“string”));return 0;} (a) 7 6(b) 7 7(c) 6 7(d) 6 6

Answer: (a) Explanation: char has memory of 1 byte so sizeof(“string”)=>7 including null char; strlen(“string”)=>6 which is the length.

(7) What will be output if you will compile and execute the following c code?#includeint main(){int a=1,2;int b=(1,2);printf(“%d %d”,a,b);return 0;} (a)1,1(b)1,2(c)2,1(d)2,2Ans:bExp:1,2 will think as array and a[0]which is same as a will be assigned as 1(1,2) comma operator will lead to right most one so it returns 2

(8) What will be output if you will compile and execute the following c code?#includeint main(){int i=0;if(i==0){i=((5,(i=3)),i=1);printf(“%d”,i);}elseprintf(“equal”);} (a) 5(b) 3(c) 1(d) equalAns :c Exp: refer previous exp

(9) What will be output if you will compile and execute the following c code?

#include#define message “union is\power of c”int main(){printf(“%s”,message);return 0;} (a) union is power of c(b) union ispower of c(c) union isPower of c(d) Compiler errorAns:bExp: If you want to write macro constant in new line the end with the character \.

(10) What will be output if you will compile and execute the following c code?

#include#define call(x) #xint main(){printf(“%s”,call(c/c++));return 0;} (a)c(b)c++(c)#c/c++(d)c/c++Answer: (d)Exp:the macro call() will return the string as it is

(11) What will be output if you will compile and execute the following c code?#includeint main(){if(printf(“cquestionbank”))printf(“I know c”);elseprintf(“I know c++”);return 0;} (a) I know c(b) I know c++(c) cquestionbankI know c(d) cquestionbankI know c++Answer: (c)Exp: printf() always returns true if it prints somethink

(12) What will be output if you will compile and execute the following c code?int main(){int i=10;static int x=i;if(x==i)printf(“Equal”);else if(x>i)printf(“Greater than”);elseprintf(“Less than”);return 0;} (a) Equal(b) Greater than(c) Less than(d) Compiler errorAnswer: (d)Exp: we cant allocate value for a static variable dynamically

(13) What will be output if you will compile and execute the following c code?#includeint main(){printf(“%s”,__DATE__);return 0;} (a) Current system date(b) Current system date with time(c) null(d) Compiler errorAnswer: (a)

(14) What will be output if you will compile and execute the following c code?#include#define var 3int main(){char *cricket[var+~0]={“clarke”,”kallis”};char *ptr=cricket;printf(“%c”,*++ptr);return 0;}Choose all that apply: (A) a(B) r(C) l(D) Compilation errorAnswer: (C)Exp: in the above code cricket[0] will be “clarke” and cricket[1] will be “kallis”so *ptr=cricketthis will Asian cricket[0] value to *ptrand *++ptr denotes the second character in the string that is ‘l’

(15) What will be output if you will compile and execute the following c code?#includeint main(){int i=5,j;j=++i+++i+++i;printf(“%d %d”,i,j);return 0;}(A) 7 21(B) 8 21(C) 7 24(D) 8 24Answer: (D)Exp: where j=++i + ++i + ++i;++ operator have high priority than + so all ++ operator will perform first after that it will likej=8+8+8;so j=24

(16)What will be output of the following c program?#includeint main(){int class=150;int public=25;int private=30;class = class >> private – public;printf(“%d”,class);return 0;} (A) 1(B) 2(C) 4(D) Compilation errorAnswer: (C)Exp:Keyword of c++ can be used in c

(17) What will be output if you will compile and execute the following c code?#includeint main(){int i=2,j=2;while(i+1?–i:j++)printf(“%d”,i);return 0;} (A)1(B)2(C)3(D)4Answer: (A) Exp:where i+1 will return 3 but still i is 2rule: any number other that 0 will be considered as TRUE so the return of 2 will be considered as true and the left expression to ‘:’ will execute to bring it as i=1

(18) What will be output if you will compile and execute the following c code?#includeint main(){int i,j;i=j=2;while(–i&&j++)printf(“%d %d”,i,j);return 0;}(A) 2 3(B) 0 3(C) 1 3(D)Infinite loopAnswer: (c)Exp: in while loopfirst time (1 && 2)so it accepts the first time and print 1 3second timein the while loop(0 && 3)0 will be considered as falseso it will stops

(19)The size of generic pointer in c is 2? a)true b)falseAnswer: a

(20)Int aaaaaaaaa; is a legal variable namea)true b)falseans:a

21.    void main(){            int  const * p=5;            printf("%d",++(*p));}

Answer:Compiler error: Cannot modify a constant value. Explanation:    p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".

21.    main(){            char s[ ]="man";            int i;            for(i=0;s[ i ];i++)            printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);}

Answer:                        mmmm                       aaaa                       nnnnExplanation:s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally  array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the  case of  C  it is same as s[i].

23.      main(){            float me = 1.1;            double you = 1.1;            if(me==you)printf("I love U");else                        printf("I hate U");}

Answer: I hate U

Explanation:For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value  represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double.Rule of Thumb: Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) . 

24.      main()            {            static int var = 5;            printf("%d ",var--);            if(var)                        main();            }

Answer:5 4 3 2 1

Explanation:When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively. 

25.      main(){             int c[ ]={2.8,3.4,4,6.7,5};             int j,*p=c,*q=c;             for(j=0;j<5;j++) {                        printf(" %d ",*c);                        ++q;     }             for(j=0;j<5;j++){printf(" %d ",*p);++p;     }} Answer:                        2 2 2 2 2 2 3 4 6 5

Explanation: Initially pointer c is assigned to both p and q. In the first loop, since only q is incremented and not c , the value 2 will be printed 5 times. In second loop p itself is incremented. So the values 2 3 4 6 5 will be printed.

26.      main(){            extern int i;            i=20;printf("%d",i);} Answer:  Linker Error : Undefined symbol '_i'Explanation:                         extern storage class in the following declaration,                                    extern int i;specifies to the compiler that the memory for i is allocated in some other program and that address will be given to the current program at the time of linking. But linker finds that no other variable of name i is available in any other program with memory space allocated for it. Hence a linker error has occurred .

27.      main(){            int i=-1,j=-1,k=0,l=2,m;            m=i++&&j++&&k++||l++;            printf("%d %d %d %d %d",i,j,k,l,m);}

Answer:                        0 0 1 3 1

Explanation :Logical operations always give a result of 1 or 0 . And also the logical AND (&&) operator has higher priority over the logical OR (||) operator. So the expression  ‘i++ && j++ && k++’ is executed first. The result of this expression is 0    (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for ‘0 || 0’ combination- for which it gives 0). So the value of m is 1. The values of other variables are also incremented by 1.

28.      main(){            char *p;            printf("%d %d ",sizeof(*p),sizeof(p));} Answer:                         1 2

Explanation:The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2.

29.      main(){            int i=3;            switch(i)             {                default:printf("zero");                case 1: printf("one");                           break;               case 2:printf("two");                          break;              case 3: printf("three");                          break;              }  }

Answer :three

Explanation :The default case can be placed anywhere inside the loop. It is executed only when all other cases doesn't match.

30.      main(){              printf("%x",-1<<4);}

Answer: fff0

Explanation :-1 is internally represented as all 1's. When left shifted four times the least significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be printed as a hexadecimal value.

31.      main(){            char string[]="Hello World";            display(string);}void display(char *string){            printf("%s",string);}

Answer:Compiler Error : Type mismatch in redeclaration of function display 

Explanation :In third line, when the function display is encountered, the compiler doesn't know anything about the function display. It assumes the arguments and return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs.

32.      main(){            int c=- -2;            printf("c=%d",c);}

Answer:                                    c=2;

Explanation:Here unary minus (or negation) operator is used twice. Same maths  rules applies, ie. minus * minus= plus.Note: However you cannot give like --2. Because -- operator can  only be applied to variables as a decrement operator (eg., i--). 2 is a constant and not a variable.

33.      #define int charmain(){            int i=65;            printf("sizeof(i)=%d",sizeof(i));}

Answer:                        sizeof(i)=1

Explanation:Since the #define replaces the string  int by the macro char

34.      main(){int i=10;i=!i>14;Printf ("i=%d",i);}

Answer:i=0

Explanation:In the expression !i>14 , NOT (!) operator has more precedence than ‘ >’ symbol.  ! is a unary logical operator. !i (!10) is 0 (not of true is false).  0>14 is false (zero).

35.      #includemain(){char s[]={'a','b','c','\n','c','\0'};char *p,*str,*str1;p=&s[3];str=p;str1=s;printf("%d",++*p + ++*str1-32);}

Answer:77        

Explanation:p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. Now performing (11 + 98 – 32), we get 77("M"); So we get the output 77 :: "M" (Ascii is 77).3

36.      #includemain(){int a[2][2][2] = { {10,2,3,4}, {5,6,7,8}  };int *p,*q;p=&a[2][2][2];*q=***a;printf("%d----%d",*p,*q);}

Answer:SomeGarbageValue---1

Explanation:p=&a[2][2][2]  you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.

37.      #includemain(){struct xx{      int x=3;      char name[]="hello"; };struct xx *s;printf("%d",s->x);printf("%s",s->name);}

Answer:Compiler Error

Explanation:You should not initialize variables in declaration

38.      #includemain(){struct xx{int x;struct yy{char s;            struct xx *p;};struct yy *q;};}

Answer:Compiler Error

Explanation:The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.

39.      main(){printf("\nab");printf("\bsi");printf("\rha");}

Answer:hai

Explanation:\n  - newline\b  - backspace\r  - linefeed

40.      main(){int i=5;printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);}

Answer:45545

Explanation:The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the  evaluation is from right to left, hence the result.

41.      #define square(x) x*xmain(){int i;i = 64/square(4);printf("%d",i);}

Answer:64

Explanation:the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64

42.      main(){char *p="hai friends",*p1;p1=p;while(*p!='\0') ++*p++;printf("%s   %s",p,p1);}

Answer:ibj!gsjfoet

Explanation:                        ++*p++ will be parse in the given orderØ  *p that is value at the location currently pointed by p will be takenØ  ++*p the retrieved value will be incremented Ø  when ; is encountered the location will be incremented that is p++ will be executedHence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by executing ++*p and pointer moves to point, ‘a’ which is similarly changed to ‘b’ and so on. Similarly blank space is converted to ‘!’. Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches ‘\0’ and p1 points to p thus p1doesnot print anything.

43.      #include #define a 10main(){#define a 50printf("%d",a);}

Answer:50

Explanation:The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.

44.      #define clrscr() 100main(){clrscr();printf("%d\n",clrscr());}

Answer:100

Explanation:Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input  program to compiler looks like this :                        main()                        {                             100;                             printf("%d\n",100);                        }            Note:   100; is an executable statement but with no action. So it doesn't give any problem

45.   main(){printf("%p",main);}

Answer:                        Some address will be printed.

Explanation:            Function names are just addresses (just like array names are addresses).main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers.

46.       main(){clrscr();}clrscr();            Answer:No output/error

Explanation:The first clrscr() occurs inside a function. So it becomes a function call. In the second clrscr(); is a function declaration (because it is not inside any function).

47.       enum colors {BLACK,BLUE,GREEN} main(){   printf("%d..%d..%d",BLACK,BLUE,GREEN);    return(1);}

Answer:0..1..2

Explanation:enum assigns numbers starting from 0, if not explicitly defined.

48.       void main(){ char far *farther,*farthest;   printf("%d..%d",sizeof(farther),sizeof(farthest));    }

Answer:4..2  

Explanation:            the second pointer is of char type and not a far pointer

49.       main(){ int i=400,j=300; printf("%d..%d");}

Answer:400..300

Explanation:printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values. If more number of assignments given in the program, then printf will take garbage values.

50.       main(){ char *p; p="Hello"; printf("%c\n",*&*p);}

Answer:H 

Explanation:* is a dereference operator & is a reference  operator. They can be    applied any number of times provided it is meaningful. Here  p points to  the first character in the string "Hello". *p dereferences it and so its value is H. Again  & references it to an address and * dereferences it to the value H.

51.       main(){    int i=1;    while (i<=5)    {       printf("%d",i);       if (i>2)              goto here;       i++;    }}fun(){   here:     printf("PP");}

Answer:Compiler error: Undefined label 'here' in function main

Explanation:Labels have functions scope, in other words The scope of the labels is limited to functions . The label 'here' is available in function fun() Hence it is not visible in function main.

52.       main(){   static char names[5][20]={"pascal","ada","cobol","fortran","perl"};    int i;    char *t;    t=names[3];    names[3]=names[4];    names[4]=t;     for (i=0;i<=4;i++)            printf("%s",names[i]);}

Answer:Compiler error: Lvalue required in function main

Explanation:Array names are pointer constants. So it cannot be