Monday, 31 August 2015

Java Questions & Answers : Set - II

19. Explain the benefits of packages.

By organizing the classes into packages, we achieve the following benefits :
The classes contained in the packages of other programs can be easily reused.
In packages, classes can be unique compared with classes in other packages. That is, two classes in two different packages can have the same name. They may be referred by their fully qualified name, comprising the package name and class name.
Packages provide a way to hide classes thus preventing other programs or packages from accessing classes that are meant for internal use only.
Packages also provide a way for separating design from coding. First, we can design classes and decide their relationships and then we can implement the Java code needed for the methods. It is possible to change the implementation of any method without affecting the rest of the design.

20. What is static import?

Static import is another language feature introduced with the J2SE 5.0 release. This feature eliminates the need of qualifying a static member with the class name.

21. What is multitasking?

In the modern operating systems such as Windows 7, several programs can be executed simultaneously. This ability is known as multitasking.

22. What is multithreading ?

Multithreading is a conceptual programming paradigm where a program (process) is divided into two or more subprograms (processes), which can be implemented/executed at the same time in parallel.
This is similar to dividing a task into sub-tasks and assigning them to different people for execution independently and simultaneously.

23. What is thread?

A thread is similar to a program that has a single flow of control. It has a beginning, a body and an end and executes commands sequentially.

24. What is concurrency?

The ability of a language to support multithreads is referred to as concurrency.

25. Why threads are known as lightweights processes?

Since threads in Java are subprograms of a main application program and share the same memory space, they are known as lightweight processes or lightweight threads.

26. In how many ways a thread an be created?

A new thread can be created in two ways :

By creating a thread class : Define a class that extends thread class and    override its run() method with the code required by the thread.
By converting a class to a thread : Define a class that implements    Runnable interface. The Runnable interface has only one method, run() that is to be defined in the method with the code to be executed by the thread.
27. Define the steps of extending the thread class.

Define the class as extending the Thread class.
Implement the run() method that is responsible for executing the sequence of code that the thread will execute.
Create a thread object and call the start() method to initialize the thread execution.

28. What are Local and Remote applets?

An applet developed locally and stored in a local system is known as a Local applet. When a web page is trying to find a local applet, it doesn’t need to use the Internet and therefore the local system doesn’t require the Internet connection. It simply searches the directories of the local system and locates and loads the specified applet.
Remote applet is that which is developed by someone else and stored on a remote computer connected to the Internet. If our system is connected to the Internet, we can download the remote applet onto our system via the Internet and run it.

29. Explain how applets differ from Applications.

Applets do not use the main() method for initializing the execution of the code. Applets, when loaded, automatically call certain methods of applet class to start and execute the applet code.
Unlike stand-alone applications, applets cannot be run independently. They are run from inside a web-page using a special feature known as HTML tag.
Applets cannot read from or write to the files in the local computer.
Applets cannot communicate with other services on the network.
Applets cannot run any program from the local computer.
Applets are restricted from using libraries from other languages such as C or C++.

30. What is event handling?

Event handling is a mechanism that is used to handle events generated by applets. An event could be the occurrence of any activity such as a mouse click or a key press. In Java, events are regarded as method calls with a certain task performed against the occurrence of each event.

31. Name some of the key events in Java.

Some of the key events in Java are:

Action event is triggered whenever a user interface element is activated,    such as selection of a menu item.
Item event is triggered at the selection or de-selection of an itemized or list  element, such as check box.
Text event is triggered when a text field is modified.
Window event is triggered whenever a window-related operation is  performed, such as closing or activating a window.
Key event is triggered whenever a key is pressed on the keyboard.

  

Java Questions & Answers : Set - I

1. What are standalone applications?

Standalone applications are programs written in Java to carry out certain tasks on a local computer. Executing a standalone Java program involves two steps :
Compiling source code into byte code using javac compiler.
Executing the bytecode program using Java interpreter.

2. What are applets?

Applets are small Java programs developed for internet applications.A applet located on a distant computer (server) can be downloaded via internet and executed on a local computer (client) using a Javaenabled browser. We can develop applets for doing everything from simple animated graphics to complex games and utilities. Since applets are embedded in an HTML document and run inside a web page, creating and running applets are complex than creating an application.

3. Difference between standalone applications and applets.

Standalone programs can read and write files and perform certain operations that applets cannot do. An applet can only run within a web browser.

4. What are local variables?

Variables declared and used inside methods are called local variables and these are accessible within the method only.

5. What are instance variables ?

Instance variables are created when the objects are instantiated and therefore they are associated with the object. They take different values for each object.

6. What are class variables?

Class variables are global to a class and belong to the entire set of objects that class creates.

7. What is Java Virtual Machine (JVM) ?

To achieve architecture neutrality, Java compiler produces an intermediate code known as bytecode for  machine that does not exist. This machine is called Java Virtual Machine (JVM) and it exists only inside the computer memory. It is a simulated computer within the computer and does all major functions of a real computer.
The virtual machine code is not machine specific. The machine specific code (known as machine code) is generated by the Java interpreter by acting as an intermediary between the virtual machine and the real machine. Remember that interpreter is different for different machine.

8. What is wrapper class ?

Primitive data types may be converted into object types by using the wrapper classes contained in the java.lang package.

9. What are classes and objects?
 
A class defines the state and behavior of the basic program components known as objects. Classes create objects and objects use methods to communicate between them.
In other words, a class is a user-defined data type with a template that servers to define its properties.

10. What is a constructor?

A constructor enables an object to initialize itself when it is created.
Constructors have the same name as the class itself. And they do not specify a return type, not even void. This is because they return the instance of the class itself.

11. What is method overloading?

In Java, it is possible to create methods that have the same name, but different parameter lists and different definitions. This is called method overloading. Method overloading is used when objects are required to perform similar tasks but using different input parameters.

12. What is polymorphism?

When we call a method in an object, Java matches up the method name first and then the number and type of parameters to decide which one of the definitions to execute. This process is known as polymorphism.

13. What is inheritance?

The mechanism of deriving a new class from an old one is called inheritance.
The old class is known as the base class or super class or parent class and the new one is called the subclass or derived class or child class.

14. Explain the thumb rules of access specifiers.

Use public if the field is to be visible everywhere.
Use protected if the field is to be visible everywhere in current package and also subclass of other package.
default visible everywhere in current package only.
private protected visible subclass regardless of package.
private not visible anywhere except own class.

15. Where the final keyword is used?

All methods and variables can be overridden by default in subclass. If we wish to prevent the subclass from overriding the members of the superclass, we can declare them as final using the keyword final as a modifier.

16. Explain the advantages of vectors over arrays.

Vectors posses a number of advantages over arrays :

It is inconvenient to use vectors to store objects.
A vector can be used to store a list of objects that may vary in size.
We can add and delete objects from the list as and when required.

17. What is interface ?

An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a major difference. The difference is that interfaces define only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contains only constants.
Therefore, it is the responsibility of the class that implement an interface to define the code for implementation of these methods.
   
Note : Java does not support multiple inheritance. It means that Java cannot have     more than one superclass. Java provides an alternative approach known as interface to support the concept of multiple inheritance.

18. What are packages in Java?

Packages are Java’s way of grouping a variety of classes and/or interfaces together. The grouping is usually done according to functionality. In fact, packages act as “container” of classes.

Wednesday, 29 July 2015

Write a C program to check whether the given number is palindrome or not

#include <stdio.h>
#include <conio.h>

void main()
{
int b,r,n,s=0;
scanf("%d",&n);
b=n;
while(n!=0)
{
r=n%10;
s=s*10 + r;
n/=10;
}
if(s==b)
printf("\n The number is palindrome");
else
printf("\n The number is not palindrome");
getch();
}

Write a C program to print the following pattern:

       

#include <stdio.h>
#include <conio.h>

void main()
{
int i,j,k=1,n;
clrscr();
printf("\n Enter the no of rows: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",k%2);
k++;
}
printf("\n");
}
getch();
}

Write a C program to print the following pattern:

*
**
***
****

#include <stdio.h>
#include <conio.h>

void main()
{
int i,j,n;
clrscr();
printf("\n Enter the no of rows: ");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
}

Write a C program to search an element in an array using Binary Search

#include <stdio.h>
#include <conio.h>

void main()
{
int a[5];
int mid, lower=0, upper=4, flag=1, num, i;
clrscr();
printf("\n Enter the array elements: ");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
while(lower <= upper)
{
mid=(lower+upper)/2;
if(a[mid]==num)
{
printf("\n The no is present at position %d",mid);
flag=0;
break;
}
else
{
if(a[mid] > num)
upper=mid-1;
else
lower=mid+1;
}
}
if(flag)
printf("The no is not present in the array");
getch();
}

Write a C program to implement array operations

 #include <stdio.h>
#include <conio.h>

int n;
void beg_ins(int a[10])
{
  int k,i;
printf("Enter the number you want to add: ");
scanf("%d",&k);
for(i=0;i>=0;i--)
a[i]=a[i-1];
n++;
a[0]=k;
display(a);
getch();
}

void beg_del(int a[10])
{
int i;
for(i=0;i<n;i++)
a[i]=a[i+1];
n--;
display(a);
getch();
}

void repl_posn(int a[10])
{
int x,p,i;
printf("\nEnter the position to be replaced: ");
scanf("%d",&p);
if(p>=n)
printf("\nSorry, cannot be replaced");
else
{
printf("\n Enter the number: ");
scanf("%d",&x);
a[p-1]=x;
}
display(a);
getch();
}

void display(int a[10])
{
int i;
printf("\n The array elements are : ");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

void main()
{
int a[10],i,x;
printf("\n Enter the number of elements : ");
scanf("%d",&n);
printf("\n Enter the array elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n 1. Insert \n 2. Delete \n 3. Replace \n 4. Display \n 5. Exit ");
printf("\n Enter your choice: ");
scanf("%d", &x);
switch(x)
{
case 1 : beg_ins(a);
break;
case 2 : beg_del(a);
break;
case 3 : repl_posn(a);
break;
case 4 : display(a);
break;
case 5 : return 0;
default : printf("Invalid choice");
}
}

Tuesday, 21 July 2015

Interview Questions on C Programming

1. Difference between array and linked list.

1. Access :Random / Sequential

Stack elements can be randomly Accessed using Subscript Variable
e.g a[0],a[1],a[3] can be randomly accessed
While In Linked List We have to Traverse Through the Linked List for Accessing Element. So O(n) Time required for Accessing Element .
Generally In linked List Elements are accessed Sequentially.

2 . Memory Structure :

Stack is stored in contiguous Memory Locations , i.e Suppose first element is Stored at 2000 then Second Integer element will be stored at 2002 .
But It is not necessary to store next element at the Consecutive memory Location .
Element is stored at any available Location , but the Pointer to that memory location is stored in Previous Node.

3 . Insertion / Deletion

As the Array elements are stored in Consecutive memory Locations , so While Inserting elements ,we have to create space for Insertion.
So More time required for Creating space and Inserting Element
Similarly We have to Delete the Element from given Location and then Shift All successive elements up by 1 position
In Linked List we have to Just Change the Pointer address field (Pointer),So Insertion and Deletion Operations are quite easy to implement

4 . Memory Allocation :

Memory Should be allocated at Compile-Time in Stack . i.e at the time when Programmer is Writing Program
In Linked list memory can be allocated at Run-Time , i.e After executing Program
Stack uses Static Memory Allocation and Linked List Uses Dynamic Memory Allocation
Dynamic Memory allocation functions – malloc,calloc,delete etc…
2. What are enumerations?

An enumeration is a user-defined data type consists of integral constants and each integral constant is give a name. Keyword enum is used to defined enumerated data type.
enum type_name{ value1, value2,...,valueN };
Here, type_name is the name of enumerated data type or tag. And value1value2,....,valueN are values of type type_name.
By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change the default value.
3. Describe about storage allocation and scope of global, extern, static, local and regular variables.
The storage allocation / class determine the memory part where the storage space is allocated for variables, functions and how long the allocation of storage continues to exist. 
The scope of a variable is specified by its storage allocation. This is specified by the keywords – auto, extern, static and register.
- ‘auto’ variables stores in the memory storage. Majority of the variables in a program / application are of type ‘auto’. Their scope might be local or global.
- ‘extern’ variables are of global variables and can be declared in another source file which could be external / outside the current program scope,
- ‘register’ variables are allocated in the CPU registers. These variables storage and accessibility is much faster than other variables, being they are stored in CPU itself. The variables of repeated usage or access time is critical, can be declared as register variables.
- ‘static’ variables provides a lifetime over the program, and provides a way for limiting the scope of such variables. These variables are automatically initialized to zero and could be specified for ‘auto’ and ‘extern’ variables. The values are retained, even though they are declared in local scope, between the repeated function calls to the same function.

4. What is the use of typedef ?

typedef is a keyword in the C and C++ programming languages. The purpose of typedef is to assign alternative names to existing types, most often those whose standard declaration is cumbersome, potentially confusing, or likely to vary from one implementation to another.

And:
K&R states that there are two reasons for using a typedef. First, it provides a means to make a program more portable. Instead of having to change a type everywhere it appears throughout the program's source files, only a single typedef statement needs to be changed. Second, a typedef can make a complex declaration easier to understand.

5. Can we specify variable field width in a scanf() format string? If possible how?
It is possible to specify variable field width in a scanf() format string. By using %s control string. This character reads a string of variable field width up to the first white space character. 
Ex: scanf(“%s”, name); // where name is a character array
6. Out of fgets() and gets() which function is safe to use and why?
The function fgets() function is safer to use. It checks the bounds, i.e., the size of the buffer and does not cause overflow on the stack to occur. gets() does not check the bounds.
7. Difference between strdup and strcpy.
The function strcpy() will not allocate the memory space to copy. A pointer to the string to copy and a pointer to place to copy it to should be given.
The function strdup() will occupy / grab itself the memory space for copying the string to. This memory space needs to be freed up later when it is of no use anymore.
8. What is recursion?

Recursion is an approach in which a function calls itself with an argument. Upon reaching a termination condition, the control returns to the calling function.
9. Write down the equivalent pointer expression for referring the same element a[i][j][k][l] ?

It is a[i][j][k][l]; so in pointer reference:
(*(*(*(*(a+i)+j))+k)+l)

10. What is difference between Structure and Unions?

Structure
Union
1.The keyword  struct is used to define a structure
1. The keyword union is used to define a union.
2. When a variable is associated with a structure, the compiler allocates the 
memory for each member.
 The size of structure is greater than or equal to the sum of  sizes of its members. 
The smaller members may end with unused slack bytes.
2. When a variable is associated with a union, the  compiler allocates the 
 memory by considering the size of the largest memory. So, size of union 
is equal to the size of largest member.
3. Each member within a structure is assigned unique storage area of location.
3. Memory allocated is shared by individual members of union.
4. The address of each member will be in ascending order This indicates that
 memory for each member will start at different offset values.
4. The address is same for all the members of a union. This indicates that
 every member begins at the same offset value.
5 Altering the value of a member will not affect other members of the structure.
5. Altering the value of any of the member will alter other member values.
6. Individual member can be accessed at a time
6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at once.
7. Only the first member of a union can be initialized.

11. What are the advantage of using Unions?

Unions are useful (often in embedded programming) when it is needed to refer to a data item as two or more different types: e.g. it may be used as an integer for math, but an array of bytes for a serial transmission or a checksum calculation.
For memory preservation, since the space allocated for the union is as big as its biggest member.

12. What are the advantages of using pointers in a program?

pointers are generally useful in the context where we need a continuous memory allocation. Using pointers dynamic allocation of memory is achieved 

pointers basically hold the address of a variable. they are mainly used as function parameters to pass values of parameters as references rather than values



14. What is a far pointer? Where we use it?

 Far pointer: it will access the total memory of the system and can be use to point to every object used in the memory.

15. What is NULL pointer? Whether it is same as an uninitialized pointer?

An uninitialized pointer is a pointer that has not been assigned a value; it's uninitialized. 
The value of an uninitialized pointer is undefined (it could be anything). 
A null pointer is simply a pointer that has a value of NULL. 
A word of advice: initialize your pointers to NULL. 
This allows you to see that the pointer is invalid; to check if an uninitialized pointer is valid is quite impossible. 

16. What does the error ‘NULL pointer assignment’ means and what causes this error?

A NULL pointer assignment is a runtime error It occurs due to various reasons one is that your program has tried to access an illegal memory location. Illegal location means either the location is in the operating systems address space or in the other processes memory space. In stdio.h NULL is defined as 0 So whenever your program tries to access 0th location the operating system kills your program with runtime assignment error because the 0th location is in the operating systems address space and operating system doesn't allow access to its address space by user program.

17. What are near, far and huge pointers? How many bytes do they occupy?

Near, far, and huge pointers are different types of pointers used to reconcile the different addressing models of the Intel 8086/8088 class processors, running in a 16-bit operating system such as Windows 3.x, as well as any of the newer incarnations running in real mode or virtual 8086 mode. 
A near pointer can address something within one 64Kb memory segment, containing only an offset, and it takes two bytes. The segment is implied by context, and is usually the data segment, selected for the addressing model.
A far pointer can address anything in the 1Mb memory1, containing both a segment and an offset, and it takes four bytes. 
A huge pointer is a normalised far pointer, which means its offset part is always between 00H and 0FH. 
In 32-bit mode a pointer can address anything in 4Gb memory, containing a flat 32-bit offset, and it takes four bytes. (In this mode segments have no significance.) It only works, however, when there is support for it, such as the WIN32 extension of Windows 3.x.