Wednesday, July 21, 2010
*
Everything can be sacrificed for truth, but truth cannot be sacrificed for anything.
*
The highest ideal is eternal and entire self-abnegation, where there is no 'I', but is Thou'.
*
By work alone, men may get to where Buddha got largely by meditation or Christ by prayer. Buddha was a working Jnani, Christ was a Bhakta, but the same goal was reached by both of them.
*
All expansion is life, all contraction is death.
*
All love is expansion, all selfishness is contraction. Love is therefore the only law of life. He who loves lives, he who is selfish is dying. Therefore love for love's sake, because it is law of life, just as you breathe to live.
*
The national ideals of India are Renunciation and Service. Intensity her in those channels, and the rest will take care of itself.
*
Good motives, sincerity, and infinite love can conquer the world. One single soul possessed of these virtues can destroy the dark designs of millions of hypocrites and brutes.
*
Take up one idea. Make that one idea your life - think of it, dream of it, live on idea. Let the brain, muscles, nerves, every part of your body, be full of that idea, and just leave every other idea alone. This is the way to success.
*
- Swami Vivekananda
Saturday, July 17, 2010
BEL Interview
* Written By: Admin Admin
* 9-28-2006
* Categorized in: BEL
BEL Interview
On this 21st August, 2004 I am attended the interview for Probationary Engineer at BEL,
Bangalore. Its for CSE stream. Interview lasts for 40 minutes. As I have to face my ever
first Job interview, am with little bit anxiety. Here are the details of the interview I would
like to share with these magnificent group friends.
As I entered in to the room by asking excuse me Sir, They invited me very politely and
offered a chair to seat. There were four members in the panel all were in age group of 50,
of which two members are from Central Research Laboratory of BEL grilled out me with
tech questions. One is HR department person and remained was acts as head of the
panel.
First the head of the panel introduced all the members and explained the procedure of the
interview. First he starts by describing about the company for almost five minutes, which
makes me to relax and comfortable with the panel. After that he asked to tell about
myself briefly for a minute.
While I am in a way of describing myself, he also asked to point out the achievements,
strong points, hobbies and regarding sports. Also asked for favorite subjects, and I told
that C, Database and Networks are my favorites.
Now it’s the time for technical grilling..
The first person from CRL starts by asking
What are the components of LAN?
How do u connects the systems?
What is UTP? (Unshielded Twisted Pair)
How much distance it supports?
Fiber optic supports how much distance?(I don’t know exactly?)
What is the throughput of the Ethernet LAN?
Describe about OSI Layers?
In which layer encryption can be done? And other than presentation layer?
What is the function of Bridge? Router?
Which layer is responsible for end 2 end connection?
What is RAID? (Redundant Array of Inexpensive Disks)
For what it is used for?
How can achieve fault tolerance through RAID?
Where the Static variable stored in C?
And local variables?( I was made a mistake here by telling it is also in heap)
And he shows already written function prototypes asked to describe it.. as
int *(*p)(int a, float b) // pointer 2 the function p returns integer pointer
int (*p)(int *a, float b) //pointer 2 the function p returns integer
int *p(int a, float *b) // function p returns integer pointer
int p(int a, float *b) // function p returns integer
now he looks as impressed and asked
how to return 1000 variables from a function in C?
Now seen changes to second person of CRL
He asked to explain about my project? (It lasts for 4 minutes)
What are the functions of the OS?
Which OS you are familiar with?
What is the process?
What r its attributes?
How the process interacts with each others?
What r the mechanisms for inter process communication?
What is semaphore?
What is critical region?
How can semaphore avoid conflicts?
Again first person starts asking
What is a virtual function?
What is late binding?
What is scope resolution operator?
Differentiate between testing and debugging? (here I take time 2 distinguish )
Distinguish black box testing and white box testing?
What is unit testing?
How can u control the lost acknowledgement issue?
Is there is any difference between switch and hub? Which is good? ( here again I wasn’t
answered properly)
And some more questions I wasn’t reminded correctly..
After that head of the panel gestures to HR to ask questions
What do u prefer to be a team leader or team member?
What r the qualities u have for being a leader?
How can u solve the conflicts in a team?
How can u react if some one else competing with u in ur team for promotion?
Again head asks me
What is ur reaction if some one copying in the exam?
Can u tell me a instance in ur college that insists ur leadership attitude?
Have u ever short tempered?
Have u attended any interviews?
Is u don’t have campus?
And he gestures to HR to explain pay and bond details
He told that first 6 months will be the training period after that for three years u will be
appointed as probationary engineer, and also told that based on our performance
promotion will be carried out early or late.
For this probationary engineer u can draw 2.65 laks per anum with all allowances, and u
have to execute a bond of Rs50000/- for three years effects from date of appointment
after training.
And now head asks for any questions from me. I was asked the same qns
What is the career path?
When can I know the results?
Read more: http://www.ittestpapers.com/articles/placement-paper-and-interview-questions-of-bel.html#ixzz0u0cdv6Pv
* 9-28-2006
* Categorized in: BEL
BEL Interview
On this 21st August, 2004 I am attended the interview for Probationary Engineer at BEL,
Bangalore. Its for CSE stream. Interview lasts for 40 minutes. As I have to face my ever
first Job interview, am with little bit anxiety. Here are the details of the interview I would
like to share with these magnificent group friends.
As I entered in to the room by asking excuse me Sir, They invited me very politely and
offered a chair to seat. There were four members in the panel all were in age group of 50,
of which two members are from Central Research Laboratory of BEL grilled out me with
tech questions. One is HR department person and remained was acts as head of the
panel.
First the head of the panel introduced all the members and explained the procedure of the
interview. First he starts by describing about the company for almost five minutes, which
makes me to relax and comfortable with the panel. After that he asked to tell about
myself briefly for a minute.
While I am in a way of describing myself, he also asked to point out the achievements,
strong points, hobbies and regarding sports. Also asked for favorite subjects, and I told
that C, Database and Networks are my favorites.
Now it’s the time for technical grilling..
The first person from CRL starts by asking
What are the components of LAN?
How do u connects the systems?
What is UTP? (Unshielded Twisted Pair)
How much distance it supports?
Fiber optic supports how much distance?(I don’t know exactly?)
What is the throughput of the Ethernet LAN?
Describe about OSI Layers?
In which layer encryption can be done? And other than presentation layer?
What is the function of Bridge? Router?
Which layer is responsible for end 2 end connection?
What is RAID? (Redundant Array of Inexpensive Disks)
For what it is used for?
How can achieve fault tolerance through RAID?
Where the Static variable stored in C?
And local variables?( I was made a mistake here by telling it is also in heap)
And he shows already written function prototypes asked to describe it.. as
int *(*p)(int a, float b) // pointer 2 the function p returns integer pointer
int (*p)(int *a, float b) //pointer 2 the function p returns integer
int *p(int a, float *b) // function p returns integer pointer
int p(int a, float *b) // function p returns integer
now he looks as impressed and asked
how to return 1000 variables from a function in C?
Now seen changes to second person of CRL
He asked to explain about my project? (It lasts for 4 minutes)
What are the functions of the OS?
Which OS you are familiar with?
What is the process?
What r its attributes?
How the process interacts with each others?
What r the mechanisms for inter process communication?
What is semaphore?
What is critical region?
How can semaphore avoid conflicts?
Again first person starts asking
What is a virtual function?
What is late binding?
What is scope resolution operator?
Differentiate between testing and debugging? (here I take time 2 distinguish )
Distinguish black box testing and white box testing?
What is unit testing?
How can u control the lost acknowledgement issue?
Is there is any difference between switch and hub? Which is good? ( here again I wasn’t
answered properly)
And some more questions I wasn’t reminded correctly..
After that head of the panel gestures to HR to ask questions
What do u prefer to be a team leader or team member?
What r the qualities u have for being a leader?
How can u solve the conflicts in a team?
How can u react if some one else competing with u in ur team for promotion?
Again head asks me
What is ur reaction if some one copying in the exam?
Can u tell me a instance in ur college that insists ur leadership attitude?
Have u ever short tempered?
Have u attended any interviews?
Is u don’t have campus?
And he gestures to HR to explain pay and bond details
He told that first 6 months will be the training period after that for three years u will be
appointed as probationary engineer, and also told that based on our performance
promotion will be carried out early or late.
For this probationary engineer u can draw 2.65 laks per anum with all allowances, and u
have to execute a bond of Rs50000/- for three years effects from date of appointment
after training.
And now head asks for any questions from me. I was asked the same qns
What is the career path?
When can I know the results?
Read more: http://www.ittestpapers.com/articles/placement-paper-and-interview-questions-of-bel.html#ixzz0u0cdv6Pv
C-DAC
C-DAC Placement Papers
CDAC Pattern and Sample Paper
* Article
* By Mahidhar Babu
* July 20, 2006
* 4 comments
1. What is data structure?
Answer: A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data.
2. List out the areas in which data structures are applied extensively?
Compiler Design,
Operating System,
Database Management System,
Statistical analysis package,
Numerical Analysis,
Graphics,
Artificial Intelligence,
Simulation
3. What are the major data structures used in the following areas : RDBMS, Network data model & Hierarchical data model.
RDBMS � Array (i.e. Array of structures)
Network data model � Graph
Hierarchical data model � Trees
4. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.
CDAC Paper 2 - 2006
* Article
* By Mahidhar Babu
* July 20, 2006
* 9 comments
C-Dac Sample quesion paper - pattern 1
1.The programming language that was designed for specifying algorithm
Address
ASCII
ALGOL
None of these options
2. _____ contains the addresses of all the records according to the contents of the field designed as the record key.
Index<------ans
Subscript
Array
File
3. _________ symbol is used for Processing of data.
Oval
Parallelogram<------ans
Rectangle
Diamond
4. __________ is the analysis tool used for planning program logic
Protocol
None of these options
PROLOG
Pseudocode
5. Machine language has two part format the first part is__________ and the second part is __________
OPCODE,OPERAND<------ans
OPERAND,OPCODE
DATA CODE,OPERAND
OPERAND,CODEOP
6. Language Primarily used for internet-based applications
ADA
C++
JAVA<------ans
FORTRAN
7. _________ is a point at which the debugger stops during program execution and awaits a further command.
Memory Dump
Watch point<------ans
Break point
None of these options
8. ________do not contain any program logic and are ignored by the language processor.
Protocol
Virus
Comment
None of these options
9. The component of data base management system is ________
Data definition Language
Data manipulation Language
Data definition Language and Data manipulation Language
None of these options
10. The quality of Algorithm is judged on the basis of_________
Time requirement
Memory Requirement
Accuracy of solution
All of these options<------ans
11. Advantages of using flow charts is
Effective Analysis
Efficient Coding
Time consuming
Effective Analysis and Efficient Coding<-----ans
Programming in C
12. The Real constants in C can be expressed in which of the following forms
Fractional form only
Exponential form only
ASCII form only
Both Fractional and Exponential forms<------ans
13. The program, which translates high-level program into its equivalent machine language program, is called
Transformer
Language processor
Converter
None of these options<------ans
14. Consider the following statements. i.Multiplication associates left to right ii.Division associates left to right
iii.Unary Minus associates right to left
iv.subtraction associates left to right All are true <------ans
only i and ii are true
all are false
only iii and iv are true
15. What will be the value of variable a in the following code?
unsigned char a;
a = 0xFF + 1;
printf("%d", a);
0xFF
0x100
0 <------ans
0x0
16. What is the output of the following program?
#include
void main()
{
printf("\n10!=9 : %5d",10!=9);
}
1<------ans
0
Error
None of these options
17. #include
void main()
{
int x=10;
(x<0)?(int a =100):(int a =1000);
printf(" %d",a);
}
Error<------ans
1000
100
None of these options
18. Which of the following shows the correct hierarchy of arithmetic operations in C
(), **, * or /, + or -
(), **, *, /, +, -
(), **, /, *, +, -
(), / or *, - or + <-----Ans
19. What is the output of the following code?
#include
void main()
{
int a=14;
a += 7;
a -= 5;
a *= 7;
printf("\n%d",a);
}
112<------ans
98
89
None of these options
20. What is the output of the following code? #include
#define T t
void main()
{
char T = `T`;
printf("\n%c\t%c\n",T,t);
}
Error
T t
T T---ans
t t
Read more: http://www.ittestpapers.com/placement-papers/cdac.html#ixzz0u0dqr2UI
CDAC Pattern and Sample Paper
* Article
* By Mahidhar Babu
* July 20, 2006
* 4 comments
1. What is data structure?
Answer: A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data.
2. List out the areas in which data structures are applied extensively?
Compiler Design,
Operating System,
Database Management System,
Statistical analysis package,
Numerical Analysis,
Graphics,
Artificial Intelligence,
Simulation
3. What are the major data structures used in the following areas : RDBMS, Network data model & Hierarchical data model.
RDBMS � Array (i.e. Array of structures)
Network data model � Graph
Hierarchical data model � Trees
4. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.
CDAC Paper 2 - 2006
* Article
* By Mahidhar Babu
* July 20, 2006
* 9 comments
C-Dac Sample quesion paper - pattern 1
1.The programming language that was designed for specifying algorithm
Address
ASCII
ALGOL
None of these options
2. _____ contains the addresses of all the records according to the contents of the field designed as the record key.
Index<------ans
Subscript
Array
File
3. _________ symbol is used for Processing of data.
Oval
Parallelogram<------ans
Rectangle
Diamond
4. __________ is the analysis tool used for planning program logic
Protocol
None of these options
PROLOG
Pseudocode
5. Machine language has two part format the first part is__________ and the second part is __________
OPCODE,OPERAND<------ans
OPERAND,OPCODE
DATA CODE,OPERAND
OPERAND,CODEOP
6. Language Primarily used for internet-based applications
ADA
C++
JAVA<------ans
FORTRAN
7. _________ is a point at which the debugger stops during program execution and awaits a further command.
Memory Dump
Watch point<------ans
Break point
None of these options
8. ________do not contain any program logic and are ignored by the language processor.
Protocol
Virus
Comment
None of these options
9. The component of data base management system is ________
Data definition Language
Data manipulation Language
Data definition Language and Data manipulation Language
None of these options
10. The quality of Algorithm is judged on the basis of_________
Time requirement
Memory Requirement
Accuracy of solution
All of these options<------ans
11. Advantages of using flow charts is
Effective Analysis
Efficient Coding
Time consuming
Effective Analysis and Efficient Coding<-----ans
Programming in C
12. The Real constants in C can be expressed in which of the following forms
Fractional form only
Exponential form only
ASCII form only
Both Fractional and Exponential forms<------ans
13. The program, which translates high-level program into its equivalent machine language program, is called
Transformer
Language processor
Converter
None of these options<------ans
14. Consider the following statements. i.Multiplication associates left to right ii.Division associates left to right
iii.Unary Minus associates right to left
iv.subtraction associates left to right All are true <------ans
only i and ii are true
all are false
only iii and iv are true
15. What will be the value of variable a in the following code?
unsigned char a;
a = 0xFF + 1;
printf("%d", a);
0xFF
0x100
0 <------ans
0x0
16. What is the output of the following program?
#include
void main()
{
printf("\n10!=9 : %5d",10!=9);
}
1<------ans
0
Error
None of these options
17. #include
void main()
{
int x=10;
(x<0)?(int a =100):(int a =1000);
printf(" %d",a);
}
Error<------ans
1000
100
None of these options
18. Which of the following shows the correct hierarchy of arithmetic operations in C
(), **, * or /, + or -
(), **, *, /, +, -
(), **, /, *, +, -
(), / or *, - or + <-----Ans
19. What is the output of the following code?
#include
void main()
{
int a=14;
a += 7;
a -= 5;
a *= 7;
printf("\n%d",a);
}
112<------ans
98
89
None of these options
20. What is the output of the following code? #include
#define T t
void main()
{
char T = `T`;
printf("\n%c\t%c\n",T,t);
}
Error
T t
T T---ans
t t
Read more: http://www.ittestpapers.com/placement-papers/cdac.html#ixzz0u0dqr2UI
Operating Systems
Operating Systems is an interface between hardware and user. OS is responsible for the management and the coordination of activities. It acts as a host for the applications running on the machine and contains the details of the hardware. All types of computers like handheld computers, desktop computers, and even video game consoles use some kind of Operating system. OS offers number of services to programs and users and these services are accessed through application programming interfaces (API) or system calls.
1. When is a system in safe state?
The set of dispatchable processes is in a safe state if there exists at least one temporal order in which all processes can be run to completion without resulting in a deadlock.
2. What is cycle stealing?
We encounter cycle stealing in the context of Direct Memory Access (DMA). Either the DMA controller can use the data bus when the CPU does not need it, or it may force the CPU to temporarily suspend operation. The latter technique is called cycle stealing. Note that cycle stealing can be done only at specific break points in an instruction cycle.
3. What is meant by arm-stickiness?
If one or a few processes have a high access rate to data on one track of a storage disk, then they may monopolize the device by repeated requests to that track. This generally happens with most common device scheduling algorithms (LIFO, SSTF, C-SCAN, etc). High-density multisurface disks are more likely to be affected by this than low density ones.
4. What are the stipulations of C2 level security?
C2 level security provides for:
> Discretionary Access Control
> Identification and Authentication
> Auditing
> Resource reuse
5. What is busy waiting?
The repeated execution of a loop of code while waiting for an event to occur is called busy-waiting. The CPU is not engaged in any real productive activity during this period, and the process does not progress toward completion.
6. What are short-, long- and medium-term scheduling?
Long term scheduler determines which programs are admitted to the system for processing. It controls the degree of multiprogramming. Once admitted, a job becomes a process.
Medium term scheduling is part of the swapping function. This relates to processes that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memory-management criteria.
Short term scheduler, also know as a dispatcher executes most frequently, and makes the finest-grained decision of which process should execute next. This scheduler is invoked whenever an event occurs. It may lead to interruption of one process by preemption.
7. What are short-, long- and medium-term scheduling?
Long term scheduler determines which programs are admitted to the system for processing. It controls the degree of multiprogramming. Once admitted, a job becomes a process.
Medium term scheduling is part of the swapping function. This relates to processes that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memory-management criteria.
Short term scheduler, also know as a dispatcher executes most frequently, and makes the finest-grained decision of which process should execute next. This scheduler is invoked whenever an event occurs. It may lead to interruption of one process by preemption.
8. What are turnaround time and response time?
Turnaround time is the interval between the submission of a job and its completion. Response time is the interval between submission of a request, and the first response to that request.
9. What are the typical elements of a process image?
> User data: Modifiable part of user space. May include program data, user stack area, and programs that may be modified.
> User program: The instructions to be executed.
> System Stack: Each process has one or more LIFO stacks associated with it. Used to store parameters and calling addresses for procedure and system calls.
> Process control Block (PCB): Info needed by the OS to control processes.
10. What is the Translation Lookaside Buffer (TLB)?
In a cached system, the base addresses of the last few referenced pages is maintained in registers called the TLB that aids in faster lookup. TLB contains those page-table entries that have been most recently used. Normally, each virtualmemory reference causes 2 physical memory accesses-- one to fetch appropriate page-table entry, and one to fetch the desired data. Using TLB in-between, this is reduced to just one physicalmemory access in cases of TLB-hit.
11. What is the resident set and working set of a process?
Resident set is that portion of the process image that is actually in real-memory at a particular instant. Working set is that subset of resident set that is actually needed for execution. (Relate this to the variable-window size method for swapping techniques.)
12. Explain the concept of Reentrancy.
It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Eachexecution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack.
Note: A reentrant procedure can be interrupted and called by an interrupting program, and still execute correctly on returning to the procedure.
13. Explain Belady's Anomaly.
Also called FIFO anomaly. Usually, on increasing the number of frames allocated to a process' virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the reverse happens, i.e., the execution time increases even when more frames are allocated to the process. This is Belady's Anomaly. This is true for certain page reference patterns.
14. What is a binary semaphore? What is its use?
A binary semaphore is one, which takes only 0 and 1 as values. They are used to implement mutual exclusion and synchronize concurrentprocesses.
15. What is thrashing?
It is a phenomenon in virtual memory schemes when the processor spends most of its time swapping pages, rather than executing instructions. This is due to an inordinate number of page faults.
16. List the Coffman's conditions that lead to a deadlock.
> Mutual Exclusion: Only one process may use a critical resource at a time.
> Hold & Wait: A process may be allocated some resources while waiting for others.
> No Pre-emption: No resource can be forcible removed from a process holding it.
> Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain.
17. Explain the popular multiprocessor thread-scheduling strategies.
> Load Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis.
> Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads /processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy.
> Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool.
> Dynamic scheduling: The number of thread in a program can be altered during the course of execution.
18. When does the condition 'rendezvous' arise?
In message passing, it is the condition in which, both, the sender and receiver are blocked until the message is delivered.
19. What is a trap and trapdoor?
Trapdoor is a secret undocumented entry point into a program used to grant access without normal methods of access authentication. A trap is a software interrupt, usually the result of an error condition.
20. What are local and global page replacements?
Local replacement means that an incoming page is brought in only to the relevant process' address space. Global replacement policy allows any page frame from any process to be replaced. The latter is applicable to variable partitions model only.
21. Define latency, transfer and seek time with respect to disk I/O.
Seek time is the time required to move the disk arm to the required track. Rotational delay or latency is the time it takes for the beginning of the required sector to reach the head. Sum of seek time (if any) and latency is the access time. Time taken to actually transfer a span of data is transfer time.
22. Describe the Buddy system of memory allocation.
Free memory is maintained in linked lists, each of equal sized blocks. Any such block is of size 2^k. When some memory is required by a process, the block size of next higher order is chosen, and broken into two. Note that the two such pieces differ in address only in their kth bit. Such pieces are called buddies. When any used block is freed, the OS checks to see if its buddy is also free. If so, it is rejoined, and put into the original free-block linked-list.
23. What is time-stamping?
It is a technique proposed by Lamport, used to order events in a distributed system without the use of clocks. This scheme is intended to order events consisting of the transmission of messages. Each system 'i' in the network maintains a counter Ci. Every time a system transmits a message, it increments its counter by 1 and attaches the time-stamp Ti to the message. When a message is received, the receiving system 'j' sets its counter Cj to 1 more than the maximum of its current value and the incoming time-stamp Ti. At each site, the ordering of messages is determined by the following rules: For messages x from site i and y from site j, x precedes y if one of the following conditions holds....(a) if Ti Increased speed and memory capacity of microprocessors together with the support fir virtual memory and
> Growth of client server computing
31. What are the four layers that Windows NT have in order to achieve independence?
> Hardware abstraction layer
> Kernel
> Subsystems
> System Services.
32. What is SMP?
To achieve maximum efficiency and reliability a mode of operation known as symmetric multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor.
33. What are the key object oriented concepts used by Windows NT?
> Encapsulation
> Object class and instance
34. Is Windows NT a full blown object oriented operating system? Give reasons.
No Windows NT is not so, because its not implemented in object oriented language and the data structures reside within one executive component and are not represented as objects and it does not support object oriented capabilities .
35. What is a drawback of MVT?
It does not have the features like
> ability to support multiple processors
> virtual storage
> source level debugging
36. What is process spawning?
When the OS at the explicit request of another process creates a process, this action is called process spawning.
37. How many jobs can be run concurrently on MVT?
15 jobs
38. List out some reasons for process termination.
> Normal completion
> Time limit exceeded
> Memory unavailable
> Bounds violation
> Protection error
> Arithmetic error
> Time overrun
> I/O failure
> Invalid instruction
> Privileged instruction
> Data misuse
> Operator or OS intervention
> Parent termination.
39. What are the reasons for process suspension?
> swapping
> interactive user request
> timing
> parent process request
40. What is process migration?
It is the transfer of sufficient amount of the state of process from one machine to the target machine
41. What is mutant?
In Windows NT a mutant provides kernel mode or user mode mutual exclusion with the notion of ownership.
42. What is an idle thread?
The special thread a dispatcher will execute when no ready thread is found.
43. What is FtDisk?
It is a fault tolerance disk driver for Windows NT.
44. What are the possible threads a thread can have?
> Ready
> Standby
> Running
> Waiting
> Transition
> Terminated.
45. What are rings in Windows NT?
Windows NT uses protection mechanism called rings provides by the process to implement separation between the user mode and kernel mode.
46. What is Executive in Windows NT?
In Windows NT, executive refers to the operating system code that runs in kernel mode.
47. What are the sub-components of I/O manager in Windows NT?
> Network redirector/ Server
> Cache manager.
> File systems
> Network driver
> Device driver
48. What are DDks? Name an operating system that includes this feature.
DDks are device driver kits, which are equivalent to SDKs for writing device drivers. Windows NT includes DDks.
49. What level of security does Windows NT meets?
C2 level security.
fundamental concepts:
1. Explain the concept of Reentrancy.
It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Each execution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack.
Note: A reentrant procedure can be interrupted and called by an interrupting program, and still execute correctly on returning to the procedure.
2. Explain Belady's Anomaly.
Also called FIFO anomaly. Usually, on increasing the number of frames allocated to a process' virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the reverse happens, i.e., the execution time increases even when more frames are allocated tothe process. This is Belady's Anomaly. This is true for certain page reference patterns.
3. What is a binary semaphore? What is its use?
A binary semaphore is one, which takes only 0 and 1 as values. They are used to implement mutual exclusion and synchronize concurrent processes.
4. What is thrashing?
It is a phenomenon in virtual memory schemes when the processor spends most of its time swapping pages, rather than executing instructions. This is due to an inordinate number of page faults.
5. List the Coffman's conditions that lead to a deadlock.
Mutual Exclusion: Only one process may use a critical resource at a time.
Hold & Wait: A process may be allocated some resources while waiting for others.
No Pre-emption: No resource can be forcible removed from a process holding it.
Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain.
6. What are short-, long- and medium-term scheduling?
Long term scheduler determines which programs are admitted to the system for processing. It controls the degree of multiprogramming. Once admitted, a job becomes a process.
Medium term scheduling is part of the swapping function. This relates to processes that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memory-management criteria.
Short term scheduler, also know as a dispatcher executes most frequently, and makes the finest-grained decision of which process should execute next. This scheduler is invoked whenever an event occurs. It may lead to interruption of one process by preemption.
7. What are turnaround time and response time?
Turnaround time is the interval between the submission of a job and its completion. Response time is the interval between submission of a request, and the first response to that request.
8. What are the typical elements of a process image?
User data: Modifiable part of user space. May include program data, user stack area, and programs that may be modified.
User program: The instructions to be executed.
System Stack: Each process has one or more LIFO stacks associated with it. Used to store parameters and calling addresses for procedure and system calls.
Process control Block (PCB): Info needed by the OS to control processes.
9. What is the Translation Lookaside Buffer (TLB)?
In a cached system, the base addresses of the last few referenced pages is maintained in registers called the TLB that aids in faster lookup. TLB contains those page-table entries that have been most recently used. Normally, each virtual memory reference causes 2 physical memory accesses-- one to fetch appropriate page-table entry, and one to fetch the desired data. Using TLB in-between, this is reduced to just one physical memory access in cases of TLB-hit.
10. What is the resident set and working set of a process?
Resident set is that portion of the process image that is actually in real-memory at a particular instant. Working set is that subset of resident set that is actually needed for execution. (Relate this to the variable-window size method for swapping techniques.)
11. When is a system in safe state?
The set of dispatchable processes is in a safe state if there exists at least one temporal order in which all processes can be run to completion without resulting in a deadlock.
12. What is cycle stealing?
We encounter cycle stealing in the context of Direct Memory Access (DMA). Either the DMA controller can use the data bus when the CPU does not need it, or it may force the CPU to temporarily suspend operation. The latter technique is called cycle stealing. Note that cycle stealing can be done only at specific break points in an instruction cycle.
13. What is meant by arm-stickiness?
If one or a few processes have a high access rate to data on one track of a storage disk, then they may monopolize the device by repeated requests to that track. This generally happens with most common device scheduling algorithms (LIFO, SSTF, C-SCAN, etc). High-density multisurface disks are more likely to be affected by this than low density ones.
14. What are the stipulations of C2 level security?
C2 level security provides for:
Discretionary Access Control
Identification and Authentication
Auditing
Resource reuse
15. What is busy waiting?
The repeated execution of a loop of code while waiting for an event to occur is called busy-waiting. The CPU is not engaged in any real productive activity during this period, and the process does not progress toward completion.
16. Explain the popular multiprocessor thread-scheduling strategies.
Load Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis.
Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads / processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy.
Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool.
Dynamic scheduling: The number of thread in a program can be altered during the course of execution.
17. When does the condition 'rendezvous' arise?
In message passing, it is the condition in which, both, the sender and receiver are blocked until the message is delivered.
18. What is a trap and trapdoor?
Trapdoor is a secret undocumented entry point into a program used to grant access without normal methods of access authentication. A trap is a software interrupt, usually the result of an error condition.
19. What are local and global page replacements?
Local replacement means that an incoming page is brought in only to the relevant process' address space. Global replacement policy allows any page frame from any process to be replaced. The latter is applicable to variable partitions model only.
20. Define latency, transfer and seek time with respect to disk I/O.
Seek time is the time required to move the disk arm to the required track. Rotational delay or latency is the time it takes for the beginning of the required sector to reach the head. Sum of seek time (if any) and latency is the access time. Time taken to actually transfer a span of data is transfer time.
22. What is time-stamping?
It is a technique proposed by Lamport, used to order events in a distributed system without the use of clocks. This scheme is intended to order events consisting of the transmission of messages. Each system 'i' in the network maintains a counter Ci. Every time a system transmits a message, it increments its counter by 1 and attaches the time-stamp Ti to the message. When a message is received, the receiving system 'j' sets its counter Cj to 1 more than the maximum of its current value and the incoming time-stamp Ti. At each site, the ordering of messages is determined by the following rules: For messages x from site i and y from site j, x precedes y if one of the following conditions holds....(a) if Ti<Tj or (b) if Ti=Tj and i<j.
23. How are the wait/signal operations for monitor different from those for semaphores?
If a process in a monitor signal and no task is waiting on the condition variable, the signal is lost. So this allows easier program design. Whereas in semaphores, every operation affects the value of the semaphore, so the wait and signal operations should be perfectly balanced in the program.
24. In the context of memory management, what are placement and replacement algorithms?
Placement algorithms determine where in available real-memory to load a program. Common methods are first-fit, next-fit, best-fit. Replacement algorithms are used when memory is full, and one process (or part of a process) needs to be swapped out to accommodate a new program. The replacement algorithm determines which are the partitions to be swapped out.
25. In loading programs into memory, what is the difference between load-time dynamic linking and run-time dynamic linking?
For load-time dynamic linking: Load module to be loaded is read into memory. Any reference to a target external module causes that module to be loaded and the references are updated to a relative address from the start base address of the application module.
With run-time dynamic loading: Some of the linking is postponed until actual reference during execution. Then the correct module is loaded and linked.
26. What are demand- and pre-paging?
With demand paging, a page is brought into memory only when a location on that page is actually referenced during execution. With pre-paging, pages other than the one demanded by a page fault are brought in. The selection of such pages is done based on common access patterns, especially for secondary memory devices.
27. Paging a memory management function, while multiprogramming a processor management function, are the two interdependent?
Yes.
28. What is page cannibalizing?
Page swapping or page replacements are called page cannibalizing.
29. What has triggered the need for multitasking in PCs?
Increased speed and memory capacity of microprocessors together with the support fir virtual memory and
Growth of client server computing
30. What are the four layers that Windows NT have in order to achieve independence?
Hardware abstraction layer
Kernel
Subsystems
System Services.
31. What is SMP?
To achieve maximum efficiency and reliability a mode of operation known as symmetric multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor.
32. What are the key object oriented concepts used by Windows NT?
Encapsulation
Object class and instance
33. Is Windows NT a full blown object oriented operating system? Give reasons.
No Windows NT is not so, because its not implemented in object oriented language and the data structures reside within one executive component and are not represented as objects and it does not support object oriented capabilities .
34. What is a drawback of MVT?
It does not have the features like
ability to support multiple processors
virtual storage
source level debugging
35. What is process spawning?
When the OS at the explicit request of another process creates a process, this action is called process spawning.
36. How many jobs can be run concurrently on MVT?
15 jobs
37. List out some reasons for process termination.
Normal completion
Time limit exceeded
Memory unavailable
Bounds violation
Protection error
Arithmetic error
Time overrun
I/O failure
Invalid instruction
Privileged instruction
Data misuse
Operator or OS intervention
Parent termination.
38. What are the reasons for process suspension?
1. swapping
2. interactive user request
3. timing
4. parent process request
1. When is a system in safe state?
The set of dispatchable processes is in a safe state if there exists at least one temporal order in which all processes can be run to completion without resulting in a deadlock.
2. What is cycle stealing?
We encounter cycle stealing in the context of Direct Memory Access (DMA). Either the DMA controller can use the data bus when the CPU does not need it, or it may force the CPU to temporarily suspend operation. The latter technique is called cycle stealing. Note that cycle stealing can be done only at specific break points in an instruction cycle.
3. What is meant by arm-stickiness?
If one or a few processes have a high access rate to data on one track of a storage disk, then they may monopolize the device by repeated requests to that track. This generally happens with most common device scheduling algorithms (LIFO, SSTF, C-SCAN, etc). High-density multisurface disks are more likely to be affected by this than low density ones.
4. What are the stipulations of C2 level security?
C2 level security provides for:
> Discretionary Access Control
> Identification and Authentication
> Auditing
> Resource reuse
5. What is busy waiting?
The repeated execution of a loop of code while waiting for an event to occur is called busy-waiting. The CPU is not engaged in any real productive activity during this period, and the process does not progress toward completion.
6. What are short-, long- and medium-term scheduling?
Long term scheduler determines which programs are admitted to the system for processing. It controls the degree of multiprogramming. Once admitted, a job becomes a process.
Medium term scheduling is part of the swapping function. This relates to processes that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memory-management criteria.
Short term scheduler, also know as a dispatcher executes most frequently, and makes the finest-grained decision of which process should execute next. This scheduler is invoked whenever an event occurs. It may lead to interruption of one process by preemption.
7. What are short-, long- and medium-term scheduling?
Long term scheduler determines which programs are admitted to the system for processing. It controls the degree of multiprogramming. Once admitted, a job becomes a process.
Medium term scheduling is part of the swapping function. This relates to processes that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memory-management criteria.
Short term scheduler, also know as a dispatcher executes most frequently, and makes the finest-grained decision of which process should execute next. This scheduler is invoked whenever an event occurs. It may lead to interruption of one process by preemption.
8. What are turnaround time and response time?
Turnaround time is the interval between the submission of a job and its completion. Response time is the interval between submission of a request, and the first response to that request.
9. What are the typical elements of a process image?
> User data: Modifiable part of user space. May include program data, user stack area, and programs that may be modified.
> User program: The instructions to be executed.
> System Stack: Each process has one or more LIFO stacks associated with it. Used to store parameters and calling addresses for procedure and system calls.
> Process control Block (PCB): Info needed by the OS to control processes.
10. What is the Translation Lookaside Buffer (TLB)?
In a cached system, the base addresses of the last few referenced pages is maintained in registers called the TLB that aids in faster lookup. TLB contains those page-table entries that have been most recently used. Normally, each virtualmemory reference causes 2 physical memory accesses-- one to fetch appropriate page-table entry, and one to fetch the desired data. Using TLB in-between, this is reduced to just one physicalmemory access in cases of TLB-hit.
11. What is the resident set and working set of a process?
Resident set is that portion of the process image that is actually in real-memory at a particular instant. Working set is that subset of resident set that is actually needed for execution. (Relate this to the variable-window size method for swapping techniques.)
12. Explain the concept of Reentrancy.
It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Eachexecution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack.
Note: A reentrant procedure can be interrupted and called by an interrupting program, and still execute correctly on returning to the procedure.
13. Explain Belady's Anomaly.
Also called FIFO anomaly. Usually, on increasing the number of frames allocated to a process' virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the reverse happens, i.e., the execution time increases even when more frames are allocated to the process. This is Belady's Anomaly. This is true for certain page reference patterns.
14. What is a binary semaphore? What is its use?
A binary semaphore is one, which takes only 0 and 1 as values. They are used to implement mutual exclusion and synchronize concurrentprocesses.
15. What is thrashing?
It is a phenomenon in virtual memory schemes when the processor spends most of its time swapping pages, rather than executing instructions. This is due to an inordinate number of page faults.
16. List the Coffman's conditions that lead to a deadlock.
> Mutual Exclusion: Only one process may use a critical resource at a time.
> Hold & Wait: A process may be allocated some resources while waiting for others.
> No Pre-emption: No resource can be forcible removed from a process holding it.
> Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain.
17. Explain the popular multiprocessor thread-scheduling strategies.
> Load Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis.
> Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads /processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy.
> Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool.
> Dynamic scheduling: The number of thread in a program can be altered during the course of execution.
18. When does the condition 'rendezvous' arise?
In message passing, it is the condition in which, both, the sender and receiver are blocked until the message is delivered.
19. What is a trap and trapdoor?
Trapdoor is a secret undocumented entry point into a program used to grant access without normal methods of access authentication. A trap is a software interrupt, usually the result of an error condition.
20. What are local and global page replacements?
Local replacement means that an incoming page is brought in only to the relevant process' address space. Global replacement policy allows any page frame from any process to be replaced. The latter is applicable to variable partitions model only.
21. Define latency, transfer and seek time with respect to disk I/O.
Seek time is the time required to move the disk arm to the required track. Rotational delay or latency is the time it takes for the beginning of the required sector to reach the head. Sum of seek time (if any) and latency is the access time. Time taken to actually transfer a span of data is transfer time.
22. Describe the Buddy system of memory allocation.
Free memory is maintained in linked lists, each of equal sized blocks. Any such block is of size 2^k. When some memory is required by a process, the block size of next higher order is chosen, and broken into two. Note that the two such pieces differ in address only in their kth bit. Such pieces are called buddies. When any used block is freed, the OS checks to see if its buddy is also free. If so, it is rejoined, and put into the original free-block linked-list.
23. What is time-stamping?
It is a technique proposed by Lamport, used to order events in a distributed system without the use of clocks. This scheme is intended to order events consisting of the transmission of messages. Each system 'i' in the network maintains a counter Ci. Every time a system transmits a message, it increments its counter by 1 and attaches the time-stamp Ti to the message. When a message is received, the receiving system 'j' sets its counter Cj to 1 more than the maximum of its current value and the incoming time-stamp Ti. At each site, the ordering of messages is determined by the following rules: For messages x from site i and y from site j, x precedes y if one of the following conditions holds....(a) if Ti
> Growth of client server computing
31. What are the four layers that Windows NT have in order to achieve independence?
> Hardware abstraction layer
> Kernel
> Subsystems
> System Services.
32. What is SMP?
To achieve maximum efficiency and reliability a mode of operation known as symmetric multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor.
33. What are the key object oriented concepts used by Windows NT?
> Encapsulation
> Object class and instance
34. Is Windows NT a full blown object oriented operating system? Give reasons.
No Windows NT is not so, because its not implemented in object oriented language and the data structures reside within one executive component and are not represented as objects and it does not support object oriented capabilities .
35. What is a drawback of MVT?
It does not have the features like
> ability to support multiple processors
> virtual storage
> source level debugging
36. What is process spawning?
When the OS at the explicit request of another process creates a process, this action is called process spawning.
37. How many jobs can be run concurrently on MVT?
15 jobs
38. List out some reasons for process termination.
> Normal completion
> Time limit exceeded
> Memory unavailable
> Bounds violation
> Protection error
> Arithmetic error
> Time overrun
> I/O failure
> Invalid instruction
> Privileged instruction
> Data misuse
> Operator or OS intervention
> Parent termination.
39. What are the reasons for process suspension?
> swapping
> interactive user request
> timing
> parent process request
40. What is process migration?
It is the transfer of sufficient amount of the state of process from one machine to the target machine
41. What is mutant?
In Windows NT a mutant provides kernel mode or user mode mutual exclusion with the notion of ownership.
42. What is an idle thread?
The special thread a dispatcher will execute when no ready thread is found.
43. What is FtDisk?
It is a fault tolerance disk driver for Windows NT.
44. What are the possible threads a thread can have?
> Ready
> Standby
> Running
> Waiting
> Transition
> Terminated.
45. What are rings in Windows NT?
Windows NT uses protection mechanism called rings provides by the process to implement separation between the user mode and kernel mode.
46. What is Executive in Windows NT?
In Windows NT, executive refers to the operating system code that runs in kernel mode.
47. What are the sub-components of I/O manager in Windows NT?
> Network redirector/ Server
> Cache manager.
> File systems
> Network driver
> Device driver
48. What are DDks? Name an operating system that includes this feature.
DDks are device driver kits, which are equivalent to SDKs for writing device drivers. Windows NT includes DDks.
49. What level of security does Windows NT meets?
C2 level security.
fundamental concepts:
1. Explain the concept of Reentrancy.
It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Each execution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack.
Note: A reentrant procedure can be interrupted and called by an interrupting program, and still execute correctly on returning to the procedure.
2. Explain Belady's Anomaly.
Also called FIFO anomaly. Usually, on increasing the number of frames allocated to a process' virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the reverse happens, i.e., the execution time increases even when more frames are allocated tothe process. This is Belady's Anomaly. This is true for certain page reference patterns.
3. What is a binary semaphore? What is its use?
A binary semaphore is one, which takes only 0 and 1 as values. They are used to implement mutual exclusion and synchronize concurrent processes.
4. What is thrashing?
It is a phenomenon in virtual memory schemes when the processor spends most of its time swapping pages, rather than executing instructions. This is due to an inordinate number of page faults.
5. List the Coffman's conditions that lead to a deadlock.
Mutual Exclusion: Only one process may use a critical resource at a time.
Hold & Wait: A process may be allocated some resources while waiting for others.
No Pre-emption: No resource can be forcible removed from a process holding it.
Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain.
6. What are short-, long- and medium-term scheduling?
Long term scheduler determines which programs are admitted to the system for processing. It controls the degree of multiprogramming. Once admitted, a job becomes a process.
Medium term scheduling is part of the swapping function. This relates to processes that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memory-management criteria.
Short term scheduler, also know as a dispatcher executes most frequently, and makes the finest-grained decision of which process should execute next. This scheduler is invoked whenever an event occurs. It may lead to interruption of one process by preemption.
7. What are turnaround time and response time?
Turnaround time is the interval between the submission of a job and its completion. Response time is the interval between submission of a request, and the first response to that request.
8. What are the typical elements of a process image?
User data: Modifiable part of user space. May include program data, user stack area, and programs that may be modified.
User program: The instructions to be executed.
System Stack: Each process has one or more LIFO stacks associated with it. Used to store parameters and calling addresses for procedure and system calls.
Process control Block (PCB): Info needed by the OS to control processes.
9. What is the Translation Lookaside Buffer (TLB)?
In a cached system, the base addresses of the last few referenced pages is maintained in registers called the TLB that aids in faster lookup. TLB contains those page-table entries that have been most recently used. Normally, each virtual memory reference causes 2 physical memory accesses-- one to fetch appropriate page-table entry, and one to fetch the desired data. Using TLB in-between, this is reduced to just one physical memory access in cases of TLB-hit.
10. What is the resident set and working set of a process?
Resident set is that portion of the process image that is actually in real-memory at a particular instant. Working set is that subset of resident set that is actually needed for execution. (Relate this to the variable-window size method for swapping techniques.)
11. When is a system in safe state?
The set of dispatchable processes is in a safe state if there exists at least one temporal order in which all processes can be run to completion without resulting in a deadlock.
12. What is cycle stealing?
We encounter cycle stealing in the context of Direct Memory Access (DMA). Either the DMA controller can use the data bus when the CPU does not need it, or it may force the CPU to temporarily suspend operation. The latter technique is called cycle stealing. Note that cycle stealing can be done only at specific break points in an instruction cycle.
13. What is meant by arm-stickiness?
If one or a few processes have a high access rate to data on one track of a storage disk, then they may monopolize the device by repeated requests to that track. This generally happens with most common device scheduling algorithms (LIFO, SSTF, C-SCAN, etc). High-density multisurface disks are more likely to be affected by this than low density ones.
14. What are the stipulations of C2 level security?
C2 level security provides for:
Discretionary Access Control
Identification and Authentication
Auditing
Resource reuse
15. What is busy waiting?
The repeated execution of a loop of code while waiting for an event to occur is called busy-waiting. The CPU is not engaged in any real productive activity during this period, and the process does not progress toward completion.
16. Explain the popular multiprocessor thread-scheduling strategies.
Load Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis.
Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads / processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy.
Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool.
Dynamic scheduling: The number of thread in a program can be altered during the course of execution.
17. When does the condition 'rendezvous' arise?
In message passing, it is the condition in which, both, the sender and receiver are blocked until the message is delivered.
18. What is a trap and trapdoor?
Trapdoor is a secret undocumented entry point into a program used to grant access without normal methods of access authentication. A trap is a software interrupt, usually the result of an error condition.
19. What are local and global page replacements?
Local replacement means that an incoming page is brought in only to the relevant process' address space. Global replacement policy allows any page frame from any process to be replaced. The latter is applicable to variable partitions model only.
20. Define latency, transfer and seek time with respect to disk I/O.
Seek time is the time required to move the disk arm to the required track. Rotational delay or latency is the time it takes for the beginning of the required sector to reach the head. Sum of seek time (if any) and latency is the access time. Time taken to actually transfer a span of data is transfer time.
22. What is time-stamping?
It is a technique proposed by Lamport, used to order events in a distributed system without the use of clocks. This scheme is intended to order events consisting of the transmission of messages. Each system 'i' in the network maintains a counter Ci. Every time a system transmits a message, it increments its counter by 1 and attaches the time-stamp Ti to the message. When a message is received, the receiving system 'j' sets its counter Cj to 1 more than the maximum of its current value and the incoming time-stamp Ti. At each site, the ordering of messages is determined by the following rules: For messages x from site i and y from site j, x precedes y if one of the following conditions holds....(a) if Ti<Tj or (b) if Ti=Tj and i<j.
23. How are the wait/signal operations for monitor different from those for semaphores?
If a process in a monitor signal and no task is waiting on the condition variable, the signal is lost. So this allows easier program design. Whereas in semaphores, every operation affects the value of the semaphore, so the wait and signal operations should be perfectly balanced in the program.
24. In the context of memory management, what are placement and replacement algorithms?
Placement algorithms determine where in available real-memory to load a program. Common methods are first-fit, next-fit, best-fit. Replacement algorithms are used when memory is full, and one process (or part of a process) needs to be swapped out to accommodate a new program. The replacement algorithm determines which are the partitions to be swapped out.
25. In loading programs into memory, what is the difference between load-time dynamic linking and run-time dynamic linking?
For load-time dynamic linking: Load module to be loaded is read into memory. Any reference to a target external module causes that module to be loaded and the references are updated to a relative address from the start base address of the application module.
With run-time dynamic loading: Some of the linking is postponed until actual reference during execution. Then the correct module is loaded and linked.
26. What are demand- and pre-paging?
With demand paging, a page is brought into memory only when a location on that page is actually referenced during execution. With pre-paging, pages other than the one demanded by a page fault are brought in. The selection of such pages is done based on common access patterns, especially for secondary memory devices.
27. Paging a memory management function, while multiprogramming a processor management function, are the two interdependent?
Yes.
28. What is page cannibalizing?
Page swapping or page replacements are called page cannibalizing.
29. What has triggered the need for multitasking in PCs?
Increased speed and memory capacity of microprocessors together with the support fir virtual memory and
Growth of client server computing
30. What are the four layers that Windows NT have in order to achieve independence?
Hardware abstraction layer
Kernel
Subsystems
System Services.
31. What is SMP?
To achieve maximum efficiency and reliability a mode of operation known as symmetric multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor.
32. What are the key object oriented concepts used by Windows NT?
Encapsulation
Object class and instance
33. Is Windows NT a full blown object oriented operating system? Give reasons.
No Windows NT is not so, because its not implemented in object oriented language and the data structures reside within one executive component and are not represented as objects and it does not support object oriented capabilities .
34. What is a drawback of MVT?
It does not have the features like
ability to support multiple processors
virtual storage
source level debugging
35. What is process spawning?
When the OS at the explicit request of another process creates a process, this action is called process spawning.
36. How many jobs can be run concurrently on MVT?
15 jobs
37. List out some reasons for process termination.
Normal completion
Time limit exceeded
Memory unavailable
Bounds violation
Protection error
Arithmetic error
Time overrun
I/O failure
Invalid instruction
Privileged instruction
Data misuse
Operator or OS intervention
Parent termination.
38. What are the reasons for process suspension?
1. swapping
2. interactive user request
3. timing
4. parent process request
corejava
1.what is a transient variable?
A transient variable is a variable that may not be serialized.
2.which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.
3.Why do threads block on I/O?
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.
4. How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
5. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.
6. Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object..
7. What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
8. Is null a keyword?
The null value is not a keyword.
9. What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component to display normally.
10. What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.
11. Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
12. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
13. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
14. Which characters may be used as the second character of an identifier,
but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
15. What is the List interface?
The List interface provides support for ordered collections of objects.
16. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
17. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
18. What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
19. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.
20. What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
21. Which method of the Component class is used to set the position and
size of a component?
setBounds()
22. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
23What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
24. Which java.util classes and interfaces support event handling?
The EventObject class and the EventListener interface support event processing.
25. Is sizeof a keyword?
The sizeof operator is not a keyword.
26. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
27. Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
28. What restrictions are placed on the location of a package statement
within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and comments).
29. Can an object's finalize() method be invoked while it is reachable?
An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.
30. What is the immediate superclass of the Applet class?
Panel
31. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and
other factors.
32. Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
33. What value does readLine() return when it has reached the end of a file?
The readLine() method returns null when it has reached the end of a file.
34. What is the immediate superclass of the Dialog class?
Window
35. What is clipping?
Clipping is the process of confining paint operations to a limited area or shape.
36. What is a native method?
A native method is a method that is implemented in a language other than Java.
37. Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following:
for(;;) ;
38. What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left
39. When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.
40. To what value is a variable of the String type automatically initialized?
The default value of an String type is null.
41. What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
42. What is the difference between a MenuItem and a CheckboxMenuItem?
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.
43. What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
44. What class is the top of the AWT event hierarchy?
The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.
45. When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.
46. Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
47. What is the range of the short type?
The range of the short type is -(2^15) to 2^15 - 1.
48. What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.
49. In which package are most of the AWT events that support the event-delegation
model defined?
Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.
50. What is the immediate superclass of Menu?
MenuItem
51. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
52. Which class is the immediate superclass of the MenuComponent class.
Object
53. What invokes a thread's run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
54. What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
55. Name three subclasses of the Component class.
Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent
56. What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
57. Which Container method is used to cause a container to be laid out and redisplayed?
validate()
58. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
59. How many times may an object's finalize() method be invoked by the
garbage collector?
An object's finalize() method may only be invoked once by the garbage collector.
60. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
61. What is the argument type of a program's main() method?
A program's main() method takes an argument of the String[] type.
62. Which Java operator is right associative?
The = operator is right associative.
63. What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
64. Can a double value be cast to a byte?
Yes, a double value can be cast to a byte.
65. What is the difference between a break statement and a continue statement?
A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
66. What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its implements clause.
67. What method is invoked to cause an object to begin executing as a separate thread?
The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.
68. Name two subclasses of the TextComponent class.
TextField and TextArea
69. What is the advantage of the event-delegation model over the earlier event-inheritance model?
The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.
70. Which containers may have a MenuBar?
Frame
71. How are commas used in the intialization and iteration parts of a for statement?
Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.
72. What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods..
73. What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.
74. How are Java source code files named?
A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.
75. What is the relationship between the Canvas class and the Graphics class?
A Canvas object provides access to a Graphics object via its paint() method.
76. What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
77. What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.
78. Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.
79. What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.
80. What is the difference between the String and StringBuffer classes?
String objects are constants. StringBuffer objects are not.
81. If a variable is declared as private, where may the variable be accessed?
A private variable may only be accessed within the class in which it is declared.
82. What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.
83. What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs.
84. How are the elements of a BorderLayout organized?
The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.
85. What is the % operator?
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.
86. When can an object reference be cast to an interface reference?
An object reference be cast to an interface reference when the object implements the referenced interface.
87. What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can have a menu bar.
88. Which class is extended by all other classes?
The Object class is extended by all other classes.
89. Can an object be garbage collected while it is still reachable?
A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected..
90. Is the ternary operator written x : y ? z or x ? y : z ?
It is written x ? y : z.
91. What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.
92. How is rounding performed under integer division?
The fractional part of the result is truncated. This is known as rounding toward zero.
93. What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
94. What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
95. What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
96. If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
97. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
98. What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
99. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
100. For which statements does it make sense to use a label?
The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement.
101. What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
102. Which TextComponent method is used to set a TextComponent to the read-only state?
setEditable()
103. How are the elements of a CardLayout organized?
The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
104. Is &&= a valid Java operator?
No, it is not.
105. Name the eight primitive Java types.
The eight primitive types are byte, char, short, int, long, float, double, and boolean.
106. Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object's design.
107. What is the relationship between clipping and repainting?
When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.
108. Is "abc" a primitive value?
The String literal "abc" is not a primitive value. It is a String object.
109. What is the relationship between an event-listener interface and an
event-adapter class?
An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.
110. What restrictions are placed on the values of each case of a switch statement?
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
111. What modifiers may be used with an interface declaration?
An interface may be declared as public or abstract.
112. Is a class a subclass of itself?
A class is a subclass of itself.
113. What is the highest-level event class of the event-delegation model?
The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.
114. What event results from the clicking of a button?
The ActionEvent event is generated as the result of the clicking of a button.
115. How can a GUI component handle its own events?
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.
116. What is the difference between a while statement and a do statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
117. How are the elements of a GridBagLayout organized?
The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
118. What advantage do Java's layout managers provide over traditional windowing systems?
Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.
119. What is the Collection interface?
The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.
120. What modifiers can be used with a local inner class?
A local inner class may be final or abstract.
121. What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
122. What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.
123. What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.
124. Can an exception be rethrown?
Yes, an exception can be rethrown.
125. Which Math method is used to calculate the absolute value of a number?
The abs() method is used to calculate absolute values.
126. How does multithreading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
127. When does the compiler supply a default constructor for a class?
The compiler supplies a default constructor for a class if no other constructors are provided.
128. When is the finally clause of a try-catch-finally statement executed?
The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause.
129. Which class is the immediate superclass of the Container class?
Component
130. If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
131. How can the Checkbox class be used to create a radio button?
By associating Checkbox objects with a CheckboxGroup.
132. Which non-Unicode letter characters may be used as the first character
of an identifier?
The non-Unicode letter characters $ and _ may appear as the first character of an identifier
133. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
134. What happens when you invoke a thread's interrupt method while it is
sleeping or waiting?
When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.
135. What is casting?
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
136. What is the return type of a program's main() method?
A program's main() method has a void return type.
137. Name four Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane
138. What is the difference between a Choice and a List?
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.
139. What class of exceptions are generated by the Java run-time system?
The Java runtime system generates RuntimeException and Error exceptions.
140. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
141. What is the difference between a field variable and a local variable?
A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.
142. Under what conditions is an object's finalize() method invoked by the garbage collector?
The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable.
143. How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
144. What is the relationship between a method's throws clause and the exceptions
that can be thrown during the method's execution?
A method's throws clause must declare any checked exceptions that are not caught within the body of the method.
145. What is the difference between the JDK 1.02 event model and the event-delegation
model introduced with JDK 1.1?
The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component's container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried..
In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.
146. How is it possible for two String objects with identical values not to be equal
under the == operator?
The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.
147. Why are the methods of the Math class static?
So they can be invoked as if they are a mathematical code library.
148. What Checkbox method allows you to tell if a Checkbox is checked?
getState()
149. What state is a thread in when it is executing?
An executing thread is in the running state.
150. What are the legal operands of the instanceof operator?
The left operand is an object reference or null value and the right operand is a class, interface, or array type.
151. How are the elements of a GridLayout organized?
The elements of a GridBad layout are of equal size and are laid out using the squares of a grid.
152. What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
153. If an object is garbage collected, can it become reachable again?
Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
154. What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
155. What classes of exceptions may be thrown by a throw statement?
A throw statement may throw any expression that may be assigned to the Throwable type.
156. What are E and PI?
E is the base of the natural logarithm and PI is mathematical value pi.
157. Are true and false keywords?
The values true and false are not keywords.
158. What is a void return type?
A void return type indicates that a method does not return a value.
159. What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.
160. What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
161. What happens when you add a double value to a String?
The result is a String object.
162. What is your platform's default character encoding?
If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1..
163. Which package is always imported by default?
The java.lang package is always imported by default.
164. What interface must an object implement before it can be written to a
stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
165. How are this and super used?
this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance.
166. What is the purpose of garbage collection?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused
167. What is a compilation unit?
A compilation unit is a Java source code file.
168. What interface is extended by AWT event listeners?
All AWT event listeners extend the java.util.EventListener interface.
169. What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type.
The overriding method may not limit the access of the method it overrides.
The overriding method may not throw any exceptions that may not be thrown
by the overridden method.
170. How can a dead thread be restarted?
A dead thread cannot be restarted.
171. What happens if an exception is not caught?
An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.
172. What is a layout manager?
A layout manager is an object that is used to organize components in a container.
173. Which arithmetic operations can result in the throwing of an ArithmeticException?
Integer / and % can result in the throwing of an ArithmeticException.
174. What are three ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
175. Can an abstract class be final?
An abstract class may not be declared as final.
176. What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.
177. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.
178. What is numeric promotion?
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations
may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
179. What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
180. What is the difference between a public and a non-public class?
A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.
181. To what value is a variable of the boolean type automatically initialized?
The default value of the boolean type is false.
182. Can try statements be nested?
Try statements may be tested.
183. What is the difference between the prefix and postfix forms of the ++ operator?
The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.
184. What is the purpose of a statement block?
A statement block is used to organize a sequence of statements as a single statement group.
185. What is a Java package and how is it used?
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
186. What modifiers may be used with a top-level class?
A top-level class may be public, abstract, or final.
187. What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class
hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program..
188. How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.
189. Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.
190. When is an object subject to garbage collection?
An object is subject to garbage collection when it becomes unreachable to the program in which it is used.
191. What method must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.
192. What methods are used to get and set the text label displayed by a Button object?
getLabel() and setLabel()
193. Which Component subclass is used for drawing and painting?
Canvas
194. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
195. What are the two basic ways in which classes that can be run as threads may be defined?
A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.
196. What are the problems faced by Java programmers who don't use layout managers?
Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.
197. What is the difference between an if statement and a switch statement?
The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.
198. What happens when you add a double value to a String?
The result is a String object.
199. What is the List interface?
The List interface provides support for ordered collections of objects.
A transient variable is a variable that may not be serialized.
2.which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.
3.Why do threads block on I/O?
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.
4. How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
5. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.
6. Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object..
7. What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
8. Is null a keyword?
The null value is not a keyword.
9. What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component to display normally.
10. What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.
11. Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
12. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
13. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
14. Which characters may be used as the second character of an identifier,
but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
15. What is the List interface?
The List interface provides support for ordered collections of objects.
16. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
17. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
18. What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
19. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.
20. What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
21. Which method of the Component class is used to set the position and
size of a component?
setBounds()
22. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
23What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
24. Which java.util classes and interfaces support event handling?
The EventObject class and the EventListener interface support event processing.
25. Is sizeof a keyword?
The sizeof operator is not a keyword.
26. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
27. Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
28. What restrictions are placed on the location of a package statement
within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and comments).
29. Can an object's finalize() method be invoked while it is reachable?
An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.
30. What is the immediate superclass of the Applet class?
Panel
31. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and
other factors.
32. Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
33. What value does readLine() return when it has reached the end of a file?
The readLine() method returns null when it has reached the end of a file.
34. What is the immediate superclass of the Dialog class?
Window
35. What is clipping?
Clipping is the process of confining paint operations to a limited area or shape.
36. What is a native method?
A native method is a method that is implemented in a language other than Java.
37. Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following:
for(;;) ;
38. What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left
39. When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.
40. To what value is a variable of the String type automatically initialized?
The default value of an String type is null.
41. What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
42. What is the difference between a MenuItem and a CheckboxMenuItem?
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.
43. What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
44. What class is the top of the AWT event hierarchy?
The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.
45. When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.
46. Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
47. What is the range of the short type?
The range of the short type is -(2^15) to 2^15 - 1.
48. What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.
49. In which package are most of the AWT events that support the event-delegation
model defined?
Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.
50. What is the immediate superclass of Menu?
MenuItem
51. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
52. Which class is the immediate superclass of the MenuComponent class.
Object
53. What invokes a thread's run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
54. What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
55. Name three subclasses of the Component class.
Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent
56. What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
57. Which Container method is used to cause a container to be laid out and redisplayed?
validate()
58. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
59. How many times may an object's finalize() method be invoked by the
garbage collector?
An object's finalize() method may only be invoked once by the garbage collector.
60. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
61. What is the argument type of a program's main() method?
A program's main() method takes an argument of the String[] type.
62. Which Java operator is right associative?
The = operator is right associative.
63. What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
64. Can a double value be cast to a byte?
Yes, a double value can be cast to a byte.
65. What is the difference between a break statement and a continue statement?
A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
66. What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its implements clause.
67. What method is invoked to cause an object to begin executing as a separate thread?
The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.
68. Name two subclasses of the TextComponent class.
TextField and TextArea
69. What is the advantage of the event-delegation model over the earlier event-inheritance model?
The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.
70. Which containers may have a MenuBar?
Frame
71. How are commas used in the intialization and iteration parts of a for statement?
Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.
72. What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods..
73. What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.
74. How are Java source code files named?
A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.
75. What is the relationship between the Canvas class and the Graphics class?
A Canvas object provides access to a Graphics object via its paint() method.
76. What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
77. What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.
78. Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.
79. What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.
80. What is the difference between the String and StringBuffer classes?
String objects are constants. StringBuffer objects are not.
81. If a variable is declared as private, where may the variable be accessed?
A private variable may only be accessed within the class in which it is declared.
82. What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.
83. What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs.
84. How are the elements of a BorderLayout organized?
The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.
85. What is the % operator?
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.
86. When can an object reference be cast to an interface reference?
An object reference be cast to an interface reference when the object implements the referenced interface.
87. What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can have a menu bar.
88. Which class is extended by all other classes?
The Object class is extended by all other classes.
89. Can an object be garbage collected while it is still reachable?
A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected..
90. Is the ternary operator written x : y ? z or x ? y : z ?
It is written x ? y : z.
91. What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.
92. How is rounding performed under integer division?
The fractional part of the result is truncated. This is known as rounding toward zero.
93. What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
94. What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
95. What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
96. If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
97. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
98. What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
99. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
100. For which statements does it make sense to use a label?
The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement.
101. What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
102. Which TextComponent method is used to set a TextComponent to the read-only state?
setEditable()
103. How are the elements of a CardLayout organized?
The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
104. Is &&= a valid Java operator?
No, it is not.
105. Name the eight primitive Java types.
The eight primitive types are byte, char, short, int, long, float, double, and boolean.
106. Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object's design.
107. What is the relationship between clipping and repainting?
When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.
108. Is "abc" a primitive value?
The String literal "abc" is not a primitive value. It is a String object.
109. What is the relationship between an event-listener interface and an
event-adapter class?
An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.
110. What restrictions are placed on the values of each case of a switch statement?
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
111. What modifiers may be used with an interface declaration?
An interface may be declared as public or abstract.
112. Is a class a subclass of itself?
A class is a subclass of itself.
113. What is the highest-level event class of the event-delegation model?
The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.
114. What event results from the clicking of a button?
The ActionEvent event is generated as the result of the clicking of a button.
115. How can a GUI component handle its own events?
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.
116. What is the difference between a while statement and a do statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
117. How are the elements of a GridBagLayout organized?
The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
118. What advantage do Java's layout managers provide over traditional windowing systems?
Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.
119. What is the Collection interface?
The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.
120. What modifiers can be used with a local inner class?
A local inner class may be final or abstract.
121. What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
122. What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.
123. What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.
124. Can an exception be rethrown?
Yes, an exception can be rethrown.
125. Which Math method is used to calculate the absolute value of a number?
The abs() method is used to calculate absolute values.
126. How does multithreading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
127. When does the compiler supply a default constructor for a class?
The compiler supplies a default constructor for a class if no other constructors are provided.
128. When is the finally clause of a try-catch-finally statement executed?
The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause.
129. Which class is the immediate superclass of the Container class?
Component
130. If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
131. How can the Checkbox class be used to create a radio button?
By associating Checkbox objects with a CheckboxGroup.
132. Which non-Unicode letter characters may be used as the first character
of an identifier?
The non-Unicode letter characters $ and _ may appear as the first character of an identifier
133. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
134. What happens when you invoke a thread's interrupt method while it is
sleeping or waiting?
When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.
135. What is casting?
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
136. What is the return type of a program's main() method?
A program's main() method has a void return type.
137. Name four Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane
138. What is the difference between a Choice and a List?
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.
139. What class of exceptions are generated by the Java run-time system?
The Java runtime system generates RuntimeException and Error exceptions.
140. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
141. What is the difference between a field variable and a local variable?
A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.
142. Under what conditions is an object's finalize() method invoked by the garbage collector?
The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable.
143. How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
144. What is the relationship between a method's throws clause and the exceptions
that can be thrown during the method's execution?
A method's throws clause must declare any checked exceptions that are not caught within the body of the method.
145. What is the difference between the JDK 1.02 event model and the event-delegation
model introduced with JDK 1.1?
The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component's container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried..
In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.
146. How is it possible for two String objects with identical values not to be equal
under the == operator?
The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.
147. Why are the methods of the Math class static?
So they can be invoked as if they are a mathematical code library.
148. What Checkbox method allows you to tell if a Checkbox is checked?
getState()
149. What state is a thread in when it is executing?
An executing thread is in the running state.
150. What are the legal operands of the instanceof operator?
The left operand is an object reference or null value and the right operand is a class, interface, or array type.
151. How are the elements of a GridLayout organized?
The elements of a GridBad layout are of equal size and are laid out using the squares of a grid.
152. What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
153. If an object is garbage collected, can it become reachable again?
Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
154. What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
155. What classes of exceptions may be thrown by a throw statement?
A throw statement may throw any expression that may be assigned to the Throwable type.
156. What are E and PI?
E is the base of the natural logarithm and PI is mathematical value pi.
157. Are true and false keywords?
The values true and false are not keywords.
158. What is a void return type?
A void return type indicates that a method does not return a value.
159. What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.
160. What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
161. What happens when you add a double value to a String?
The result is a String object.
162. What is your platform's default character encoding?
If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1..
163. Which package is always imported by default?
The java.lang package is always imported by default.
164. What interface must an object implement before it can be written to a
stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
165. How are this and super used?
this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance.
166. What is the purpose of garbage collection?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused
167. What is a compilation unit?
A compilation unit is a Java source code file.
168. What interface is extended by AWT event listeners?
All AWT event listeners extend the java.util.EventListener interface.
169. What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type.
The overriding method may not limit the access of the method it overrides.
The overriding method may not throw any exceptions that may not be thrown
by the overridden method.
170. How can a dead thread be restarted?
A dead thread cannot be restarted.
171. What happens if an exception is not caught?
An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.
172. What is a layout manager?
A layout manager is an object that is used to organize components in a container.
173. Which arithmetic operations can result in the throwing of an ArithmeticException?
Integer / and % can result in the throwing of an ArithmeticException.
174. What are three ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
175. Can an abstract class be final?
An abstract class may not be declared as final.
176. What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.
177. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.
178. What is numeric promotion?
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations
may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
179. What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
180. What is the difference between a public and a non-public class?
A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.
181. To what value is a variable of the boolean type automatically initialized?
The default value of the boolean type is false.
182. Can try statements be nested?
Try statements may be tested.
183. What is the difference between the prefix and postfix forms of the ++ operator?
The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.
184. What is the purpose of a statement block?
A statement block is used to organize a sequence of statements as a single statement group.
185. What is a Java package and how is it used?
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
186. What modifiers may be used with a top-level class?
A top-level class may be public, abstract, or final.
187. What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class
hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program..
188. How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.
189. Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.
190. When is an object subject to garbage collection?
An object is subject to garbage collection when it becomes unreachable to the program in which it is used.
191. What method must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.
192. What methods are used to get and set the text label displayed by a Button object?
getLabel() and setLabel()
193. Which Component subclass is used for drawing and painting?
Canvas
194. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
195. What are the two basic ways in which classes that can be run as threads may be defined?
A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.
196. What are the problems faced by Java programmers who don't use layout managers?
Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.
197. What is the difference between an if statement and a switch statement?
The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.
198. What happens when you add a double value to a String?
The result is a String object.
199. What is the List interface?
The List interface provides support for ordered collections of objects.
mca
Ques. What is M.C.A?
Ans. M.C.A ( Master of Computer Application ) is generally a 3-year post graduate degree/diploma in Computer Applications. In some institutes it is called PGDCA, PGDIT etc.
Ques. Should I opt for MCA or MBA in systems?
Ans. The classical dilemma faced by those among you who are interested in a career in software would be whether to go for an MCA or an MBA in systems.
This dilemma according to us should simply be converted into a question, which you should ask yourself, do I want a technical career path or a managerial one? The answer to this question would be the answer to your dilemma.
The MBA systems graduate would be actively involved in implementing the top and middle managements IT initiatives, he would translate the management's growth objectives into a plan for system requirements that need to be put in place in order to enable the above objectives .He would then pass on these requirements to the MCA who would implement the plan for system requirements.
Thus one can see that the career path for the MBA systems graduate is managerial while the career path of the MCA graduate is technical.
Ques. What are the career opportunities after M.C.A.?
Ans. Today's is an age of computers. As an M.C.A you can work-
(a) In a consultancy firm such as TCS
(b) In a large corporation having an in-house systems department such as TUL
(c) As an entrepreneur providing complete (or specific) solutions to problems of your
(d) As systems developer in any organization big or small.
Ques. What are the different specializations I can opt in MCA?
Ans. There are many fields an MCA can specialize in the last year/semester of his 3 year programme.
(a) Systems Management
(b) Management Information Systems (MIS)
(c) Systems Development
(d) Systems Engineering
(e) Networking
(f) Internet working
(g) Application Software
(h) Software Development
(i) Troubleshooting
(j) Hardware Technology
Ans. M.C.A ( Master of Computer Application ) is generally a 3-year post graduate degree/diploma in Computer Applications. In some institutes it is called PGDCA, PGDIT etc.
Ques. Should I opt for MCA or MBA in systems?
Ans. The classical dilemma faced by those among you who are interested in a career in software would be whether to go for an MCA or an MBA in systems.
This dilemma according to us should simply be converted into a question, which you should ask yourself, do I want a technical career path or a managerial one? The answer to this question would be the answer to your dilemma.
The MBA systems graduate would be actively involved in implementing the top and middle managements IT initiatives, he would translate the management's growth objectives into a plan for system requirements that need to be put in place in order to enable the above objectives .He would then pass on these requirements to the MCA who would implement the plan for system requirements.
Thus one can see that the career path for the MBA systems graduate is managerial while the career path of the MCA graduate is technical.
Ques. What are the career opportunities after M.C.A.?
Ans. Today's is an age of computers. As an M.C.A you can work-
(a) In a consultancy firm such as TCS
(b) In a large corporation having an in-house systems department such as TUL
(c) As an entrepreneur providing complete (or specific) solutions to problems of your
(d) As systems developer in any organization big or small.
Ques. What are the different specializations I can opt in MCA?
Ans. There are many fields an MCA can specialize in the last year/semester of his 3 year programme.
(a) Systems Management
(b) Management Information Systems (MIS)
(c) Systems Development
(d) Systems Engineering
(e) Networking
(f) Internet working
(g) Application Software
(h) Software Development
(i) Troubleshooting
(j) Hardware Technology
c++
1.
Can we declare a static function as virtual?
Ans: No. The virtual function mechanism is used on the specific object that determines which virtual function to call. Since the static functions are not any way related to objects, they cannot be declared as virtual.
-------------------------------------------------------------------------------------------------
2.
Can user-defined object be declared as static data member of another class?
Ans: Yes. The following code shows how to initialize a user-defined object.
#include
class test
{
int i ;
public :
test ( int ii = 0 )
{
i = ii ;
}
} ;
class sample
{
static test s ;
} ;
test sample::s ( 26 ) ;
Here we have initialized the object s by calling the one-argument constructor. We can use the same convention to initialize the object by calling multiple-argument constructor.
-------------------------------------------------------------------------------------------------
3.
What is forward referencing and when should it be used?
Ans: Consider the following program:
class test
{
public :
friend void fun ( sample, test ) ;
} ;
class sample
{
public :
friend void fun ( sample, test ) ;
} ;
void fun ( sample s, test t )
{
// code
}
void main( )
{
sample s ;
test t ;
fun ( s, t ) ;
}
This program would not compile. It gives an error that sample is undeclared identifier in the statement friend void fun ( sample, test ) ; of the class test. This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of theclass sample before the definition of class test. The following statement is the forward reference of class sample. Forward referencing is generally required when we make a class or a function as a friend.
-------------------------------------------------------------------------------------------------
4.
The istream_withassign class has been derived from the istream class and overloaded assignment operator has been added to it. The _withassign classes are much like their base classes except that they include overloaded assignment operators. Using these operators the objects of the _withassign classes can be copied. The istream, ostream, and iostream classes are made uncopyable by making their overloaded copy constructor and assignment operators private.
-------------------------------------------------------------------------------------------------
5.
How do I write my own zero-argument manipulator that should work same as hex?
Ans: This is shown in following program.
#include
ostream& myhex ( ostream &o )
{
o.setf ( ios::hex) ;
return o ;
}
void main( )
{
cout << endl << myhex << 2000 ;
}
-------------------------------------------------------------------------------------------------
6.
We all know that a const variable needs to be initialized at the time of declaration. Then how come the program given below runs properly even when we have not initialized p?
#include
void main( )
{
const char *p ;
p = "A const pointer" ;
cout << p ;
}
Ans: The output of the above program is 'A const pointer'. This is because in this program p is declared as 'const char*' which means that value stored at p will be constant and not p and so the program works properly
7.
How do I refer to a name of class or function that is defined within a namespace?
Ans: There are two ways in which we can refer to a name of class or function that is defined within a namespace: Using scope resolution operator through the using keyword. This is shown in following example:
namespace name1
{
class sample1
{
// code
} ;
}
namespace name2
{
class sample2
{
// code
} ;
}
using namespace name2 ;
void main( )
{
name1::sample1 s1 ;
sample2 s2 ;
}
Here, class sample1 is referred using the scope resolution operator. On the other hand we can directly refer to class sample2 because of the statement using namespace name2 ; the using keyword declares all the names in the namespace to be in the current scope. So we can use the names without any qualifiers.
-------------------------------------------------------------------------------------------------
8.
While overloading a binary operator can we provide default values?
Ans: No!. This is because even if we provide the default arguments to the parameters of the overloadedoperator function we would end up using the binary operator incorrectly. This is explained in the following example:
sample operator + ( sample a, sample b = sample (2, 3.5f ) )
{
}
void main( )
{
sample s1, s2, s3 ;
s3 = s1 + ; // error
}
-------------------------------------------------------------------------------------------------
9.
How do I carry out conversion of one object of user-defined type to another?
Ans: To perform conversion from one user-defined type to another we need to provide conversion function. Following program demonstrates how to provide such conversion function.
class circle
{
private :
int radius ;
public:
circle ( int r = 0 )
{
radius = r ;
}
} ;
class rectangle
{
private :
int length, breadth ;
public :
rectangle( int l, int b )
{
length = l ;
breadth = b ;
}
operator circle( )
{
return circle ( length ) ;
}
} ;
void main( )
{
rectangle r ( 20, 10 ) ;
circle c;
c = r ;
}
Here, when the statement c = r ; is executed the compiler searches for an overloaded assignment operator in the class circle which accepts the object of type rectangle. Since there is no such overloaded assignment operator, the conversion operator function that converts the rectangle object to the circle object is searched in the rectangle class. We have provided such a conversion function in the rectangle class. This conversion operator function returns a circle object. By default conversion operators have the name and return type same as the object type to which it converts to. Here the type of the object is circle and hence the name of the operator function as well as the return type is circle.
-------------------------------------------------------------------------------------------------
10.
How do I write code that allows to create only one instance of a class?
Ans: This is shown in following code snippet.
#include
class sample
{
static sample *ptr ;
private:
sample( )
{
}
public:
static sample* create( )
{
if ( ptr == NULL )
ptr = new sample ;
return ptr ;
}
} ;
sample *sample::ptr = NULL ;
void main( )
{
sample *a = sample::create( ) ;
sample *b = sample::create( ) ;
}
Here, the class sample contains a static data member ptr, which is a pointer to the object of same class. The constructor is private which avoids us from creating objects outside the class. A static member function called create( ) is used to create an object of the class. In this function the condition is checked whether or not ptr is NULL, if it is then an object is created dynamically and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the firststatement one object of sample gets created whereas on execution of second statement, b holds the address of the first object. Thus, whatever number of times you call create( ) function, only one object of sample class will be available.
11.
How do I write code to add functions, which would work as get and put properties of a class?
Ans: This is shown in following code.
#include
class sample
{
int data ;
public:
__declspec ( property ( put = fun1, get = fun2 ) )
int x ;
void fun1 ( int i )
{
if ( i < 0 )
data = 0 ;
else
data = i ;
}
int fun2( )
{
return data ;
}
} ;
void main( )
{
sample a ;
a.x = -99 ;
cout << a.x ;
}
Here, the function fun1( ) of class sample is used to set the given integer value into data, whereas fun2( ) returns the current value of data. To set these functions as properties of aclass we have given the statement as shown below:
__declspec ( property ( put = fun1, get = fun2 )) int x ;
As a result, the statement a.x = -99 ; would cause fun1( ) to get called to set the value in data. On the other hand, the laststatement would cause fun2( ) to get called to return the value of data.
-------------------------------------------------------------------------------------------------
12.
How do I write code to make an object work like a 2-D array?
Ans: Take a look at the following program.
#include
class emp
{
public :
int a[3][3] ;
emp( )
{
int c = 1 ;
for ( int i = 0 ; i <= 2 ; i++ )
{
for ( int j = 0 ; j <= 2 ; j++ )
{
a[i][j] = c ;
c++ ;
}
}
}
int* operator[] ( int i )
{
return a[i] ;
}
} ;
void main( )
{
emp e ;
cout << e[0][1] ;
}
The class emp has an overloaded operator [ ] function. It takes one argument an integer representing an array index and returns an int pointer. The statement cout << e[0][1] ; would get converted into a call to the overloaded [ ] function as e.operator[ ] ( 0 ). 0 would get collected in i. The function would return a[i] that represents the base address of the zeroeth row. Next the statement would get expanded as base address of zeroeth row[1] that can be further expanded as *( base address + 1 ). This gives us a value in zeroth row and first column.
13.
What are formatting flags in ios class?
Ans: The ios class contains formatting flags that help users to format the stream data. Formatting flags are a set of enum definitions. There are two types of formatting flags:
On/Off flags
Flags that work in-group
The On/Off flags are turned on using the setf( ) function and are turned off using the unsetf( ) function. To set the On/Off flags, the one argument setf( ) function is used. The flags working in groups are set through the two-argument setf( ) function. For example, to left justify a string we can set the flag as,
cout.setf ( ios::left ) ;
cout << "KICIT Nagpur" ;
To remove the left justification for subsequent output we can say,
cout.unsetf ( ios::left ) ;
The flags that can be set/unset include skipws, showbase, showpoint, uppercase, showpos, unitbuf and stdio. The flags that work in a group can have only one of these flags set at a time.
-------------------------------------------------------------------------------------------------
14.
What is the purpose of ios::basefield in the following statement?
cout.setf ( ios::hex, ios::basefield ) ;
Ans: This is an example of formatting flags that work in a group. There is a flag for each numbering system (base) like decimal, octal and hexadecimal. Collectively, these flags are referred to as basefield and are specified by ios::basefield flag. We can have only one of these flags on at a time. If we set the hex flag as setf ( ios::hex ) then we will set the hex bit but we won't clear the dec bit resulting in undefined behavior. The solution is to call setf( ) as setf ( ios::hex, ios::basefield ). This call first clears all the bits and then sets the hex bit.
-------------------------------------------------------------------------------------------------
15.
Can we get the value of ios format flags?
Ans: Yes! The ios::flags( ) member function gives the value format flags. This function takes no arguments and returns a long ( typedefed to fmtflags) that contains the current format flags.
-------------------------------------------------------------------------------------------------
16.
Is there any function that can skip certain number of characters present in the input stream?
Ans: Yes! This can be done using cin::ignore( ) function. The prototype of this function is as shown below:
istream& ignore ( int n = 1, int d =EOF ) ;
Sometimes it happens that some extra characters are left in the input stream while taking the input such as, the '\n' (Enter) character. This extra character is then passed to the next input and may pose problem.
To get rid of such extra characters the cin::ignore( ) function is used. This is equivalent to fflush ( stdin ) used in C language. This function ignores the first n characters (if present) in the input stream, stops if delimiter d is encountered.
-------------------------------------------------------------------------------------------------
17.
Write a program that implements a date class containing day, month and year as data members. Implement assignment operator and copy constructor in this class.
Ans: This is shown in following program:
#include
class date
{
private :
int day ;
int month ;
int year ;
public :
date ( int d = 0, int m = 0, int y = 0 )
{
day = d ;
month = m ;
year = y ;
}
// copy constructor
date ( date &d )
{
day = d.day ;
month = d.month ;
year = d.year ;
}
// an overloaded assignment operator
date operator = ( date d )
{
day = d.day ;
month = d.month ;
year = d.year ;
return d ;
}
void display( )
{
cout << day << "/" << month << "/" << year ;
}
} ;
void main( )
{
date d1 ( 25, 9, 1979 ) ;
date d2 = d1 ;
date d3 ;
d3 = d2 ;
d3.display( ) ;
}
18.
When should I use unitbuf flag?
Ans: The unit buffering (unitbuf) flag should be turned on when we want to ensure that each character is output as soon as it is inserted into an output stream. The same can be done using unbuffered output but unit buffering provides a better performance than the unbuffered output.
-------------------------------------------------------------------------------------------------
19.
What are manipulators?
Ans: Manipulators are the instructions to the output stream to modify the output in various ways. The manipulators provide a clean and easy way for formatted output in comparison to the formatting flags of the ios class. When manipulators are used, the formatting instructions are inserted directly into the stream. Manipulators are of two types, those that take an argument and those that don't.
-------------------------------------------------------------------------------------------------
20.
What is the difference between the manipulator and setf( ) function?
Ans: The difference between the manipulator and setf( ) function are as follows:
The setf( ) function is used to set the flags of the ios but manipulators directly insert the formatting instructions into the stream. We can create user-defined manipulators but setf( ) function uses data members of ios class only. The flags put on through the setf( ) function can be put off through unsetf( ) function. Such flexibility is not available with manipulators.
-------------------------------------------------------------------------------------------------
21.
How do I get the current position of the file pointer?
Ans: We can get the current position of the file pointer by using the tellp( ) member function of ostream class or tellg( ) member function of istream class. These functions return (in bytes) positions of put pointer and get pointer respectively.
-------------------------------------------------------------------------------------------------
22.
What are put and get pointers?
Ans: These are the long integers associated with the streams. The value present in the put pointer specifies the byte number in the file from where next write would take place in the file. The get pointer specifies the byte number in the file from where the next reading should take place.
-------------------------------------------------------------------------------------------------
23.
What do the nocreate and noreplace flag ensure when they are used for opening a file?
Ans: nocreate and noreplace are file-opening modes. A bit in the ios class defines these modes. The flag nocreate ensures that the file must exist before opening it. On the other hand the flag noreplace ensures that while opening a file for output it does not get overwritten with new one unless ate or app is set. When the app flag is set then whatever we write gets appended to the existing file. When ate flag is set we can start reading or writing at the end of existing file.
-------------------------------------------------------------------------------------------------
24.
What is the limitation of cin while taking input for character array?
Ans: To understand this consider following statements,
char str[5] ;
cin >> str ;
While entering the value for str if we enter more than 5 characters then there is no provision in cin to check the array bounds. If the array overflows, it may be dangerous. This can be avoided by using get( ) function. For example, consider following statement,
cin.get ( str, 5 ) ;
On executing this statement if we enter more than 5 characters, then get( ) takes only first five characters and ignores rest of the characters. Some more variations of get( ) are available, such as shown below:
get ( ch ) - Extracts one character only
get ( str, n ) - Extracts up to n characters into str
get ( str, DELIM ) - Extracts characters into array str until specified delimiter (such as '\n'). Leaves delimiting character in stream.
get ( str, n, DELIM ) - Extracts characters into array str until n characters or DELIM character, leaving delimiting character in stream.
-------------------------------------------------------------------------------------------------
25.
What is the purpose of istream class?
Ans: The istream class performs activities specific to input. It is derived from the ios class. The most commonly used member function of this class is the overloaded >> operator which can extract values of all basic types. We can extract even a string using this operator.
-------------------------------------------------------------------------------------------------
26.
Would the following code work?
#include
void main( )
{
ostream o ;
o << "Dream. Then make it happen!" ;
}
Ans: No! This is because we cannot create an object of the ostream class since its constructor and copy constructor are declared private.
27.
Can we use this pointer inside static member function?
Ans: No! The this pointer cannot be used inside a static member function. This is because a static member function is never called through an object.
-------------------------------------------------------------------------------------------------
28.
What is strstream?
Ans: strstream is a type of input/output stream that works with the memory. It allows using section of the memory as a stream object. These streams provide the classes that can be used for storing the stream of bytes into memory. For example, we can store integers, floats and strings as a stream of bytes. There are several classes that implement this in-memory formatting. The class ostrstream derived from ostream is used when output is to be sent to memory, the class istrstream derived from istream is used when input is taken from memory and strstream class derived from iostream is used for
memory objects that do both input and output.
-------------------------------------------------------------------------------------------------
29.
Ans: When we want to retrieve the streams of bytes from memory we can use istrestream. The following example shows the use of istrstream class.
#include
void main( )
{
int age ;
float salary ;
char name[50] ;
char str[] = "22 12004.50 K. Vishwanatth" ;
istrstream s ( str ) ;
s >> age >> salary >> name ;
cout << age << endl << salary << endl << name ;
cout << endl << s.rdbuf( ) ;
}
Here, s is the object of the class istrstream. When we are creating the object s, the constructor of istrstream gets called that receives a pointer to the zero terminated character array str. The statement s >> age >> salary >> name ; extracts the age, salary and the name from the istrstream object s. However, while extracting the name, only the first word of name gets extracted. The balance is extracted using rdbuf( ).
-------------------------------------------------------------------------------------------------
30.
When the constructor of a base class
calls a virtual function, why doesn't the override function of the derived class gets called?
Ans: While building an object of a derived class first the constructor of the base class and then the constructor of the derived class gets called. The object is said an immature object at the stage when the constructor of base class is called. This object will be called a matured object after the execution of the constructor of the derived class. Thus, if we call a virtual function when an object is still immature, obviously, the virtual function of the base class would get called. This is illustrated in the following example.
#include
class base
{
protected :
int i ;
public :
base ( int ii = 0 )
{
i = ii ;
show( ) ;
}
virtual void show( )
{
cout << "base's show( )" << endl ;
}
} ;
class derived : public base
{
private :
int j ;
public :
derived ( int ii, int jj = 0 ) : base ( ii )
{
j = jj ;
show( ) ;
}
void show( )
{
cout << "derived's show( )" << endl ;
}
} ;
void main( )
{
derived dobj ( 20, 5 ) ;
}
The output of this program would be:
base's show( )
derived's show( )
31.
Can I have a reference as a data member of a class? If yes, then how do I initialise it?
Ans: Yes, we can have a reference as a data member of a class. A reference as a data member of a class is initialised in the initialisation list of the constructor. This is shown in following program.
#include
class sample
{
private :
int& i ;
public :
sample ( int& ii ) : i ( ii )
{
}
void show( )
{
cout << i << endl ;
}
} ;
void main( )
{
int j = 10 ;
sample s ( j ) ;
s.show( ) ;
}
Here, i refers to a variable j allocated on the stack. A point to note here is that we cannot bind a reference to an object passed to the constructor as a value. If we do so, then the reference i would refer to the function parameter (i.e. parameter ii in the constructor), which would disappear as soon as the function returns, thereby creating a situation of dangling reference.
-------------------------------------------------------------------------------------------------
32.
Why does the following code fail?
#include
class sample
{
private :
char *str ;
public :
sample ( char *s )
{
strcpy ( str, s ) ;
}
~sample( )
{
delete str ;
}
} ;
void main( )
{
sample s1 ( "abc" ) ;
}
Ans: Here, through the destructor we are trying to deal locate memory, which has been allocated statically. To remove an exception, add following statement to the constructor.
sample ( char *s )
{
str = new char[strlen(s) + 1] ;
strcpy ( str, s ) ;
}
Here, first we have allocated memory of required size, which then would get deal located through the destructor.
-------------------------------------------------------------------------------------------------
33.
assert( ) macro...
We can use a macro called assert( ) to test for conditions that should not occur in a code. This macro expands to an if statement. If test evaluates to 0, assert prints an error message and calls abort to abort the program.
#include
#include
void main( )
{
int i ;
cout << "\nEnter an integer: " ;
cin >> i ;
assert ( i >= 0 ) ;
cout << i << endl ;
}
34.
Why it is unsafe to deal locate the memory using free( ) if it has been allocated using new?
Ans: This can be explained with the following example:
#include
class sample
{
int *p ;
public :
sample( )
{
p = new int ;
}
~sample( )
{
delete p ;
}
} ;
void main( )
{
sample *s1 = new sample ;
free ( s1 ) ;
sample *s2 = ( sample * ) malloc ( sizeof ( sample
) ) ;
delete s2 ;
}
The new operator allocates memory and calls the constructor. In the constructor we have allocated memory on heap, which is pointed to by p. If we release the object using the free( ) function the object would die but the memory allocated in the constructor would leak. This is because free( ) being a C library function does not call the destructor where we have deal located the memory.
As against this, if we allocate memory by calling malloc( ) the constructor would not get called. Hence p holds a garbage address. Now if the memory is deal located using delete, the destructor would get called where we have tried to release the memory pointed to by p. Since p contains garbage this may result in a runtime error.
-------------------------------------------------------------------------------------------------
35.
Can we distribute function templates and class templates in object libraries?
Ans: No! We can compile a function template or a class template into object code (.obj file). The code that contains a call to the function template or the code that creates an object from a class template can get compiled. This is because the compiler merely checks whether the call matches the declaration (in case of function template) and whether the object definition matches class declaration (in case of class template). Since the function template and the class template definitions are not found, the compiler leaves it to the linker to restore this. However, during linking, linker doesn't find the matching definitions for the function call or a matching definition for object creation. In short the expanded versions of templates are not found in
the object library. Hence the linker reports error.
-------------------------------------------------------------------------------------------------
36.
What is the difference between an inspector and a mutator ?
Ans: An inspector is a member function that returns information about an object's state (information stored in object's data members) without changing the object's state. A mutator is a member function that changes the state of an object. In the class Stack given below we have defined a mutator and an inspector.
class Stack
{
public :
int pop( ) ;
int getcount( ) ;
}
In the above example, the function pop( ) removes top element of stack thereby changing the state of an object. So, the function pop( ) is a mutator. The function getcount( ) is an inspector because it simply counts the number of elements in the stack without changing the stack.
37.
Namespaces:
The C++ language provides a single global namespace. This can cause problems with global name clashes. For instance, consider these two C++ header files:
// file1.h
float f ( float, int ) ;
class sample { ... } ;
// file2.h
class sample { ... } ;
With these definitions, it is impossible to use both header files in a single program; the sample classes will clash.A namespace is a declarative region that attaches an additional identifier to any names declared inside it. The additional identifier thus avoids the possibility that a name will conflict with names declared elsewhere in the program. It is possible to use the same name in separate namespaces without conflict even if the names appear in the same translation unit. As long as they appear in separate namespaces, each name will be unique because of the addition of the namespace identifier. For example:
// file1.h
namespace file1
{
float f ( float, int ) ;
class sample { ... } ;
}
// file2.h
namespace file2
{
class sample { ... } ;
}
Now the class names will not clash because they become file1::sample and file2::sample, respectively.
-------------------------------------------------------------------------------------------------
38.
What would be the output of the following program?
#include
class user
{
int i ;
float f ;
char c ;
public :
void displaydata( )
{
cout << endl << i << endl << f << endl << c ;
}
} ;
void main( )
{
cout << sizeof ( user ) ;
user u1 ;
cout << endl << sizeof ( u1 ) ;
u1.displaydata( ) ;
}
Ans: The output of this program would be,
9 or 7
9 or 7
Garbage
Garbage
Garbage
Since the user class contains three elements, int, float and char its size would be 9 bytes (int-4, float-4, char-1) under Windows and 7 bytes (int-2, float-4, char-1) under DOS. Second output is again the same because u1 is an object of the class user. Finally three garbage values are printed out because i, f and c are not initialized anywhere in the program.
Note that if you run this program you may not get the answer shown here. This is because packing is done for an object in memory to increase the access efficiency. For example, under DOS, the object would be aligned on a 2-byte boundary. As a result, the size of the object would be reported as 6 bytes. Unlike this, Windows being a 32-bit OS the object would be aligned on a 4-byte boundary. Hence the size of the object would be reported as 12 bytes. To force the alignment on a 1-byte boundary, write the following statement before the class declaration.
#pragma pack ( 1 )
-------------------------------------------------------------------------------------------------
39.
Write a program that will convert an integer pointer to an integer and vice-versa.
Ans: The following program demonstrates this.
#include
void main( )
{
int i = 65000 ;
int *iptr = reinterpret_cast ( i ) ;
cout << endl << iptr ;
iptr++ ;
cout << endl << iptr ;
i = reinterpret_cast ( iptr ) ;
cout << endl << i ;
i++ ;
cout << endl << i ;
}
40.
What is a const_cast?
Ans. The const_cast is used to convert a const to a non-const. This is shown in the following
program:
#include
void main( )
{
const int a = 0 ;
int *ptr = ( int * ) &a ; //one way
ptr = const_cast_ ( &a ) ; //better way
}
Here, the address of the const variable a is assigned to the pointer to a non-const variable. The const_cast is also used when we want to change the data members of a class inside the const member functions. The following code snippet shows this:
class sample
{
private:
int data;
public:
void func( ) const
{
(const_cast (this))->data = 70 ;
}
} ;
-------------------------------------------------------------------------------------------------
41.
What is forward referencing and when should it be used?
Ans: Forward referencing is generally required when we make a class or a function as a friend.
Consider following program:
class test
{
public:
friend void fun ( sample, test ) ;
} ;
class sample
{
public:
friend void fun ( sample, test ) ;
} ;
void fun ( sample s, test t )
{
// code
}
void main( )
{
sample s ;
test t ;
fun ( s, t ) ;
}
On compiling this program it gives error on the following statement of test class. It gives an error that sample is undeclared identifier. friend void fun ( sample, test ) ;
This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of the class sample before the definition of class test. The following statement is the forward reference of class sample.
class sample ;
-------------------------------------------------------------------------------------------------
42.
How would you give an alternate name to a namespace?
Ans: An alternate name given to namespace is called a namespace-alias. namespace-alias is generally used to save the typing effort when the names of namespaces are very long or complex. The following syntax is used to give an alias to a namespace.
namespace myname = my_old_very_long_name ;
-------------------------------------------------------------------------------------------------
43.
Using a smart pointer can we iterate through a container?
Ans: Yes. A container is a collection of elements or objects. It helps to properly organize and store the data. Stacks, linked lists, arrays are examples of containers. Following program shows how to iterate through a container using a smart pointer.
#include
class smartpointer
{
private :
int *p ; // ordinary pointer
public :
smartpointer ( int n )
{
p = new int [ n ] ;
int *t = p ;
for ( int i = 0 ; i <= 9 ; i++ )
*t++ = i * i ;
}
int* operator ++ ( int )
{
return p++ ;
}
int operator * ( )
{
return *p ;
}
} ;
void main( )
{
smartpointer sp ( 10 ) ;
for ( int i = 0 ; i <= 9 ; i++ )
cout << *sp++ << endl ;
}
Here, sp is a smart pointer. When we say *sp, the operator * ( ) function gets called. It returns the integer being pointed to by p. When we say sp++ the operator ++ ( ) function gets called. It increments p to point to
the next element in the array and then returns the address of this new location.
44.
Can objects read and write themselves?
Ans: Yes! This can be explained with the help of following example:
#include
#include
class employee
{
private :
char name [ 20 ] ;
int age ;
float salary ;
public :
void getdata( )
{
cout << "Enter name, age and salary of employee : " ;
cin >> name >> age >> salary ;
}
void store( )
{
ofstream file ;
file.open ( "EMPLOYEE.DAT", ios::app | ios::binary ) ;
file.write ( ( char * ) this, sizeof ( *this ) ) ;
file.close( ) ;
}
void retrieve ( int n )
{
ifstream file ;
file.open ( "EMPLOYEE.DAT", ios::binary ) ;
file.seekg ( n * sizeof ( employee ) ) ;
file.read ( ( char * ) this, sizeof ( *this ) ) ;
file.close( ) ;
}
void show( )
{
cout << "Name : " << name
<< endl << "Age : " << age
<< endl << "Salary :" << salary << endl ;
}
} ;
void main( )
{
employee e [ 5 ] ;
for ( int i = 0 ; i <= 4 ; i++ )
{
e [ i ].getdata( ) ;
e [ i ].store( ) ;
}
for ( i = 0 ; i <= 4 ; i++ )
{
e [ i ].retrieve ( i ) ;
e [ i ].show( ) ;
}
}
Here, employee is the class whose objects can write and read themselves. The getdata( ) function has been used to get the data of employee and store it in the data members name, age and salary. The store( ) function is used to write an object to the file. In this function a file has been opened in append mode and each time data of current object has been stored after the last record (if any) in the file.Function retrieve( ) is used to get the data of a particular employee from the file. This retrieved data has been stored in the data members name, age and salary. Here this has been used to store data since it contains the address of the current object. Thefunction show( ) has been used to display the data of employee.
-------------------------------------------------------------------------------------------------
45.
Why is it necessary to use a reference in the argument to the copy constructor?
Ans : If we pass the copy constructor the argument by value, its copy would get constructed using the copy constructor. This means the copy constructor would call itself to make this copy. This process would go on and on until the compiler runs out of memory. This can be explained with the help of following example:
class sample
{
int i ;
public :
sample ( sample p )
{
i = p.i ;
}
} ;
void main( )
{
sample s ;
sample s1 ( s ) ;
}
While executing the statement sample s1 ( s ), the copy constructor would get called. As the copy construct here accepts a value, the value of s would be passed which would get collected in p. We can think of this statement as sample p = s. Here p is getting created and initialized. Means again the copyconstructor would get called. This would result into recursive calls. Hence we must use a reference as an argument in a copy constructor.
46.
Virtual Multiple Inheritance:
A class b is defined having member variable i. Suppose two classes d1 and d2 are derived from class b and a class multiple is derived from both d1 and d2. If variable i is accessed from a memberfunction of multiple then it gives error as 'member is ambiguous'. To avoid this error derive classes d1 and d2 with modifier virtual as shown in the following program.
#include
class b
{
public :
int i ;
public :
fun( )
{
i = 0 ;
}
} ;
class d1 : virtual public b
{
public :
fun( )
{
i = 1 ;
}
} ;
class d2 : virtual public b
{
public :
fun( )
{
i = 2 ;
}
} ;
class multiple : public d1, public d2
{
public :
fun( )
{
i = 10 ;
}
} ;
void main( )
{
multiple d ;
d.fun( ) ;
cout << d.i ;
}
-------------------------------------------------------------------------------------------------
47.
Can we use this pointer in a class specific, operator-overloading function for new operator?
Ans: No! The this pointer is never passed to the overloaded operator new() member function because this function gets called before the object is created. Hence there is no question of the this pointer getting passed to operator new( ).
-------------------------------------------------------------------------------------------------
48.
Can we allocate memory dynamically for a reference?
Ans: No! It is not possible to allocate memory dynamically for a reference. This is because, when we create a reference, it gets tied with some variable of its type. Now, if we try to allocate memory dynamically for a reference, it is not possible to mention that to which variable the reference would get tied.
49.
When should I overload new operator on a global basis or a class basis?
Ans: We overload operator new in our program, when we want to initialize a data item or a class object at the same place where it has been allocated memory. The following example shows how to overload newoperator on global basis.
#include
#include
void * operator new ( size_t s )
{
void *q = malloc ( s ) ;
return q ;
}
void main( )
{
int *p = new int ;
*p = 25 ;
cout << *p ;
}
When the operator new is overloaded on global basis it becomes impossible to initialize the data members of a class as different classes may have different types of data members. The following example shows how to
overload new operator on class-by-class basis.
#include
#include
class sample
{
int i ;
public :
void* operator new ( size_t s, int ii )
{
sample *q = ( sample * ) malloc ( s ) ;
q -> i = ii ;
return q ;
}
} ;
class sample1
{
float f ;
public :
void* operator new ( size_t s, float ff )
{
sample1 *q = ( sample1 * ) malloc ( s ) ;
q -> f = ff ;
return q ;
}
} ;
void main( )
{
sample *s = new ( 7 ) sample ;
sample1 *s1 = new ( 5.6f ) sample1 ;
}
Overloading the operator new on class-by-class basis makes it possible to allocate memory for an object and initialize its data members at the same place.
-------------------------------------------------------------------------------------------------
50.
How would you define a pointer to a data member of the type pointer to pointer?
Ans: The following program demonstrates this...
#include
class sample
{
public :
sample ( int **pp )
{
p = pp ;
}
int **p ;
} ;
int **sample::*ptr = &sample::p ;
void main( )
{
int i = 9 ;
int *pi = &i ;
sample s ( π ) ;
cout << ** ( s.*ptr ) ;
}
Here, ptr is the pointer to data member p of class sample, which in turn is a pointer pointing to an int.
-------------------------------------------------------------------------------------------------
51.
How do I write a code to catch multiple types of exceptions in one single catch block?
Ans: The following program demonstrates the use of a single catch block to catch multiple exceptions.
#include
class test
{
} ;
class sample
{
public :
void fun1( )
{
throw 99 ;
}
void fun2( )
{
throw 3.14f ;
}
void fun3( )
{
throw "error" ;
}
void fun4( )
{
throw test( ) ;
}
} ;
void main( )
{
try
{
sample s ;
s.fun4( ) ;
s.fun1( ) ;
s.fun2( ) ;
s.fun3( ) ;
}
catch ( ... )
{
cout << "strange" ;
}
}
Here, different types of exceptions are thrown by the member functions of the class sample. While catching the exception instead of four different catch blocks we can as well define one single catch block. Note the syntax for defining the catch block, where we have used three dots (…) in the formal parameter list. This indicates that any thrown exception should get caught in the same catch block. When the exception is thrown from the fun4( ) control reaches the catch block, ignoring the rest of the calls.
52.
Can we return an error value from the constructor of a class?
Ans: No. We cannot return any error value from the constructor, as the constructor doesn't have any return type. However, by throwing an exception we can pass value to catch block. This is shown in the following example:
#include
class sample
{
public :
sample ( int i )
{
if ( i == 0 )
throw "error" ;
}
} ;
void main( )
{
try
{
sample s ( 0 ) ;
}
catch ( char * str )
{
cout << str ;
}
}
In this program, the statement throw "error" ; would throw an exception when an object s of the class sample would get created. The catch block would collect the string error.
-------------------------------------------------------------------------------------------------
53.
How do I define the member function of a template class, which has to be defined outside the template class. The function receives an object of its own class as a parameter and returns the value of the same type.
Ans: The following example shows how we can define such a function.
sample sample::fun ( sample s )
{
// code
}
Here, the first sample indicates the return type of the function and the next sample is used for the scope of function.
-------------------------------------------------------------------------------------------------
54.
How name mangling can be prevented?
Ans: To avoid name mangling the function should be declared with an extern "C" attribute. Functions declared as extern "C" are treated as C-style functions. Hence the compiler does not mangle them. The following code snippet shows how to declare such a function.
#include
extern "C" void display( )
{
cout << "See the effect of C in C++ " ;
}
void main( )
{
display( ) ;
}
-------------------------------------------------------------------------------------------------
55.
Can we allocate memory dynamically for a reference?
Ans: No, it is not possible to allocate memory dynamically for a reference. A reference is initialized at the time of creation. Trying to allocate memory dynamically for a reference creates a problem in initializing it. Thus, the compiler does not allow us to dynamically allocate the memory for references.
-------------------------------------------------------------------------------------------------
56.
What is RTTI?
Ans: RTTI stands for 'Run Time Type Information'. We use virtual function mechanism where we can call derived class's member functions using base class's pointer. However, many times we wish to know the exact type of the object. We can know the type of the object using RTTI. A function that returns the type of the object is known as RTTI functions. C++ supports two ways to obtain information about the object's class at run time, they are typeid( ) operator and dynamic_cast operator.
57.
What is Data Conversion?
Ans: Assignments between types whether they are basic or user-defined, are handled by the compiler. If the variables are of different basic types compiler calls a special routine to convert the value. But if we want to convert between user-defined data type and basic types we have to write conversion routine ourselves. A conversion routine to convert user-defined data type string to integer is shown below:
class string
{
private :
char str[20] ;
public :
string( )
{
}
string ( char *s )
{
strcpy ( str, s ) ;
}
operator int( )
{
return 123 ; // Write logic to convert string to integer
}
} ;
main( )
{
string s2 = "123" ;
int i1 = int ( s2 ) ;
cout << endl << i1 ;
}
-------------------------------------------------------------------------------------------------
58.
How to obtain type information using typeid( ) operator?
Ans: typeid( ) operator takes an object, a reference or a pointer and returns its type. Following program shows how to use the typeid( ) operator.
#include
#include
class Base
{
public :
virtual void show( )
{
}
};
class Der1 : public Base
{
} ;
void main( )
{
Base *b1 ;
cout << endl << typeid ( b1 ).name( ) ;
Der1 d1 ;
b1 = &d1 ;
cout << endl << typeid ( *b1 ).name( ) ;
cout << endl << typeid ( 12 ).name( ) << endl << typeid ( 12.5 ).name( ) ;
}
The output of this program will be
Base*
Der1
int
double
RTTI operators must be used for polymorphic class (class having virtual function) only. For non-polymorphic class static type information is returned.
-------------------------------------------------------------------------------------------------
59.
How to use RTTI with class templates?
Ans: Templates can generate different classes. We may wish to get the type of class, which we are working in. The following program shows how to use RTTI operator typeid( ) with class template.
#include
#include
template
class base
{
public :
base( )
{
cout << typeid ( *this ).name( ) << "Constructor" << endl ;
}
T add ( T a, T b )
{
return a + b ;
}
~base( )
{
cout << typeid ( *this ).name( ) << "Destructor" << endl ;
}
} ;
void main( )
{
base b1 ;
cout << b1.add ( 10, 20 ) << endl ;
base b2 ;
cout << b2.add ( 5.5, 10.5 ) << endl ;
}
60.
We can use following C++ operators for typecasting.static_cast is used for castless conversions, narrowing conversions, conversion from void* and implicit type conversions. const_cast is used to convert a const to a non-const. reinterpret_cast is used to assign one kind of pointer to another.
-------------------------------------------------------------------------------------------------
61.
What will be the output of the following program?
#include
class A
{
public :
A( )
{
cout << "Reached in Constructor\n" ;
}
} ;
void main( )
{
A a( ) ;
A b ;
}
Output : Reached in Constructor
Constructor gets called only once when the object b is created. When the statement A a( ) ; gets executed constructor does not get called. This is because compiler takes this statement as a prototype declaration of function a( ) that returns an object of class A. However, if we pass arguments like
A a ( 10 ) ;
Compiler would search for one argument constructor and if not found would flash an error.
-------------------------------------------------------------------------------------------------
62.
What is a container?
Ans: A container is an object that holds other objects. Various collection classes like List, Hash Table, AbstractArray, etc. are the examples of containers. We can use the classes to hold objects of any derived classes. The containers provide various methods using which we can get the number of objects stored in the container and iterate through the objects stored in it.
-------------------------------------------------------------------------------------------------
63.
Function template overloading
One can declare several function templates with the same name and even declare a combination of function templates and ordinary functions with the same name. When an overloaded function is called, overload resolution is necessary to find the right function or template function to invoke.
For example:
template < class T > T sqrt ( T ) ;
template < class T > complex < T > sqrt ( complex < T > ) ;double sqrt (
double ) ;
void f ( complex < double > z )
{
sqrt ( 2 ) ; // sqrt < int > ( int )
sqrt ( 2.0 ) ; // sqrt ( double )
sqrt ( z ) ; // sqrt < complex < double > ( complex < double > )
}
In the same way that a template function is a generalization of the notion of a function, the rules for resolution in the presence of function templates are generalizations of the function overload resolution rules. Basically, for each template we find the specialization that is best for the set of function arguments. Then we apply the usual function overload resolution rules to these specializations and all ordinary functions.
• First
• Prev
Can we declare a static function as virtual?
Ans: No. The virtual function mechanism is used on the specific object that determines which virtual function to call. Since the static functions are not any way related to objects, they cannot be declared as virtual.
-------------------------------------------------------------------------------------------------
2.
Can user-defined object be declared as static data member of another class?
Ans: Yes. The following code shows how to initialize a user-defined object.
#include
class test
{
int i ;
public :
test ( int ii = 0 )
{
i = ii ;
}
} ;
class sample
{
static test s ;
} ;
test sample::s ( 26 ) ;
Here we have initialized the object s by calling the one-argument constructor. We can use the same convention to initialize the object by calling multiple-argument constructor.
-------------------------------------------------------------------------------------------------
3.
What is forward referencing and when should it be used?
Ans: Consider the following program:
class test
{
public :
friend void fun ( sample, test ) ;
} ;
class sample
{
public :
friend void fun ( sample, test ) ;
} ;
void fun ( sample s, test t )
{
// code
}
void main( )
{
sample s ;
test t ;
fun ( s, t ) ;
}
This program would not compile. It gives an error that sample is undeclared identifier in the statement friend void fun ( sample, test ) ; of the class test. This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of theclass sample before the definition of class test. The following statement is the forward reference of class sample. Forward referencing is generally required when we make a class or a function as a friend.
-------------------------------------------------------------------------------------------------
4.
The istream_withassign class has been derived from the istream class and overloaded assignment operator has been added to it. The _withassign classes are much like their base classes except that they include overloaded assignment operators. Using these operators the objects of the _withassign classes can be copied. The istream, ostream, and iostream classes are made uncopyable by making their overloaded copy constructor and assignment operators private.
-------------------------------------------------------------------------------------------------
5.
How do I write my own zero-argument manipulator that should work same as hex?
Ans: This is shown in following program.
#include
ostream& myhex ( ostream &o )
{
o.setf ( ios::hex) ;
return o ;
}
void main( )
{
cout << endl << myhex << 2000 ;
}
-------------------------------------------------------------------------------------------------
6.
We all know that a const variable needs to be initialized at the time of declaration. Then how come the program given below runs properly even when we have not initialized p?
#include
void main( )
{
const char *p ;
p = "A const pointer" ;
cout << p ;
}
Ans: The output of the above program is 'A const pointer'. This is because in this program p is declared as 'const char*' which means that value stored at p will be constant and not p and so the program works properly
7.
How do I refer to a name of class or function that is defined within a namespace?
Ans: There are two ways in which we can refer to a name of class or function that is defined within a namespace: Using scope resolution operator through the using keyword. This is shown in following example:
namespace name1
{
class sample1
{
// code
} ;
}
namespace name2
{
class sample2
{
// code
} ;
}
using namespace name2 ;
void main( )
{
name1::sample1 s1 ;
sample2 s2 ;
}
Here, class sample1 is referred using the scope resolution operator. On the other hand we can directly refer to class sample2 because of the statement using namespace name2 ; the using keyword declares all the names in the namespace to be in the current scope. So we can use the names without any qualifiers.
-------------------------------------------------------------------------------------------------
8.
While overloading a binary operator can we provide default values?
Ans: No!. This is because even if we provide the default arguments to the parameters of the overloadedoperator function we would end up using the binary operator incorrectly. This is explained in the following example:
sample operator + ( sample a, sample b = sample (2, 3.5f ) )
{
}
void main( )
{
sample s1, s2, s3 ;
s3 = s1 + ; // error
}
-------------------------------------------------------------------------------------------------
9.
How do I carry out conversion of one object of user-defined type to another?
Ans: To perform conversion from one user-defined type to another we need to provide conversion function. Following program demonstrates how to provide such conversion function.
class circle
{
private :
int radius ;
public:
circle ( int r = 0 )
{
radius = r ;
}
} ;
class rectangle
{
private :
int length, breadth ;
public :
rectangle( int l, int b )
{
length = l ;
breadth = b ;
}
operator circle( )
{
return circle ( length ) ;
}
} ;
void main( )
{
rectangle r ( 20, 10 ) ;
circle c;
c = r ;
}
Here, when the statement c = r ; is executed the compiler searches for an overloaded assignment operator in the class circle which accepts the object of type rectangle. Since there is no such overloaded assignment operator, the conversion operator function that converts the rectangle object to the circle object is searched in the rectangle class. We have provided such a conversion function in the rectangle class. This conversion operator function returns a circle object. By default conversion operators have the name and return type same as the object type to which it converts to. Here the type of the object is circle and hence the name of the operator function as well as the return type is circle.
-------------------------------------------------------------------------------------------------
10.
How do I write code that allows to create only one instance of a class?
Ans: This is shown in following code snippet.
#include
class sample
{
static sample *ptr ;
private:
sample( )
{
}
public:
static sample* create( )
{
if ( ptr == NULL )
ptr = new sample ;
return ptr ;
}
} ;
sample *sample::ptr = NULL ;
void main( )
{
sample *a = sample::create( ) ;
sample *b = sample::create( ) ;
}
Here, the class sample contains a static data member ptr, which is a pointer to the object of same class. The constructor is private which avoids us from creating objects outside the class. A static member function called create( ) is used to create an object of the class. In this function the condition is checked whether or not ptr is NULL, if it is then an object is created dynamically and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the firststatement one object of sample gets created whereas on execution of second statement, b holds the address of the first object. Thus, whatever number of times you call create( ) function, only one object of sample class will be available.
11.
How do I write code to add functions, which would work as get and put properties of a class?
Ans: This is shown in following code.
#include
class sample
{
int data ;
public:
__declspec ( property ( put = fun1, get = fun2 ) )
int x ;
void fun1 ( int i )
{
if ( i < 0 )
data = 0 ;
else
data = i ;
}
int fun2( )
{
return data ;
}
} ;
void main( )
{
sample a ;
a.x = -99 ;
cout << a.x ;
}
Here, the function fun1( ) of class sample is used to set the given integer value into data, whereas fun2( ) returns the current value of data. To set these functions as properties of aclass we have given the statement as shown below:
__declspec ( property ( put = fun1, get = fun2 )) int x ;
As a result, the statement a.x = -99 ; would cause fun1( ) to get called to set the value in data. On the other hand, the laststatement would cause fun2( ) to get called to return the value of data.
-------------------------------------------------------------------------------------------------
12.
How do I write code to make an object work like a 2-D array?
Ans: Take a look at the following program.
#include
class emp
{
public :
int a[3][3] ;
emp( )
{
int c = 1 ;
for ( int i = 0 ; i <= 2 ; i++ )
{
for ( int j = 0 ; j <= 2 ; j++ )
{
a[i][j] = c ;
c++ ;
}
}
}
int* operator[] ( int i )
{
return a[i] ;
}
} ;
void main( )
{
emp e ;
cout << e[0][1] ;
}
The class emp has an overloaded operator [ ] function. It takes one argument an integer representing an array index and returns an int pointer. The statement cout << e[0][1] ; would get converted into a call to the overloaded [ ] function as e.operator[ ] ( 0 ). 0 would get collected in i. The function would return a[i] that represents the base address of the zeroeth row. Next the statement would get expanded as base address of zeroeth row[1] that can be further expanded as *( base address + 1 ). This gives us a value in zeroth row and first column.
13.
What are formatting flags in ios class?
Ans: The ios class contains formatting flags that help users to format the stream data. Formatting flags are a set of enum definitions. There are two types of formatting flags:
On/Off flags
Flags that work in-group
The On/Off flags are turned on using the setf( ) function and are turned off using the unsetf( ) function. To set the On/Off flags, the one argument setf( ) function is used. The flags working in groups are set through the two-argument setf( ) function. For example, to left justify a string we can set the flag as,
cout.setf ( ios::left ) ;
cout << "KICIT Nagpur" ;
To remove the left justification for subsequent output we can say,
cout.unsetf ( ios::left ) ;
The flags that can be set/unset include skipws, showbase, showpoint, uppercase, showpos, unitbuf and stdio. The flags that work in a group can have only one of these flags set at a time.
-------------------------------------------------------------------------------------------------
14.
What is the purpose of ios::basefield in the following statement?
cout.setf ( ios::hex, ios::basefield ) ;
Ans: This is an example of formatting flags that work in a group. There is a flag for each numbering system (base) like decimal, octal and hexadecimal. Collectively, these flags are referred to as basefield and are specified by ios::basefield flag. We can have only one of these flags on at a time. If we set the hex flag as setf ( ios::hex ) then we will set the hex bit but we won't clear the dec bit resulting in undefined behavior. The solution is to call setf( ) as setf ( ios::hex, ios::basefield ). This call first clears all the bits and then sets the hex bit.
-------------------------------------------------------------------------------------------------
15.
Can we get the value of ios format flags?
Ans: Yes! The ios::flags( ) member function gives the value format flags. This function takes no arguments and returns a long ( typedefed to fmtflags) that contains the current format flags.
-------------------------------------------------------------------------------------------------
16.
Is there any function that can skip certain number of characters present in the input stream?
Ans: Yes! This can be done using cin::ignore( ) function. The prototype of this function is as shown below:
istream& ignore ( int n = 1, int d =EOF ) ;
Sometimes it happens that some extra characters are left in the input stream while taking the input such as, the '\n' (Enter) character. This extra character is then passed to the next input and may pose problem.
To get rid of such extra characters the cin::ignore( ) function is used. This is equivalent to fflush ( stdin ) used in C language. This function ignores the first n characters (if present) in the input stream, stops if delimiter d is encountered.
-------------------------------------------------------------------------------------------------
17.
Write a program that implements a date class containing day, month and year as data members. Implement assignment operator and copy constructor in this class.
Ans: This is shown in following program:
#include
class date
{
private :
int day ;
int month ;
int year ;
public :
date ( int d = 0, int m = 0, int y = 0 )
{
day = d ;
month = m ;
year = y ;
}
// copy constructor
date ( date &d )
{
day = d.day ;
month = d.month ;
year = d.year ;
}
// an overloaded assignment operator
date operator = ( date d )
{
day = d.day ;
month = d.month ;
year = d.year ;
return d ;
}
void display( )
{
cout << day << "/" << month << "/" << year ;
}
} ;
void main( )
{
date d1 ( 25, 9, 1979 ) ;
date d2 = d1 ;
date d3 ;
d3 = d2 ;
d3.display( ) ;
}
18.
When should I use unitbuf flag?
Ans: The unit buffering (unitbuf) flag should be turned on when we want to ensure that each character is output as soon as it is inserted into an output stream. The same can be done using unbuffered output but unit buffering provides a better performance than the unbuffered output.
-------------------------------------------------------------------------------------------------
19.
What are manipulators?
Ans: Manipulators are the instructions to the output stream to modify the output in various ways. The manipulators provide a clean and easy way for formatted output in comparison to the formatting flags of the ios class. When manipulators are used, the formatting instructions are inserted directly into the stream. Manipulators are of two types, those that take an argument and those that don't.
-------------------------------------------------------------------------------------------------
20.
What is the difference between the manipulator and setf( ) function?
Ans: The difference between the manipulator and setf( ) function are as follows:
The setf( ) function is used to set the flags of the ios but manipulators directly insert the formatting instructions into the stream. We can create user-defined manipulators but setf( ) function uses data members of ios class only. The flags put on through the setf( ) function can be put off through unsetf( ) function. Such flexibility is not available with manipulators.
-------------------------------------------------------------------------------------------------
21.
How do I get the current position of the file pointer?
Ans: We can get the current position of the file pointer by using the tellp( ) member function of ostream class or tellg( ) member function of istream class. These functions return (in bytes) positions of put pointer and get pointer respectively.
-------------------------------------------------------------------------------------------------
22.
What are put and get pointers?
Ans: These are the long integers associated with the streams. The value present in the put pointer specifies the byte number in the file from where next write would take place in the file. The get pointer specifies the byte number in the file from where the next reading should take place.
-------------------------------------------------------------------------------------------------
23.
What do the nocreate and noreplace flag ensure when they are used for opening a file?
Ans: nocreate and noreplace are file-opening modes. A bit in the ios class defines these modes. The flag nocreate ensures that the file must exist before opening it. On the other hand the flag noreplace ensures that while opening a file for output it does not get overwritten with new one unless ate or app is set. When the app flag is set then whatever we write gets appended to the existing file. When ate flag is set we can start reading or writing at the end of existing file.
-------------------------------------------------------------------------------------------------
24.
What is the limitation of cin while taking input for character array?
Ans: To understand this consider following statements,
char str[5] ;
cin >> str ;
While entering the value for str if we enter more than 5 characters then there is no provision in cin to check the array bounds. If the array overflows, it may be dangerous. This can be avoided by using get( ) function. For example, consider following statement,
cin.get ( str, 5 ) ;
On executing this statement if we enter more than 5 characters, then get( ) takes only first five characters and ignores rest of the characters. Some more variations of get( ) are available, such as shown below:
get ( ch ) - Extracts one character only
get ( str, n ) - Extracts up to n characters into str
get ( str, DELIM ) - Extracts characters into array str until specified delimiter (such as '\n'). Leaves delimiting character in stream.
get ( str, n, DELIM ) - Extracts characters into array str until n characters or DELIM character, leaving delimiting character in stream.
-------------------------------------------------------------------------------------------------
25.
What is the purpose of istream class?
Ans: The istream class performs activities specific to input. It is derived from the ios class. The most commonly used member function of this class is the overloaded >> operator which can extract values of all basic types. We can extract even a string using this operator.
-------------------------------------------------------------------------------------------------
26.
Would the following code work?
#include
void main( )
{
ostream o ;
o << "Dream. Then make it happen!" ;
}
Ans: No! This is because we cannot create an object of the ostream class since its constructor and copy constructor are declared private.
27.
Can we use this pointer inside static member function?
Ans: No! The this pointer cannot be used inside a static member function. This is because a static member function is never called through an object.
-------------------------------------------------------------------------------------------------
28.
What is strstream?
Ans: strstream is a type of input/output stream that works with the memory. It allows using section of the memory as a stream object. These streams provide the classes that can be used for storing the stream of bytes into memory. For example, we can store integers, floats and strings as a stream of bytes. There are several classes that implement this in-memory formatting. The class ostrstream derived from ostream is used when output is to be sent to memory, the class istrstream derived from istream is used when input is taken from memory and strstream class derived from iostream is used for
memory objects that do both input and output.
-------------------------------------------------------------------------------------------------
29.
Ans: When we want to retrieve the streams of bytes from memory we can use istrestream. The following example shows the use of istrstream class.
#include
void main( )
{
int age ;
float salary ;
char name[50] ;
char str[] = "22 12004.50 K. Vishwanatth" ;
istrstream s ( str ) ;
s >> age >> salary >> name ;
cout << age << endl << salary << endl << name ;
cout << endl << s.rdbuf( ) ;
}
Here, s is the object of the class istrstream. When we are creating the object s, the constructor of istrstream gets called that receives a pointer to the zero terminated character array str. The statement s >> age >> salary >> name ; extracts the age, salary and the name from the istrstream object s. However, while extracting the name, only the first word of name gets extracted. The balance is extracted using rdbuf( ).
-------------------------------------------------------------------------------------------------
30.
When the constructor of a base class
calls a virtual function, why doesn't the override function of the derived class gets called?
Ans: While building an object of a derived class first the constructor of the base class and then the constructor of the derived class gets called. The object is said an immature object at the stage when the constructor of base class is called. This object will be called a matured object after the execution of the constructor of the derived class. Thus, if we call a virtual function when an object is still immature, obviously, the virtual function of the base class would get called. This is illustrated in the following example.
#include
class base
{
protected :
int i ;
public :
base ( int ii = 0 )
{
i = ii ;
show( ) ;
}
virtual void show( )
{
cout << "base's show( )" << endl ;
}
} ;
class derived : public base
{
private :
int j ;
public :
derived ( int ii, int jj = 0 ) : base ( ii )
{
j = jj ;
show( ) ;
}
void show( )
{
cout << "derived's show( )" << endl ;
}
} ;
void main( )
{
derived dobj ( 20, 5 ) ;
}
The output of this program would be:
base's show( )
derived's show( )
31.
Can I have a reference as a data member of a class? If yes, then how do I initialise it?
Ans: Yes, we can have a reference as a data member of a class. A reference as a data member of a class is initialised in the initialisation list of the constructor. This is shown in following program.
#include
class sample
{
private :
int& i ;
public :
sample ( int& ii ) : i ( ii )
{
}
void show( )
{
cout << i << endl ;
}
} ;
void main( )
{
int j = 10 ;
sample s ( j ) ;
s.show( ) ;
}
Here, i refers to a variable j allocated on the stack. A point to note here is that we cannot bind a reference to an object passed to the constructor as a value. If we do so, then the reference i would refer to the function parameter (i.e. parameter ii in the constructor), which would disappear as soon as the function returns, thereby creating a situation of dangling reference.
-------------------------------------------------------------------------------------------------
32.
Why does the following code fail?
#include
class sample
{
private :
char *str ;
public :
sample ( char *s )
{
strcpy ( str, s ) ;
}
~sample( )
{
delete str ;
}
} ;
void main( )
{
sample s1 ( "abc" ) ;
}
Ans: Here, through the destructor we are trying to deal locate memory, which has been allocated statically. To remove an exception, add following statement to the constructor.
sample ( char *s )
{
str = new char[strlen(s) + 1] ;
strcpy ( str, s ) ;
}
Here, first we have allocated memory of required size, which then would get deal located through the destructor.
-------------------------------------------------------------------------------------------------
33.
assert( ) macro...
We can use a macro called assert( ) to test for conditions that should not occur in a code. This macro expands to an if statement. If test evaluates to 0, assert prints an error message and calls abort to abort the program.
#include
#include
void main( )
{
int i ;
cout << "\nEnter an integer: " ;
cin >> i ;
assert ( i >= 0 ) ;
cout << i << endl ;
}
34.
Why it is unsafe to deal locate the memory using free( ) if it has been allocated using new?
Ans: This can be explained with the following example:
#include
class sample
{
int *p ;
public :
sample( )
{
p = new int ;
}
~sample( )
{
delete p ;
}
} ;
void main( )
{
sample *s1 = new sample ;
free ( s1 ) ;
sample *s2 = ( sample * ) malloc ( sizeof ( sample
) ) ;
delete s2 ;
}
The new operator allocates memory and calls the constructor. In the constructor we have allocated memory on heap, which is pointed to by p. If we release the object using the free( ) function the object would die but the memory allocated in the constructor would leak. This is because free( ) being a C library function does not call the destructor where we have deal located the memory.
As against this, if we allocate memory by calling malloc( ) the constructor would not get called. Hence p holds a garbage address. Now if the memory is deal located using delete, the destructor would get called where we have tried to release the memory pointed to by p. Since p contains garbage this may result in a runtime error.
-------------------------------------------------------------------------------------------------
35.
Can we distribute function templates and class templates in object libraries?
Ans: No! We can compile a function template or a class template into object code (.obj file). The code that contains a call to the function template or the code that creates an object from a class template can get compiled. This is because the compiler merely checks whether the call matches the declaration (in case of function template) and whether the object definition matches class declaration (in case of class template). Since the function template and the class template definitions are not found, the compiler leaves it to the linker to restore this. However, during linking, linker doesn't find the matching definitions for the function call or a matching definition for object creation. In short the expanded versions of templates are not found in
the object library. Hence the linker reports error.
-------------------------------------------------------------------------------------------------
36.
What is the difference between an inspector and a mutator ?
Ans: An inspector is a member function that returns information about an object's state (information stored in object's data members) without changing the object's state. A mutator is a member function that changes the state of an object. In the class Stack given below we have defined a mutator and an inspector.
class Stack
{
public :
int pop( ) ;
int getcount( ) ;
}
In the above example, the function pop( ) removes top element of stack thereby changing the state of an object. So, the function pop( ) is a mutator. The function getcount( ) is an inspector because it simply counts the number of elements in the stack without changing the stack.
37.
Namespaces:
The C++ language provides a single global namespace. This can cause problems with global name clashes. For instance, consider these two C++ header files:
// file1.h
float f ( float, int ) ;
class sample { ... } ;
// file2.h
class sample { ... } ;
With these definitions, it is impossible to use both header files in a single program; the sample classes will clash.A namespace is a declarative region that attaches an additional identifier to any names declared inside it. The additional identifier thus avoids the possibility that a name will conflict with names declared elsewhere in the program. It is possible to use the same name in separate namespaces without conflict even if the names appear in the same translation unit. As long as they appear in separate namespaces, each name will be unique because of the addition of the namespace identifier. For example:
// file1.h
namespace file1
{
float f ( float, int ) ;
class sample { ... } ;
}
// file2.h
namespace file2
{
class sample { ... } ;
}
Now the class names will not clash because they become file1::sample and file2::sample, respectively.
-------------------------------------------------------------------------------------------------
38.
What would be the output of the following program?
#include
class user
{
int i ;
float f ;
char c ;
public :
void displaydata( )
{
cout << endl << i << endl << f << endl << c ;
}
} ;
void main( )
{
cout << sizeof ( user ) ;
user u1 ;
cout << endl << sizeof ( u1 ) ;
u1.displaydata( ) ;
}
Ans: The output of this program would be,
9 or 7
9 or 7
Garbage
Garbage
Garbage
Since the user class contains three elements, int, float and char its size would be 9 bytes (int-4, float-4, char-1) under Windows and 7 bytes (int-2, float-4, char-1) under DOS. Second output is again the same because u1 is an object of the class user. Finally three garbage values are printed out because i, f and c are not initialized anywhere in the program.
Note that if you run this program you may not get the answer shown here. This is because packing is done for an object in memory to increase the access efficiency. For example, under DOS, the object would be aligned on a 2-byte boundary. As a result, the size of the object would be reported as 6 bytes. Unlike this, Windows being a 32-bit OS the object would be aligned on a 4-byte boundary. Hence the size of the object would be reported as 12 bytes. To force the alignment on a 1-byte boundary, write the following statement before the class declaration.
#pragma pack ( 1 )
-------------------------------------------------------------------------------------------------
39.
Write a program that will convert an integer pointer to an integer and vice-versa.
Ans: The following program demonstrates this.
#include
void main( )
{
int i = 65000 ;
int *iptr = reinterpret_cast ( i ) ;
cout << endl << iptr ;
iptr++ ;
cout << endl << iptr ;
i = reinterpret_cast ( iptr ) ;
cout << endl << i ;
i++ ;
cout << endl << i ;
}
40.
What is a const_cast?
Ans. The const_cast is used to convert a const to a non-const. This is shown in the following
program:
#include
void main( )
{
const int a = 0 ;
int *ptr = ( int * ) &a ; //one way
ptr = const_cast_ ( &a ) ; //better way
}
Here, the address of the const variable a is assigned to the pointer to a non-const variable. The const_cast is also used when we want to change the data members of a class inside the const member functions. The following code snippet shows this:
class sample
{
private:
int data;
public:
void func( ) const
{
(const_cast (this))->data = 70 ;
}
} ;
-------------------------------------------------------------------------------------------------
41.
What is forward referencing and when should it be used?
Ans: Forward referencing is generally required when we make a class or a function as a friend.
Consider following program:
class test
{
public:
friend void fun ( sample, test ) ;
} ;
class sample
{
public:
friend void fun ( sample, test ) ;
} ;
void fun ( sample s, test t )
{
// code
}
void main( )
{
sample s ;
test t ;
fun ( s, t ) ;
}
On compiling this program it gives error on the following statement of test class. It gives an error that sample is undeclared identifier. friend void fun ( sample, test ) ;
This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of the class sample before the definition of class test. The following statement is the forward reference of class sample.
class sample ;
-------------------------------------------------------------------------------------------------
42.
How would you give an alternate name to a namespace?
Ans: An alternate name given to namespace is called a namespace-alias. namespace-alias is generally used to save the typing effort when the names of namespaces are very long or complex. The following syntax is used to give an alias to a namespace.
namespace myname = my_old_very_long_name ;
-------------------------------------------------------------------------------------------------
43.
Using a smart pointer can we iterate through a container?
Ans: Yes. A container is a collection of elements or objects. It helps to properly organize and store the data. Stacks, linked lists, arrays are examples of containers. Following program shows how to iterate through a container using a smart pointer.
#include
class smartpointer
{
private :
int *p ; // ordinary pointer
public :
smartpointer ( int n )
{
p = new int [ n ] ;
int *t = p ;
for ( int i = 0 ; i <= 9 ; i++ )
*t++ = i * i ;
}
int* operator ++ ( int )
{
return p++ ;
}
int operator * ( )
{
return *p ;
}
} ;
void main( )
{
smartpointer sp ( 10 ) ;
for ( int i = 0 ; i <= 9 ; i++ )
cout << *sp++ << endl ;
}
Here, sp is a smart pointer. When we say *sp, the operator * ( ) function gets called. It returns the integer being pointed to by p. When we say sp++ the operator ++ ( ) function gets called. It increments p to point to
the next element in the array and then returns the address of this new location.
44.
Can objects read and write themselves?
Ans: Yes! This can be explained with the help of following example:
#include
#include
class employee
{
private :
char name [ 20 ] ;
int age ;
float salary ;
public :
void getdata( )
{
cout << "Enter name, age and salary of employee : " ;
cin >> name >> age >> salary ;
}
void store( )
{
ofstream file ;
file.open ( "EMPLOYEE.DAT", ios::app | ios::binary ) ;
file.write ( ( char * ) this, sizeof ( *this ) ) ;
file.close( ) ;
}
void retrieve ( int n )
{
ifstream file ;
file.open ( "EMPLOYEE.DAT", ios::binary ) ;
file.seekg ( n * sizeof ( employee ) ) ;
file.read ( ( char * ) this, sizeof ( *this ) ) ;
file.close( ) ;
}
void show( )
{
cout << "Name : " << name
<< endl << "Age : " << age
<< endl << "Salary :" << salary << endl ;
}
} ;
void main( )
{
employee e [ 5 ] ;
for ( int i = 0 ; i <= 4 ; i++ )
{
e [ i ].getdata( ) ;
e [ i ].store( ) ;
}
for ( i = 0 ; i <= 4 ; i++ )
{
e [ i ].retrieve ( i ) ;
e [ i ].show( ) ;
}
}
Here, employee is the class whose objects can write and read themselves. The getdata( ) function has been used to get the data of employee and store it in the data members name, age and salary. The store( ) function is used to write an object to the file. In this function a file has been opened in append mode and each time data of current object has been stored after the last record (if any) in the file.Function retrieve( ) is used to get the data of a particular employee from the file. This retrieved data has been stored in the data members name, age and salary. Here this has been used to store data since it contains the address of the current object. Thefunction show( ) has been used to display the data of employee.
-------------------------------------------------------------------------------------------------
45.
Why is it necessary to use a reference in the argument to the copy constructor?
Ans : If we pass the copy constructor the argument by value, its copy would get constructed using the copy constructor. This means the copy constructor would call itself to make this copy. This process would go on and on until the compiler runs out of memory. This can be explained with the help of following example:
class sample
{
int i ;
public :
sample ( sample p )
{
i = p.i ;
}
} ;
void main( )
{
sample s ;
sample s1 ( s ) ;
}
While executing the statement sample s1 ( s ), the copy constructor would get called. As the copy construct here accepts a value, the value of s would be passed which would get collected in p. We can think of this statement as sample p = s. Here p is getting created and initialized. Means again the copyconstructor would get called. This would result into recursive calls. Hence we must use a reference as an argument in a copy constructor.
46.
Virtual Multiple Inheritance:
A class b is defined having member variable i. Suppose two classes d1 and d2 are derived from class b and a class multiple is derived from both d1 and d2. If variable i is accessed from a memberfunction of multiple then it gives error as 'member is ambiguous'. To avoid this error derive classes d1 and d2 with modifier virtual as shown in the following program.
#include
class b
{
public :
int i ;
public :
fun( )
{
i = 0 ;
}
} ;
class d1 : virtual public b
{
public :
fun( )
{
i = 1 ;
}
} ;
class d2 : virtual public b
{
public :
fun( )
{
i = 2 ;
}
} ;
class multiple : public d1, public d2
{
public :
fun( )
{
i = 10 ;
}
} ;
void main( )
{
multiple d ;
d.fun( ) ;
cout << d.i ;
}
-------------------------------------------------------------------------------------------------
47.
Can we use this pointer in a class specific, operator-overloading function for new operator?
Ans: No! The this pointer is never passed to the overloaded operator new() member function because this function gets called before the object is created. Hence there is no question of the this pointer getting passed to operator new( ).
-------------------------------------------------------------------------------------------------
48.
Can we allocate memory dynamically for a reference?
Ans: No! It is not possible to allocate memory dynamically for a reference. This is because, when we create a reference, it gets tied with some variable of its type. Now, if we try to allocate memory dynamically for a reference, it is not possible to mention that to which variable the reference would get tied.
49.
When should I overload new operator on a global basis or a class basis?
Ans: We overload operator new in our program, when we want to initialize a data item or a class object at the same place where it has been allocated memory. The following example shows how to overload newoperator on global basis.
#include
#include
void * operator new ( size_t s )
{
void *q = malloc ( s ) ;
return q ;
}
void main( )
{
int *p = new int ;
*p = 25 ;
cout << *p ;
}
When the operator new is overloaded on global basis it becomes impossible to initialize the data members of a class as different classes may have different types of data members. The following example shows how to
overload new operator on class-by-class basis.
#include
#include
class sample
{
int i ;
public :
void* operator new ( size_t s, int ii )
{
sample *q = ( sample * ) malloc ( s ) ;
q -> i = ii ;
return q ;
}
} ;
class sample1
{
float f ;
public :
void* operator new ( size_t s, float ff )
{
sample1 *q = ( sample1 * ) malloc ( s ) ;
q -> f = ff ;
return q ;
}
} ;
void main( )
{
sample *s = new ( 7 ) sample ;
sample1 *s1 = new ( 5.6f ) sample1 ;
}
Overloading the operator new on class-by-class basis makes it possible to allocate memory for an object and initialize its data members at the same place.
-------------------------------------------------------------------------------------------------
50.
How would you define a pointer to a data member of the type pointer to pointer?
Ans: The following program demonstrates this...
#include
class sample
{
public :
sample ( int **pp )
{
p = pp ;
}
int **p ;
} ;
int **sample::*ptr = &sample::p ;
void main( )
{
int i = 9 ;
int *pi = &i ;
sample s ( π ) ;
cout << ** ( s.*ptr ) ;
}
Here, ptr is the pointer to data member p of class sample, which in turn is a pointer pointing to an int.
-------------------------------------------------------------------------------------------------
51.
How do I write a code to catch multiple types of exceptions in one single catch block?
Ans: The following program demonstrates the use of a single catch block to catch multiple exceptions.
#include
class test
{
} ;
class sample
{
public :
void fun1( )
{
throw 99 ;
}
void fun2( )
{
throw 3.14f ;
}
void fun3( )
{
throw "error" ;
}
void fun4( )
{
throw test( ) ;
}
} ;
void main( )
{
try
{
sample s ;
s.fun4( ) ;
s.fun1( ) ;
s.fun2( ) ;
s.fun3( ) ;
}
catch ( ... )
{
cout << "strange" ;
}
}
Here, different types of exceptions are thrown by the member functions of the class sample. While catching the exception instead of four different catch blocks we can as well define one single catch block. Note the syntax for defining the catch block, where we have used three dots (…) in the formal parameter list. This indicates that any thrown exception should get caught in the same catch block. When the exception is thrown from the fun4( ) control reaches the catch block, ignoring the rest of the calls.
52.
Can we return an error value from the constructor of a class?
Ans: No. We cannot return any error value from the constructor, as the constructor doesn't have any return type. However, by throwing an exception we can pass value to catch block. This is shown in the following example:
#include
class sample
{
public :
sample ( int i )
{
if ( i == 0 )
throw "error" ;
}
} ;
void main( )
{
try
{
sample s ( 0 ) ;
}
catch ( char * str )
{
cout << str ;
}
}
In this program, the statement throw "error" ; would throw an exception when an object s of the class sample would get created. The catch block would collect the string error.
-------------------------------------------------------------------------------------------------
53.
How do I define the member function of a template class, which has to be defined outside the template class. The function receives an object of its own class as a parameter and returns the value of the same type.
Ans: The following example shows how we can define such a function.
sample sample::fun ( sample s )
{
// code
}
Here, the first sample indicates the return type of the function and the next sample is used for the scope of function.
-------------------------------------------------------------------------------------------------
54.
How name mangling can be prevented?
Ans: To avoid name mangling the function should be declared with an extern "C" attribute. Functions declared as extern "C" are treated as C-style functions. Hence the compiler does not mangle them. The following code snippet shows how to declare such a function.
#include
extern "C" void display( )
{
cout << "See the effect of C in C++ " ;
}
void main( )
{
display( ) ;
}
-------------------------------------------------------------------------------------------------
55.
Can we allocate memory dynamically for a reference?
Ans: No, it is not possible to allocate memory dynamically for a reference. A reference is initialized at the time of creation. Trying to allocate memory dynamically for a reference creates a problem in initializing it. Thus, the compiler does not allow us to dynamically allocate the memory for references.
-------------------------------------------------------------------------------------------------
56.
What is RTTI?
Ans: RTTI stands for 'Run Time Type Information'. We use virtual function mechanism where we can call derived class's member functions using base class's pointer. However, many times we wish to know the exact type of the object. We can know the type of the object using RTTI. A function that returns the type of the object is known as RTTI functions. C++ supports two ways to obtain information about the object's class at run time, they are typeid( ) operator and dynamic_cast operator.
57.
What is Data Conversion?
Ans: Assignments between types whether they are basic or user-defined, are handled by the compiler. If the variables are of different basic types compiler calls a special routine to convert the value. But if we want to convert between user-defined data type and basic types we have to write conversion routine ourselves. A conversion routine to convert user-defined data type string to integer is shown below:
class string
{
private :
char str[20] ;
public :
string( )
{
}
string ( char *s )
{
strcpy ( str, s ) ;
}
operator int( )
{
return 123 ; // Write logic to convert string to integer
}
} ;
main( )
{
string s2 = "123" ;
int i1 = int ( s2 ) ;
cout << endl << i1 ;
}
-------------------------------------------------------------------------------------------------
58.
How to obtain type information using typeid( ) operator?
Ans: typeid( ) operator takes an object, a reference or a pointer and returns its type. Following program shows how to use the typeid( ) operator.
#include
#include
class Base
{
public :
virtual void show( )
{
}
};
class Der1 : public Base
{
} ;
void main( )
{
Base *b1 ;
cout << endl << typeid ( b1 ).name( ) ;
Der1 d1 ;
b1 = &d1 ;
cout << endl << typeid ( *b1 ).name( ) ;
cout << endl << typeid ( 12 ).name( ) << endl << typeid ( 12.5 ).name( ) ;
}
The output of this program will be
Base*
Der1
int
double
RTTI operators must be used for polymorphic class (class having virtual function) only. For non-polymorphic class static type information is returned.
-------------------------------------------------------------------------------------------------
59.
How to use RTTI with class templates?
Ans: Templates can generate different classes. We may wish to get the type of class, which we are working in. The following program shows how to use RTTI operator typeid( ) with class template.
#include
#include
template
class base
{
public :
base( )
{
cout << typeid ( *this ).name( ) << "Constructor" << endl ;
}
T add ( T a, T b )
{
return a + b ;
}
~base( )
{
cout << typeid ( *this ).name( ) << "Destructor" << endl ;
}
} ;
void main( )
{
base b1 ;
cout << b1.add ( 10, 20 ) << endl ;
base b2 ;
cout << b2.add ( 5.5, 10.5 ) << endl ;
}
60.
We can use following C++ operators for typecasting.static_cast is used for castless conversions, narrowing conversions, conversion from void* and implicit type conversions. const_cast is used to convert a const to a non-const. reinterpret_cast is used to assign one kind of pointer to another.
-------------------------------------------------------------------------------------------------
61.
What will be the output of the following program?
#include
class A
{
public :
A( )
{
cout << "Reached in Constructor\n" ;
}
} ;
void main( )
{
A a( ) ;
A b ;
}
Output : Reached in Constructor
Constructor gets called only once when the object b is created. When the statement A a( ) ; gets executed constructor does not get called. This is because compiler takes this statement as a prototype declaration of function a( ) that returns an object of class A. However, if we pass arguments like
A a ( 10 ) ;
Compiler would search for one argument constructor and if not found would flash an error.
-------------------------------------------------------------------------------------------------
62.
What is a container?
Ans: A container is an object that holds other objects. Various collection classes like List, Hash Table, AbstractArray, etc. are the examples of containers. We can use the classes to hold objects of any derived classes. The containers provide various methods using which we can get the number of objects stored in the container and iterate through the objects stored in it.
-------------------------------------------------------------------------------------------------
63.
Function template overloading
One can declare several function templates with the same name and even declare a combination of function templates and ordinary functions with the same name. When an overloaded function is called, overload resolution is necessary to find the right function or template function to invoke.
For example:
template < class T > T sqrt ( T ) ;
template < class T > complex < T > sqrt ( complex < T > ) ;double sqrt (
double ) ;
void f ( complex < double > z )
{
sqrt ( 2 ) ; // sqrt < int > ( int )
sqrt ( 2.0 ) ; // sqrt ( double )
sqrt ( z ) ; // sqrt < complex < double > ( complex < double > )
}
In the same way that a template function is a generalization of the notion of a function, the rules for resolution in the presence of function templates are generalizations of the function overload resolution rules. Basically, for each template we find the specialization that is best for the set of function arguments. Then we apply the usual function overload resolution rules to these specializations and all ordinary functions.
• First
• Prev
Subscribe to:
Posts (Atom)