google Analytics

Thursday, December 16, 2010

Hibernate one-one Mappng Example




Hibernate – One-to-one relationship example
Hibernate one to one Mapping Example
hibernate one to one annotation example
=========================================================================

The Scripts
CREATE TABLE `user` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1$$

CREATE TABLE `address` (
  `ID` int(11) NOT NULL,
  `ADDRESS` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `FK_ID` (`ID`),
  CONSTRAINT `FK_ID` FOREIGN KEY (`ID`) REFERENCES `user` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$

=================================================================================
The User.java Domain Class
@Entity
@Table(name = "user", catalog = "onetwoone")
public class User implements java.io.Serializable {
    private Integer id;
    private String name;
    private Address addresses;
    public User() {
    }
    @Id
    @GeneratedValue(strategy = AUTO)
    @Column(name = "ID", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name = "NAME", length = 45)
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "user")
    @Cascade( { CascadeType.ALL })
    public Address getAddresses() {
        return this.addresses;
    }

    public void setAddresses(Address addresses) {
        this.addresses = addresses;
    }
}

===================================================================================================
The Addres class
 To map the association of user in the Address class as a shared primary key association, you also need the @PrimaryKeyJoinColumn annotation:
@Entity
@Table(name = "address", catalog = "onetwoone")
public class Address implements java.io.Serializable {
    private Integer id;
    private User user;
    private String address;
    public Address() {
    }

    // Property accessors
    @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user"))
    @Id
    @GeneratedValue(generator = "generator")
    @Column(name = "ID", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    public User getUser() {
        return this.user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    @Column(name = "ADDRESS", length = 45)
    public String getAddress() {
        return this.address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}
==================================================================================================
Test Programme
public class TestOneTwoOneMapping {
    public static void main(String[] args) {
        User user=new User();
        user.setName("Anish");
        Address address =new Address();
        address.setAddress("USA");
        address.setUser(user);
        user.setAddresses(address);
        new UserDAO().save(user);
    }
}

================================================================================================

The hibernatecfg.xml file
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
    <property name="connection.username">root</property>
    <property name="connection.url">
        jdbc:mysql://localhost/onetwoone
    </property>
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>
    <property name="myeclipse.connection.profile">
        com.mysql.jdbc.Driver
    </property>
    <property name="connection.password">password</property>
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="show_sql">true</property>
    <mapping class="session.User" />
    <mapping class="session.Address" />
</session-factory>
</hibernate-configuration>
===============================================================================================
ANish

Monday, December 6, 2010

C Objective Questions and Answers

C Objective Questions and Answers
C Technical Interview Questions and Answers
-----------------------------------------------------------------------------------------------------------




50.

How do I print a floating-point number with higher precision say 23.34568734 with only precision up to two decimal places?

Ans: This can be achieved through the use of suppression char '*' in the format string of printf( ) as shown in the following program.
main( )
{
int i = 2 ;
float f = 23.34568734 ;
printf ( "%.*f", i, f ) ;
}
The output of the above program would be 23.35.

-------------------------------------------------------------------------------------------------
51.
Are the expressions *ptr++ and ++*ptr same?

Ans: No. *ptr++ increments the pointer and not the value pointed by it, whereas ++*ptr increments the value being pointed to by ptr.

-------------------------------------------------------------------------------------------------

52.
strpbrk( )

The function strpbrk( ) takes two strings as parameters. It scans the first string, to find, the first occurrence of any character appearing in the second string. The function returns a pointer to the first occurrence of the character it found in the first string. The following program demonstrates the use of string function strpbrk( ).

#include <string.h>
main( )
{
char *str1 = "Hello!" ;
char *str2 = "Better" ;
char *p ;
p = strpbrk ( str1, str2 ) ;

if ( p )
printf ( "The first character found in str1 is %c", *p ) ;
else
printf ( "The character not found" ) ;
}
The output of the above program would be the first character found in str1 is e


53.

Can we convert an unsigned long integer value to a string?

Ans: The function ultoa( ) can be used to convert an unsigned long integer value to a string. This function takes three arguments, first the value that is to be converted, second the base address of the buffer in which the converted number has to be stored (with a string terminating null character '\0') and the last argument specifies the base to be used in converting the value. Following example demonstrates the use of this function.

#include <stdlib.h>
void main( )
{
unsigned long ul = 3234567231L ;
char str[25] ;

ultoa ( ul, str, 10 ) ;
printf ( "str = %s unsigned long = %lu\n", str, ul ) ;
}


-------------------------------------------------------------------------------------------------
54.
ceil( ) and floor( )

The math function ceil( ) takes a double value as an argument. This function finds the smallest possible integer to which the given number can be rounded up. Similarly, floor( ) being a math function, takes a double value as an argument and returns the largest possible integer to which the given double value can be rounded down. The following program demonstrates the use of both the functions.

#include <math.h>
void main( )
{
double no = 1437.23167 ;
double down, up ;

down = floor ( no ) ;
up = ceil ( no ) ;

printf ( "The original number %7.5lf\n", no ) ;
printf ( "The number rounded down %7.5lf\n", down ) ;
printf ( "The number rounded up %7.5lf\n", up ) ;
}

The output of this program would be,
The original number 1437.23167
The number rounded down 1437.00000
The number rounded up 1438.00000


-------------------------------------------------------------------------------------------------
55.

How do I use function ecvt( ) in a program?

Ans: The function ecvt( ) converts a floating-point value to a null terminated string. This function takes four arguments, such as, the value to be converted to string, the number of digits to be converted to string, and two integer pointers. The two-integer pointer stores the position of the decimal point (relative to the string) and the sign of the number, respectively. If the value in a variable, used to store sign is 0, then the number is positive and, if it is non-zero, then the number is negative. The function returns a pointer to the string containing digits. Following program demonstrates the use of this function.

#include <stdlib.h>
main( )
{
char *str ;
double val ;
int dec, sign ;
int ndig = 4 ;

val = 22 ;
str = ecvt ( val, ndig, &dec, &sign ) ;
printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ;

val = -345.67 ;
ndig = 8 ;
str = ecvt ( val, ndig, &dec, &sign ) ;
printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ;

// number with a scientific notation
val = 3.546712e5 ;
ndig = 5 ;
str = ecvt ( val, ndig, &dec, &sign ) ;
printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ;
}

The output of this program would be

string = 2200 dec = 2 sign = 0
string = 34567000 dec = 3 sign = 1
string = 35467 dec = 6 sign = 0


-------------------------------------------------------------------------------------------------

56.

How to run DIR command programmatically?

Ans: We can use the system( ) function to execute the DIR command along with its options. Following program shows how this can be achieved:

// mydir.c

main ( int argc, char *argv[ ] )
{
char str[30] ;

if ( argc < 2 )
exit ( 0 ) ;

sprintf ( str, "dir %s %s", argv[1], argv[2] ) ;
system ( str ) ;
}

If we run the executable file of this program at command prompt passing the command line arguments as follows:

> mydir abc.c /s

This will search the file 'abc.c' in the current directory.
-------------------------------------------------------------------------------------------------
57.

Suppose I have a structure having fields name, age, salary and have passed address of age to a function fun( ). How I can access the other member of the structure using the address of age?
Ans:
struct emp
{
char name[20] ;
int age ;
float salary ;
} ;
main( )
{
struct emp e ;
printf ( "\nEnter name: " ) ;
scanf ( "%s", e.name ) ;
printf ( "\nEnter age: " ) ;
scanf ( "%d", &e.age ) ;
printf ( "\nEnter salary: " ) ;
scanf ( "%f", &e.salary ) ;
fun ( &e.age ) ;
}
fun ( int *p )
{
struct emp *q ;
int offset ;
offset = ( char * ) ( & ( ( struct emp * ) 0 ) -> age ) - ( char * ) ( (
struct emp* ) 0 ) ;
q = ( struct emp * ) ( ( char * ) p - offset ) ;
printf ( "\nname: %s", q -> name ) ;
printf ( "\nage: %d", q -> age ) ;
printf ( "\nsalary: %f", q -> salary ) ;
}


58.

How to restrict the program's output to a specific screen region?

Ans: A C function window( ) can be used to restrict the screen output to a specific region. The window( ) function defines a text-mode window. The parameters passed to this function defines the upper-left and lower-right corner of the region within which you want the output. In the following program, the string 'Hello!' gets printed within the specified region. To print the string we must use cprintf( ) function which prints directly on the text-mode window.

#include <conio.h>
main( )
{
int i, j ;

window ( 20, 8, 60, 17 ) ;
for ( i = 0 ; i < 8 ; i++ )
for ( j = 0 ; j < 10 ; j++ )
cprintf ( "Hello!" ) ;
}

-------------------------------------------------------------------------------------------------
59.

Sometimes you need to prompt the user for a password. When the user types in the password, the characters the user enters should not appear on the screen. A standard library function getpass( ) can be used to perform such function. Maximum number of characters that can be entered as password is 8.

main( )
{
char *pwd ;

pwd = getpass ( "Enter Password" ) ;

if ( strcmp ( pwd, "orgcity" ) )
printf ( "\nPassword %s is incorrect", pwd ) ;
else
printf ( "\nCorrect Password" ) ;
}


-------------------------------------------------------------------------------------------------
60.
How to obtain the current drive through C ?

Ans: We can use the function _getdrive( ) to obtain the current drive. The _getdrive( ) function uses DOS function 0X19 to get the current drive number

#include <direct.h>
main( )
{
int disk ;
disk = _getdrive( ) + 'A' - 1 ;
printf ( "The current drive is: %c\n", disk ) ;
}


-------------------------------------------------------------------------------------------------
61.

How come the output for both the programs is different when the logic is same?

main( )
{
int i, j ;

for ( i = 1, j = 1 ; i <= 5, j <= 100 ; i++, j++ )
{
gotoxy ( 1, 1, ) ;
printf ( "%d %d", i, j ) ;
}
}

main( )
{
int i, j ;

for ( i =1, j = 1; j <= 100, i <= 5; i++, j++ )
{
gotoxy ( 1, 1 ) ;
printf ( "%d %d", i, j ) ;
}
}

Output -> 5 5
Even if logic of both the programs is same the output of the first program comes out to be 100, 100, but of the second program it is 5, 5. The comma operator plays a vital role inside the for loop. It always considers the value of the latest variable. So, at the time of testing the condition in for loop, the value of j will be considered in the first program and value of i in the second.


-------------------------------------------------------------------------------------------------
62.
Can we get the x and y coordinate of the current cursor position ?

Ans : The function wherex( ) and wherey( ) returns the x-coordinate and y-coordinate of the current cursor position respectively. Both the functions return an integer value. The value returned by wherex( ) is the horizontal position of cursor and the value returned by wherey( ) is the vertical position of the cursor. Following program shows how to use the wherex( ) and wherey( ) functions.

#include <conio.h>
main( )
{
printf ( "Just\n To\n Test\n Where\n the cursor\n goes" ) ;

printf ( "Current location is X: %d Y: %d\n", wherex( ), wherey( ) ) ;
}


63.
How do I programmatically delete lines in the text window?

Ans: While writing programs that perform screen-based I/O, you may want to-delete the current line's contents, moving one line up, all of the output that follows. In such cases a function called delline( ) can be used. Following code snippet illustrates the use of function delline( ).

#include <conio.h>
main( )
{
int i ;
clrscr( ) ;

for ( i = 0; i <= 23; i++ )
printf ( "Line %d\r\n", i ) ;

printf ( "Press a key to continue : " ) ;
getch( ) ;

gotoxy ( 2, 6 ) ;

for ( i = 6; i <= 12; i++ )
delline( ) ;

getch( ) ;
}


-------------------------------------------------------------------------------------------------
64.

How do I get the time elapsed between two function calls ?

Ans: The function difftime( ) finds the difference between two times. It calculates the elapsed time in seconds and returns the difference between two times as a double value.

#include <time.h>
#include <stdio.h>
#include <dos.h>

main( )
{
int a[] = { 2, -34, 56, 78, 112, 33, -7, 11, 45, 29, 6 } ;
int s ;
time_t t1, t2 ; // time_t defines the value used for time function

s = sizeof ( a ) / 2 ;
t1 = time ( NULL ) ;
sel_sort ( a, s ) ; // sort array by selection sort
bub_sort ( a, s ) ; // sort array by bubble sort method
t2 = time ( NULL ) ;
printf ( "\nThe difference between two function calls is %f", difftime (
t2, t1 ) ) ;
}

In the above program we have called difftime( ) function that returns the time elapsed from t1 to t2.


-------------------------------------------------------------------------------------------------
65.

How do I use swab( ) in my program ?

Ans: The function swab( ) swaps the adjacent bytes of memory. It copies the bytes from source string to the target string, provided that the number of characters in the source string is even. While copying, it swaps the bytes which are then assigned to the target string.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

main ( )
{
char *str1 = "hS eesll snsiasl not eh es as oher " ;
char *str2 ;
clrscr( ) ;
swab ( str1, str2, strlen ( str1 ) ) ;
printf ( "The target string is : %s\n", str2 ) ; // output -- She sells
snails on the sea shore
getch( ) ;
}

-------------------------------------------------------------------------------------------------
66.

Turbo C provides various command line compiler options which we can use through TCC. The compiler options include : displaying specific warning messages, generating 8087 hardware instructions, using a filename for generating assembly code, etc. Instead of compiler options being executed at command line we can use these compiler options in our program. This can be achieved using #pragma options. We can use various flags with #pragma options to use the compiler options. All these flags are available in turbo C's online help.
-------------------------------------------------------------------------------------------------
67.

I have an array declared in file 'F1.C' as,
int a[ ] = { 1, 2, 3, 4, 5, 6 } ;
and used in the file 'F2.C' as,
extern int a[ ] ;

In the file F2.C, why sizeof doesn't work on the array a[ ]?

Ans: An extern array of unspecified size is an incomplete type. You cannot apply sizeof to it, because sizeof operates during compile time and it is unable to learn the size of an array that is defined in another file. You have three ways to resolve this problem:
1. In file 'F1.C' define as,
int a[ ] = { 1, 2, 3, 4, 5, 6 } ;
int size_a = sizeof ( a ) ;
and in file F2.C declare as,
extern int a[ ] ;
extern int size_a ;

2. In file 'F1.H' define,

#define ARR_SIZ 6
In file F1.C declare as,
#include "F1.H"
int a[ ARR_SIZ ] ;
and in file F2.C declare as,
#include "F1.H"
extern int a[ ARR_SIZ ] ;
3. In file 'F1.C' define as,
int a[ ] = { 1, 2, 3, 4, 5, 6, -1 } ;

and in file 'F2.C' declare as,

extern int a[ ] ;
Here the element -1 is used as a sentinel value, so the code can
understand the end without any explicit size.

68.

How to delete a line from text displayed on the screen?

Ans: Sometimes, specially when we are creating a text editor like program we may wish to allow user to delete a line. We can do so by using two functions namely clreol( ) and delline( ). The clreol( ) function deletes the line from the current cursor position to the end of line. The delline() function deletes the entire line at the current cursor position and
moves up the following line. Following program shows how to use these functions.

#include <conio.h>

main( )
{
int i ;

for ( i = 1 ; i <= 20 ; i++ )
printf ( "This is Line %d\n", i ) ;

getch( ) ;
gotoxy ( 1, 7 ) ;
clreol( ) ;

getch( ) ;
gotoxy ( 1, 12 ) ;
delline( ) ;

getch( ) ;
}


-------------------------------------------------------------------------------------------------
69.
How do I programmatically insert lines in the text window?

Ans: We can insert a blank line in the text window using the insline( ) function. This function inserts line at current cursor position. While doing so, it shifts down the lines that are below the newly inserted line.

#include <conio.h>
void main( )
{
printf ( "The little snail was slowly moving up. She wanted\r\n" ) ;
printf ( "to reach the top of the tree. It was chilly\r\n" ) ;
printf ( "winter season. Most of the animals were resting in\r\n" ) ;
printf ( "their nests as there was a heavy snow fall.\r\n" ) ;
printf ( "\r\nPress any key to continue:" ) ;

gotoxy ( 10, 2 ) ;
getch( ) ;
insline( ) ;
getch( ) ;
}


-------------------------------------------------------
ANish

Sunday, December 5, 2010

C Objective Questions and Answers

C Objective Questions and Answers
=============================================================


=============================================================
 C is interviewer’s favorite language. If you have good command on C language you can get through Technical Interview easily. Most of the interviewers ask basic questions in C. Some times they may ask you to write small programs like reversal of a string, determining whether the given number is a palindrome or not and finding factorial of a given number using recursion etc. You should be able to write these programs quickly.

 Most favorite question for interviewers is interchanging two variables with out using the third variable. Another favorite topic for interviewers is Pointers. Please go through pointers once before going to the interview.

 Many interviewers look for logic in your program rather than syntax. Once you write the program you should be able to explain the logic to the interviewer with the help of flow-chart or algorithm. If there are more than one logic for a single program, choose the logic that is simple and easy to understand at the same time it should efficient one.

Below are around 25 FAQ in C language. Try to answer these questions on your own. I believe that if you are able to answer these questions, you can easily get through the technical interview.



26.
FP_SEG And FP_OFF…
Sometimes while working with far pointers we need to break a far address into its segment and offset. In such situations we can use FP_SEG and FP_OFF macros. Following program illustrates the use of these two macros.
#include <dos.h>

main( )
{
unsigned s, o ;
char far *ptr = "Hello!" ;

s = FP_SEG ( ptr ) ;
o = FP_OFF ( ptr ) ;
printf ( "\n%u %u", s, o ) ;
}

-------------------------------------------------------------------------------------------------
27.

How do I write a program to convert a string containing number in a hexadecimal form to its equivalent decimal?
Ans: The following program demonstrates this:
main( )
{
char str[] = "0AB" ;
int h, hex, i, n ;
n = 0 ; h = 1 ;
for ( i = 0 ; h == 1 ; i++ )
{
if ( str[i] >= '0' && str[i] <= '9' )
hex = str[i] - '0' ;
else
{
if ( str[i] >= 'a' && str[i] <= 'f' )
hex = str[i] - 'a' + 10 ;
else
if ( str[i] >= 'A' && str[i] <= 'F' )
hex = str[i] - 'A' + 10 ;
else
h = 0 ;
}
if ( h == 1 )
n = 16 * n + hex ;
}
printf ( "\nThe decimal equivalent of %s is %d",
str, n ) ;
}
The output of this program would be the decimal equivalent of 0AB is 171.

-------------------------------------------------------------------------------------------------
28.

How do I write code that reads the segment register settings?

Ans: We can use segread( ) function to read segment register settings. There are four segment registers—code segment, data segment, stack segment and extra segment. Sometimes when we use DOS and BIOS services in a program we need to know the segment register's value. In such a situation we can use segread( ) function. The following program illustrates the use of this function.
#include <dos.h>
main( )
{
struct SREGS s ;
segread ( &s ) ;
printf ( "\nCS: %X DS: %X SS: %X ES: %X",s.cs,
s.ds, s.ss, s.es ) ;
}

-------------------------------------------------------------------------------------------------
29.

What is environment and how do I get environment for a specific entry?

Ans: While working in DOS, it stores information in a memory region called environment. In this region we can place configuration settings such as command path, system prompt, etc. Sometimes in a program we need to access the information contained in environment. The function getenv( ) can be used when we want to access environment for a specific entry. Following program demonstrates the use of this function.
#include <stdio.h>
#include <stdlib.h>

main( )
{
char *path = NULL ;

path = getenv ( "PATH" ) ;
if ( *path != NULL )
printf ( "\nPath: %s", path ) ;
else
printf ( "\nPath is not set" ) ;
}

-------------------------------------------------------------------------------------------------
30.

How do I display current date in the format given below?

Saturday October 12, 2002
Ans: Following program illustrates how we can display date in above given format.

#include <stdio.h>
#include <time.h>

main( )
{
struct tm *curtime ;
time_t dtime ;

char str[30] ;

time ( &dtime ) ;
curtime = localtime ( &dtime ) ;
strftime ( str, 30, "%A %B %d, %Y", curtime ) ;

printf ( "\n%s", str ) ;
}
Here we have called time( ) function which returns current time. This time is returned in terms of seconds, elapsed since 00:00:00 GMT, January 1, 1970. To extract the week day, day of month, etc. from this value we need to break down the value to a tm structure. This is done by the function localtime( ). Then we have called strftime( ) function to format the time and store it in a string str.

--------------------------------------------------------------------

31.

If we have declared an array as global in one file and we are using it in another file then why doesn't the sizeof operator works on an extern array?

Ans: An extern array is of incomplete type as it does not contain the size. Hence we cannot use sizeof operator, as it cannot get the size of the array declared in another file. To resolve this use any of one the following two solutions:
1. In the same file declare one more variable that holds the size of array. For example,

array.c

int arr[5] ;
int arrsz = sizeof ( arr ) ;

myprog.c

extern int arr[] ;
extern int arrsz ;
2. Define a macro which can be used in an array
declaration. For example,

myheader.h

#define SZ 5

array.c

#include "myheader.h"
int arr[SZ] ;

myprog.c

#include "myheader.h"
extern int arr[SZ] ;

-------------------------------------------------------------------------------------------------

32.

How do I write printf( ) so that the width of a field can be specified at runtime?

Ans: This is shown in following code snippet.

main( )
{
int w, no ;
printf ( "Enter number and the width for the
number field:" ) ;
scanf ( "%d%d", &no, &w ) ;
printf ( "%*d", w, no ) ;
}
Here, an '*' in the format specifier in printf( ) indicates that an int value from the argument list should be used for the field width.

-------------------------------------------------------------------------------------------------
33.

How to find the row and column dimension of a given 2-D array?

Ans: Whenever we initialize a 2-D array at the same place where it has been declared, it is not necessary to mention the row dimension of an array. The row and column dimensions of such an array can be determined programmatically as shown in following program.

void main( )
{
int a[][3] = { 0, 1, 2,
9,-6, 8,
7, 5, 44,
23, 11,15 } ;

int c = sizeof ( a[0] ) / sizeof ( int ) ;
int r = ( sizeof ( a ) / sizeof ( int ) ) / c ;
int i, j ;

printf ( "\nRow: %d\nCol: %d\n", r, c ) ;
for ( i = 0 ; i < r ; i++ )
{
for ( j = 0 ; j < c ; j++ )
printf ( "%d ", a[i][j] ) ;
printf ( "\n" ) ;
}
}

-------------------------------------------------------------------------------------------------
34.

The access( ) function...

The access( ) function checks for the existence of a file and also determines whether it can be read, written to or executed. This function takes two arguments the filename and an integer indicating the access mode. The values 6, 4, 2, and 1 checks for read/write, read, write and execute permission of a given file, whereas value 0 checks whether the file exists or not. Following program demonstrates how we can use access( ) function to check if a given file exists.

#include <io.h>

main( )
{
char fname[67] ;

printf ( "\nEnter name of file to open" ) ;
gets ( fname ) ;

if ( access ( fname, 0 ) != 0 )
{
printf ( "\nFile does not exist." ) ;
return ;
}
}


-------------------------------------------------------------------------------------------------
35.

How do I convert a floating-point number to a string?

Ans: Use function gcvt( ) to convert a floating-point number to a string. Following program demonstrates the use of this function.
#include <stdlib.h>

main( )
{
char str[25] ;
float no ;
int dg = 5 ; /* significant digits */

no = 14.3216 ;
gcvt ( no, dg, str ) ;
printf ( "String: %s\n", str ) ;
}


36.
What is a stack ?

Ans: The stack is a region of memory within which our programs temporarily store data as they execute. For example, when a program passes parameters to functions, C places the parameters on the stack. When the function completes, C removes the items from the stack. Similarly, when a function declares local variables, C stores the variable's values on the stack during the function's execution. Depending on the program's use of functions and parameters, the amount of stack space that a program requires will differ.


-------------------------------------------------------------------------------------------------
37.
Allocating memory for a 3-D array

#include "alloc.h"
#define MAXX 3
#define MAXY 4
#define MAXZ 5
main( )
{
int ***p, i, j, k ;
p = ( int *** ) malloc ( MAXX * sizeof ( int ** ) ) ;
for ( i = 0 ; i < MAXX ; i++ )
{
p[i] = ( int ** ) malloc ( MAXY * sizeof ( int * ) ) ;
for ( j = 0 ; j < MAXY ; j++ )
p[i][j] = ( int * ) malloc ( MAXZ * sizeof ( int ) ) ;
}
for ( k = 0 ; k < MAXZ ; k++ )
{
for ( i = 0 ; i < MAXX ; i++ )
{
for ( j = 0 ; j < MAXY ; j++ )
{
p[i][j][k] = i + j + k ;
printf ( "%d ", p[i][j][k] ) ;
}
printf ( "\n" ) ;
}
printf ( "\n\n" ) ;
}
}
Data Structures
How to distinguish between a binary tree and a tree?

Ans: A node in a tree can have any number of branches. While a binary tree is a tree structure in which any node can have at most two branches. For binary trees we distinguish between the subtree on the left and subtree on the right, whereas for trees the order of the subtrees is irrelevant.
Consider the following figure...

This above figure shows two binary trees, but these binary trees are different. The first has an empty right subtree while the second has an empty left subtree. If the above are regarded as trees (not the binary trees), then they are same despite the fact that they are drawn differently. Also, an empty binary tree can exist, but there is no tree having zero nodes.


-------------------------------------------------------------------------------------------------
38.
How do I use the function ldexp( ) in a program?

Ans: The math function ldexp( ) is used while solving the complex mathematical equations. This function takes two arguments, a double value and an int respectively. The order in which ldexp( ) function performs calculations is ( n * pow ( 2, exp ) ) where n is the double value and exp is the integer. The following program demonstrates the use of this function.

#include <stdio.h>
#include <math.h>

void main( )
{
double ans ;
double n = 4 ;

ans = ldexp ( n, 2 ) ;
printf ( "\nThe ldexp value is : %lf\n", ans ) ;
}
Here, ldexp( ) function would get expanded as ( 4 * 2 * 2 ), and the output would be the ldexp value is : 16.000000


-------------------------------------------------------------------------------------------------

39.
Can we get the mantissa and exponent form of a given number?

Ans: The function frexp( ) splits the given number into a mantissa and exponent form. The function takes two arguments, the number to be converted as a double value and an int to store the exponent form. The function returns the mantissa part as a double value. Following example demonstrates the use of this function.

#include <math.h>
#include <stdio.h>

void main( )
{
double mantissa, number ;
int exponent ;

number = 8.0 ;
mantissa = frexp ( number, &exponent ) ;

printf ( "The number %lf is ", number ) ;
printf ( "%lf times two to the ", mantissa ) ;
printf ( "power of %d\n", exponent ) ;

return 0 ;
}
-------------------------------------------------------------------------------------------------
40.

How do I write code that executes certain function only at program termination?
Ans: Use atexit( ) function as shown in following program.

#include <stdlib.h>
main( )
{
int ch ;
void fun ( void ) ;
atexit ( fun ) ;
// code
}
void fun( void )
{
printf ( "\nTerminate program......" ) ;
getch( ) ;
}


-------------------------------------------------------------------------------------------------
41.
What are memory models?
Ans: The compiler uses a memory model to determine how much memory is allocated to the program. The PC divides memory into blocks called segments of size 64 KB. Usually, program uses one segment for code and a second segment for data. A memory model defines the number of segments the compiler can use for each. It is important to know which memory model can be used for a program. If we use wrong memory model, the program might not have enough memory to execute. The problem can be solved using larger memory model. However, larger the memory model, slower is your program execution. So we must choose the smallest memory model that satisfies our program needs. Most of the compilers support memory models like tiny, small, medium, compact, large and huge.

42.
How does C compiler store elements in a multi-dimensional array?

Ans: The compiler maps multi-dimensional arrays in two ways—Row major order and Column order. When the compiler places elements in columns of an array first then it is called column-major order. When the compiler places elements in rows of an array first then it is called row-major order. C compilers store multidimensional arrays in row-major order. For example, if there is a multi-dimensional array a[2][3], then according row-major order, the elements would get stored in memory following order:
a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2]


-------------------------------------------------------------------------------------------------
43.

If the result of an _expression has to be stored to one of two variables, depending on a condition, can we use conditional operators as shown below?

( ( i < 10 ) ? j : k ) = l * 2 + p ;
Ans: No! The above statement is invalid. We cannot use the conditional operators in this fashion. The conditional operators like most operators, yields a value, and we cannot assign the value of an _expression to a value. However, we can use conditional operators as shown in following code snippet.

main( )
{
int i, j, k, l ;
i = 5 ; j = 10 ; k = 12, l = 1 ;
* ( ( i < 10 ) ? &j : &k ) = l * 2 + 14 ;
printf ( "i = %d j = %d k = %d l = %d", i, j, k, l ) ;
}

The output of the above program would be as given below:
i = 5 j = 16 k = 12 l = 1

-------------------------------------------------------------------------------------------------
44.

How can I find the day of the week of a given date?

Ans: The following code snippet shows how to get the day of week from the given date.

dayofweek ( int yy, int mm, int dd )
{
/*Monday = 1 and Sunday = 0 */
/* month number >= 1 and <= 12, yy > 1752 or so */
static int arr[ ] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 } ;
yy = yy - mm < 3 ;
return ( yy + yy / 4 - yy / 100 + yy / 400 + arr[ mm - 1] + dd ) % 7 ;
}

void main( )
{
printf ( "\n\n\nDay of week : %d ", dayofweek ( 2002, 5, 18 ) ) ;
}

-------------------------------------------------------------------------------------------------

 

 

45.

What's the difference between these two declarations?

struct str1 { ... } ;
typedef struct { ... } str2 ;
Ans : The first form declares a structure tag whereas the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type -- its users don't necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it.

-------------------------------------------------------------------------------------------------
46.

How do I print the contents of environment variables?

Ans:. The following program shows how to achieve this:
main( int argc, char *argv[ ], char *env[ ] )
{
int i = 0 ;
clrscr( ) ;
while ( env[ i ] )
printf ( "\n%s", env[ i++ ] ) ;
}

main( ) has the third command line argument env, which is an array of pointers to the strings. Each pointer points to an environment variable from the list of environment variables.

-------------------------------------------------------------------------------------------------
47.
div( )...

The function div( ) divides two integers and returns the quotient and remainder. This function takes two integer values as arguments; divides first integer with the second one and returns the answer of division of type div_t. The data type div_t is a structure that contains two long ints, namely quot and rem, which store quotient and remainder of division respectively. The following example shows the use of div( ) function.

#include <stdlib.h>
void main( )
{
div_t res ;

res = div ( 32, 5 ) ;
printf ( "\nThe quotient = %d and remainder = %d ", res.quot, res.rem ) ;
}

-------------------------------------------------------------------------
48.
What would the second and the third printf( ) output the following program?

main( )
{
char *str[ ] = {
"Good Morning"
"Good Evening"
"Good Afternoon"
} ;
printf ( "\nFirst string = %s", str[0] ) ;
printf ( "\nSecond string = %s", str[1] ) ;
printf ( "\nThird string = %s", str[2] ) ;
}
Ans: For the above given program, we expect the output as Good Evening and Good Afternoon, for the second and third printf( ). However, the output would be as shown below.

First string = Good MorningGood EveningGood Afternoon
Second string = ( null )
Third string =

What is missing in the above given code snippet is a comma separator which should separate the strings Good Morning, Good Evening and Good Afternoon. On adding comma, we would get the output as shown below.

First string = Good Morning
Second string = Good Evening
Third string = Good Afternoon

-------------------------------------------------------------------------------------------------
49.

How do I use scanf( ) to read the date in the form 'dd-mm-yy' ?
Ans: There are two ways to read the date in the form of 'dd-mm-yy' one possible way is...

int dd, mm, yy ;
char ch ; /* for char '-' */
printf ( "\nEnter the date in the form of dd-mm-yy : " ) ;
scanf( "%d%c%d%c%d", &dd, &ch, &mm, &ch, &yy ) ;

And another best way is to use suppression character * as...

int dd, mm, yy ;
scanf( "%d%*c%d%*c%d", &dd, &mm, &yy ) ;

The suppression character * suppresses the input read from the standard input buffer for the assigned control character.

-------------------------------------------------------------------------------------------------
50.

How do I print a floating-point number with higher precision say 23.34568734 with only precision up to two decimal places?

Ans: This can be achieved through the use of suppression char '*' in the format string of printf( ) as shown in the following program.
main( )
{
int i = 2 ;
float f = 23.34568734 ;
printf ( "%.*f", i, f ) ;
}
The output of the above program would be 23.35.





ANish

C Objective Questions and Answers

C Objective Questions and Answers

=============================================================


=============================================================
 C is interviewer’s favorite language. If you have good command on C language you can get through Technical Interview easily. Most of the interviewers ask basic questions in C. Some times they may ask you to write small programs like reversal of a string, determining whether the given number is a palindrome or not and finding factorial of a given number using recursion etc. You should be able to write these programs quickly.

 Most favorite question for interviewers is interchanging two variables with out using the third variable. Another favorite topic for interviewers is Pointers. Please go through pointers once before going to the interview.

 Many interviewers look for logic in your program rather than syntax. Once you write the program you should be able to explain the logic to the interviewer with the help of flow-chart or algorithm. If there are more than one logic for a single program, choose the logic that is simple and easy to understand at the same time it should efficient one.

Below are around 50 FAQ in C language. Try to answer these questions on your own. I believe that if you are able to answer these questions, you can easily get through the technical interview.

1.

What will be the output of the following code?

void main ()
{ int i = 0 , a[3] ;
a[i] = i++;
printf (“%d",a[i]) ;
}
Ans: The output for the above code would be a garbage value. In the statement a[i] = i++; the value of the variable i would get assigned first to a[i] i.e. a[0] and then the value of i would get incremented by 1. Since a[i] i.e. a[1] has not been initialized, a[i] will have a garbage value.





-------------------------------------------------------------------------------------------------
2.

Why doesn't the following code give the desired result?

int x = 3000, y = 2000 ;
long int z = x * y ;
Ans: Here the multiplication is carried out between two ints x and y, and the result that would overflow would be truncated before being assigned to the variable z of type long int. However, to get the correct output, we should use an explicit cast to force long arithmetic as shown below:

long int z = ( long int ) x * y ;
Note that ( long int )( x * y ) would not give the desired effect.




-------------------------------------------------------------------------------------------------
3.

Why doesn't the following statement work?

char str[ ] = "Hello" ;
strcat ( str, '!' ) ;
Ans: The string function strcat( ) concatenates strings and not a character. The basic difference between a string and a character is that a string is a collection of characters, represented by an array of characters whereas a character is a single character. To make the above statement work writes the statement as shown below:
strcat ( str, "!" ) ;





-------------------------------------------------------------------------------------------------
4.

How do I know how many elements an array can hold?

Ans: The amount of memory an array can consume depends on the data type of an array. In DOS environment, the amount of memory an array can consume depends on the current memory model (i.e. Tiny, Small, Large, Huge, etc.). In general an array cannot consume more than 64 kb. Consider following program, which shows the maximum number of elements an array of type int, float and char can have in case of Small memory model.
main( )
{
int i[32767] ;
float f[16383] ;
char s[65535] ;
}





-------------------------------------------------------------------------------------------------

5.

How do I write code that reads data at memory location specified by segment and offset?

Ans: Use peekb( ) function. This function returns byte(s) read from specific segment and offset locations in memory. The following program illustrates use of this function. In this program from VDU memory we have read characters and its attributes of the first row. The information stored in file is then further read and displayed using peek( ) function.

#include <stdio.h>
#include <dos.h>

main( )
{

char far *scr = 0xB8000000 ;
FILE *fp ;
int offset ;
char ch ;

if ( ( fp = fopen ( "scr.dat", "wb" ) ) == NULL )
{

printf ( "\nUnable to open file" ) ;
exit( ) ;

}

// reads and writes to file
for ( offset = 0 ; offset < 160 ; offset++ )
fprintf ( fp, "%c", peekb ( scr, offset ) ) ;
fclose ( fp ) ;

if ( ( fp = fopen ( "scr.dat", "rb" ) ) == NULL )
{

printf ( "\nUnable to open file" ) ;
exit( ) ;

}

// reads and writes to file
for ( offset = 0 ; offset < 160 ; offset++ )
{

fscanf ( fp, "%c", &ch ) ;
printf ( "%c", ch ) ;

}

fclose ( fp ) ;

}


6.
How do I compare character data stored at two different memory locations?

Ans: Sometimes in a program we require to compare memory ranges containing strings. In such a situation we can use functions like memcmp( ) or memicmp( ). The basic difference between two functions is that memcmp( ) does a case-sensitive comparison whereas memicmp( ) ignores case of characters. Following program illustrates the use of both the functions.

#include <mem.h>

main( )
{
char *arr1 = "Kicit" ;
char *arr2 = "kicitNagpur" ;

int c ;

c = memcmp ( arr1, arr2, sizeof ( arr1 ) ) ;

if ( c == 0 )
printf ( "\nStrings arr1 and arr2 compared using memcmp are identical" ) ;

else
printf ( "\nStrings arr1 and arr2 compared using memcmp are not identical"
) ;

c = memicmp ( arr1, arr2, sizeof ( arr1 ) ) ;

if ( c == 0 )
printf ( "\nStrings arr1 and arr2 compared using memicmp are identical" )
;
else
printf ( "\nStrings arr1 and arr2 compared using memicmp are not
identical" ) ;
}




-------------------------------------------------------------------------------------------------
7.
Fixed-size objects are more appropriate as compared to variable size data objects. Using variable-size data objects saves very little space. Variable size data objects usually have some overhead. Manipulation of fixed-size data objects is usually faster and easier. Use fixed size when maximum size is clearly bounded and close to average. And use variable-size data objects when a few of the data items are bigger than the average size. For example,

char *num[10] = { "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten" } ;

Instead of using the above, use

char num[10][6] = { "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten" } ;

The first form uses variable-size data objects. It allocates 10 pointers, which are pointing to 10 string constants of variable size. Assuming each pointer is of 4 bytes, it requires 90 bytes. On the other hand, the second form uses fixed size data objects. It allocates 10 arrays of 6 characters each. It requires only 60 bytes of space. So, the variable-size in this case does not offer any advantage over fixed size.



-------------------------------------------------------------------------------------------------
8.

The Spawnl( ) function...

DOS is a single tasking operating system, thus only one program runs at a time. The Spawnl( ) function provides us with the capability of starting the execution of one program from within another program. The first program is called the parent process and the second program that gets called from within the first program is called a child process. Once the second program starts execution, the first is put on hold until the second program completes execution. The first program is then restarted. The following program demonstrates use of spawnl( ) function.

/* Mult.c */

int main ( int argc, char* argv[ ] )
{
int a[3], i, ret ;
if ( argc < 3 || argc > 3 )
{
printf ( "Too many or Too few arguments..." ) ;
exit ( 0 ) ;
}

for ( i = 1 ; i < argc ; i++ )
a[i] = atoi ( argv[i] ) ;
ret = a[1] * a[2] ;
return ret ;
}

/* Spawn.c */
#include <process.h>
#include <stdio.h>

main( )
{
int val ;
val = spawnl ( P_WAIT, "C:\\Mult.exe", "3", "10",
"20", NULL ) ;
printf ( "\nReturned value is: %d", val ) ;
}

Here, there are two programs. The program 'Mult.exe' works as a child process whereas 'Spawn.exe' works as a parent process. On execution of 'Spawn.exe' it invokes 'Mult.exe' and passes the command-line arguments to it. 'Mult.exe' in turn on execution, calculates the product of 10 and 20 and returns the value to val in 'Spawn.exe'. In our call to spawnl( ) function, we have passed 6 parameters, P_WAIT as the mode of execution, path of '.exe' file to run as child process, total number of arguments to be passed to the child process, list of command line arguments and NULL. P_WAIT will cause our application to freeze execution until the child process has completed its execution. This parameter needs to be passed as the default parameter if you are working under DOS. under other operating systems that support multitasking, this parameter can be P_NOWAIT or P_OVERLAY. P_NOWAIT will cause the parent process to execute along with the child process, P_OVERLAY will load the child process on top of the parent process in the memory.


-------------------------------------------------------------------------------------------------
9.

Are the following two statements identical?

char str[6] = "Kicit" ;
char *str = "Kicit" ;
Ans: No! Arrays are not pointers. An array is a single, pre-allocated chunk of contiguous elements (all of the same type), fixed in size and location. A pointer on the other hand, is a reference to any data element (of a particular type) located anywhere. A pointer must be assigned to point to space allocated elsewhere, but it can be reassigned any time. The array declaration char str[6] ; requests that space for 6 characters be set aside, to be known
by name str. In other words there is a location named str at which six characters are stored. The pointer declaration char *str ; on the other hand, requests a place that holds a pointer, to be known by the name str. This pointer can point almost anywhere to any char, to any contiguous array of chars, or nowhere.


-------------------------------------------------------------------------------------------------
10.

Is the following code fragment correct?

const int x = 10 ;
int arr[x] ;
Ans: No! Here, the variable x is first declared as an int so memory is reserved for it. Then it is qualified by a const qualifier. Hence, const qualified object is not a constant fully. It is an object with read only attribute, and in C, an object associated with memory cannot be used in array dimensions.


11.

How do I write code to retrieve current date and time from the system and display it as a string?

Ans: Use time( ) function to get current date and time and then ctime( ) function to display it as a string. This is shown in following code snippet.

#include <sys\types.h>

void main( )
{
time_t curtime ;
char ctm[50] ;

time ( &curtime ) ; //retrieves current time &
stores in curtime
printf ( "\nCurrent Date & Time: %s", ctime (
&curtime ) ) ;
}

-------------------------------------------------------------------------------------------------
12.

How do I change the type of cursor and hide a cursor?

Ans: We can change the cursor type by using function _setcursortype( ). This function can change the cursor type to solid cursor and can even hide a cursor. Following code shows how to change the cursor type and hide cursor.

#include <conio.h>
main( )
{
/* Hide cursor */
_setcursortype ( _NOCURSOR ) ;

/* Change cursor to a solid cursor */
_setcursortype ( _SOLIDCURSOR ) ;

/* Change back to the normal cursor */
_setcursortype ( _NORMALCURSOR ) ;
}

-------------------------------------------------------------------------------------------------
13.

How do I write code that would get error number and display error message if any standard error occurs?

Ans: Following code demonstrates this.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

main( )
{
char *errmsg ;
FILE *fp ;
fp = fopen ( "C:\file.txt", "r" ) ;
if ( fp == NULL )
{
errmsg = strerror ( errno ) ;
printf ( "\n%s", errmsg ) ;
}
}
Here, we are trying to open 'file.txt' file. However, if the file does not exist, then it would cause an error. As a result, a value (in this case 2) related to the error generated would get set in errno. errno is an external int variable declared in 'stdlib.h' and also in 'errno.h'. Next, we have called sterror( ) function which takes an error number and returns a pointer to standard error message related to the given error number.


-------------------------------------------------------------------------------------------------
14.

How do I write code to get the current drive as well as set the current drive?

Ans: The function getdisk( ) returns the drive number of current drive. The drive number 0 indicates 'A' as the current drive, 1 as 'B' and so on. The Setdisk( ) function sets the current drive. This function takes one argument which is an integer indicating the drive to be set. Following program demonstrates use of both the functions.

#include <dir.h>

main( )
{
int dno, maxdr ;

dno = getdisk( ) ;
printf ( "\nThe current drive is: %c\n", 65 + dno
) ;

maxdr = setdisk ( 3 ) ;
dno = getdisk( ) ;
printf ( "\nNow the current drive is: %c\n", 65 +
dno ) ;
}


-------------------------------------------------------------------------------------------------
15.

The functions memcmp( ) and memicmp( )

The functions memcmp( ) and memicmp( ) compares first n bytes of given two blocks of memory or strings. However, memcmp( ) performs comparison as unsigned chars whereas memicmp( ) performs comparison as chars but ignores case (i.e. upper or lower case). Both the functions return an integer value where 0 indicates that two memory buffers compared are identical. If the value returned is greater than 0 then it indicates that the first buffer is bigger than the second one. The value less than 0 indicate that the first buffer is less than the second buffer. The following code snippet demonstrates use of both

#include <stdio.h>
#include <mem.h>

main( )
{
char str1[] = "This string contains some
characters" ;
char str2[] = "this string contains" ;
int result ;

result = memcmp ( str1, str2, strlen ( str2 ) ) ;
printf ( "\nResult after comapring buffer using
memcmp( )" ) ;
show ( result ) ;

result = memicmp ( str1, str2, strlen ( str2 ) ) ;
printf ( "\nResult after comapring buffer using
memicmp( )" ) ;
show ( result ) ;
}

show ( int r )
{
if ( r == 0 )
printf ( "\nThe buffer str1 and str2 hold
identical data" ) ;
if ( r > 0 )
printf ( "\nThe buffer str1 is bigger than buffer
str2" ) ;
if ( r < 0 )
printf ( "\nThe buffer str1 is less than buffer
str2" ) ;
}


-------------------------------------------------------------------------------------------------

16.

How do I write code to find an amount of free disk space available on current drive?

Ans: Use getdfree( ) function as shown in follow code.

#include <stdio.h>
#include <stdlib.h>
#include <dir.h>
#include <dos.h>

main( )
{
int dr ; struct dfree disk ;
long freesp ;

dr = getdisk( ) ;
getdfree ( dr + 1 , &disk ) ;

if ( disk.df_sclus == 0xFFFF )
{
printf ( "\ngetdfree( ) function failed\n");
exit ( 1 ) ;
}

freesp = ( long ) disk.df_avail
* ( long ) disk.df_bsec
* ( long ) disk.df_sclus ;
printf ( "\nThe current drive %c: has %ld bytes
available as free space\n", 'A' + dr, freesp ) ;
}


--------------------------------------------------------------------
17.

Use of array indices...
If we wish to store a character in a char variable ch and the character to be stored depends on the value of another variable say color (of type int), then the code would be as shown below:

switch ( color )
{
case 0 :
ch = 'R' ;
break ;
case 1 :
ch = 'G' ;
break ;
case 2 :
ch = 'B' ;
break ;
}
In place of switch-case we can make use of the value in color as an index for a character array. How to do this is shown in following code snippet.

char *str = "RGB' ;
char ch ;
int color ;
// code
ch = str[ color ] ;

-------------------------------------------------------------------------------------------------
18.

Function atexit( ) recevies parameter as the address of function of the type void fun ( void ). The function whose address is passed to atexit( ) gets called before the termination of program. If atexit( ) is called for more than one function then the functions are called in "first in last out" order. You can verify that from the output.

#include <stdio.h>
#include <stdlib.h>
void fun1( )
{
printf("Inside fun1\n");
}

void fun2( )
{
printf("Inside fun2\n");
}
main( )
{
atexit ( fun1 ) ;
/* some code */
atexit ( fun2 ) ;
printf ( "This is the last statement of
program?\n" );
}

-------------------------------------------------------------------------------------------------

19.

How do I write a user-defined function, which deletes each character in a string str1, which matches any character in string str2?

Ans: The function is as shown below:

Compress ( char str1[], char str2[] )
{
int i, j, k ;

for ( i = k = 0 ; str1[i] != ‘\0’ ; i++ )
{
for ( j = 0 ; str2[j] != ‘\0’ && str2[j] !=
str1[i] ; j++ )
;
if ( str2[j] == ‘\0’ )
str1[k++] = str1[I] ;
}
str1[k] = ‘\0’
}


-------------------------------------------------------------------------------------------------

20.

How does free( ) know how many bytes to free?

Ans: The malloc( ) / free( ) implementation remembers the size of each block allocated and returned, so it is not necessary to remind it of the size when freeing.
-------------------------------------------------------------------------------------------------
21.

What is the use of randomize( ) and srand( ) function?

Ans: While generating random numbers in a program, sometimes we require to control the series of numbers that random number generator creates. The process of assigning the random number generators starting number is called seeding the generator. The randomize( ) and srand( ) functions are used to seed the random number generators. The randomize( ) function uses PC's clock to produce a random seed, whereas the srand( ) function allows us to specify the random number generator's starting value.


-------------------------------------------------------------------------------------------------
22.

How do I determine amount of memory currently available for allocating?

Ans: We can use function coreleft( ) to get the amount of memory available for allocation. However, this function does not give an exact amount of unused memory. If, we are using a small memory model, coreleft( ) returns the amount of unused memory between the top of the heap and stack. If we are using a larger model, this function returns the amount of memory between the highest allocated memory and the end of conventional memory. The function returns amount of memory in terms of bytes.


-------------------------------------------------------------------------------------------------
23.

How does a C program come to know about command line arguments?

Ans: When we execute our C program, operating system loads the program into memory. In case of DOS, it first loads 256 bytes into memory, called program segment prefix. This contains file table, environment segment, and command line information. When we compile the C program the compiler inserts additional code that parses the command, assigning it to the argv array, making the arguments easily accessible within our C program.

-------------------------------------------

24.

When we open a file, how does functions like fread( )/fwrite( ), etc. get to know from where to read or to write the data?

Ans: When we open a file for read/write operation using function like fopen( ), it returns a pointer to the structure of type FILE. This structure stores the file pointer called position pointer, which keeps track of current location within the file. On opening file for read/write operation, the file pointer is set to the start of the file. Each time we read/write a character, the position pointer advances one character. If we read one line of text at a step from the file, then file pointer advances to the start of the next line. If the file is opened in append mode, the file pointer is placed at the very end of the file. Using fseek( ) function we can set the file pointer to some other place within the file.


-------------------------------------------------------------------------------------------------

 

25.

The sizeof( ) function doesn’t return the size of the block of memory pointed to by a pointer. Why?

Ans: The sizeof( ) operator does not know that malloc( ) has been used to allocate a pointer. sizeof( ) gives us the size of pointer itself. There is no handy way to find out the size of a block allocated by malloc( ).


-------------------------------------------------------------------------------------------------


ANish

Wednesday, November 17, 2010

configuring security domains for authentication and authorization in JBoss

configuring security domains for authentication and authorization in JBoss
Securing Ejb Using JBOSS
EJB Security in JBOSS or securing Web Application in JBOSS
Setup security-domain For JBoss

=============================================================



=============================================================

To enable security in the JBoss application server, you need to create a security domain .
A security domain is a repository for users, passwords, and the roles with which each user is associated.
The EJB container delegates to the security domain when performing authentication and authorization



============================================================
Security domains are configured in the
jboss/server/default/conf/login-config.xml
Add the following entry in under the Poplict Tag

<application-policy name="testSecurityDomain">
  <authentication>
      <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"     flag = "required">
         <module-option name="usersProperties">
                   users.properties
         </module-option>
         <module-option name="rolesProperties">
                   roles.properties
         </module-option>
      </login-module>
  </authentication>
</application-policy>




The user-test.properties files
users.properties
anish=anish
nath=nath



roles-test.properties
wburke=AUTHORIZED
richard=UNAUTHORIZED



-----
The Bean Class
@Stateless
@SecurityDomain("testSecurityDomain")  //Configured in
login-config.xml
@RolesAllowed("AUTHORIZED")

public class TestBean implements TestBeanRemote,
                                           TestBeanLocal
{

@RolesAllowed({"AUTHORIZED", "CHECK_FRAUD_ENABLED"})
public voidsayHello(){}   
}


@PermitAll
public voidsayHelloWorld(){}   
}

}

}


=====================================
The client Class will hold the following information
Properties env = new Properties( );
env.setProperty(Context.SECURITY_PRINCIPAL, "anish");
env.setProperty(Context.SECURITY_CREDENTIALS, "anish");
env.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.jboss.security.jndi.JndiLoginInitialContextFactory");



---------------------------------------
Configure JBoss Security
------------------------------------
ANish

Tuesday, October 19, 2010

Java Exception Chaining

public void printStackTrace()


=============================================================

=============================================================

Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace(). The format of this information depends on the implementation, but the following example may be regarded as typical:


=============================================================

=============================================================
java.lang.NullPointerException
at MyClass.mash(MyClass.java:9)
at MyClass.crunch(MyClass.java:6)
at MyClass.main(MyClass.java:3)


This example was produced by running the program:

class MyClass {
public static void main(String[] args) {
crunch(null);
}
static void crunch(int[] a) {
mash(a);
}
static void mash(int[] b) {
System.out.println(b[0]);
}
}


=============================================================

=============================================================

The backtrace for a throwable with an initialized, non-null cause should generally include the backtrace for the cause. The format of this information depends on the implementation, but the following example may be regarded as typical:

HighLevelException: MidLevelException: LowLevelException
at Junk.a(Junk.java:13)
at Junk.main(Junk.java:4)
Caused by: MidLevelException: LowLevelException
at Junk.c(Junk.java:23)
at Junk.b(Junk.java:17)
at Junk.a(Junk.java:11)
... 1 more
Caused by: LowLevelException
at Junk.e(Junk.java:30)
at Junk.d(Junk.java:27)
at Junk.c(Junk.java:21)
... 3 more


Note the presence of lines containing the characters "...". These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught. The above example was produced by running the program:

public class Junk {
public static void main(String args[]) {
try {
a();
} catch(HighLevelException e) {
e.printStackTrace();
}
}
static void a() throws HighLevelException {
try {
b();
} catch(MidLevelException e) {
throw new HighLevelException(e);
}
}
static void b() throws MidLevelException {
c();
}
static void c() throws MidLevelException {
try {
d();
} catch(LowLevelException e) {
throw new MidLevelException(e);
}
}
static void d() throws LowLevelException {
e();
}
static void e() throws LowLevelException {
throw new LowLevelException();
}
}

class HighLevelException extends Exception {
HighLevelException(Throwable cause) { super(cause); }
}

class MidLevelException extends Exception {
MidLevelException(Throwable cause) { super(cause); }
}

class LowLevelException extends Exception {
}


=============================================================

=============================================================

Tuesday, October 12, 2010

JBOSS Clustering

JBOSS JMS clustering
----------------------


=============================================================



=============================================================
run.bat -c node1 -g PartitionA -u 239.255.100.100 -b localhost -Djboss.messaging.ServerPeerID=1
run.bat -c node2 -g PartitionB -u 239.255.100.100 -b localhost -Djboss.messaging.ServerPeerID=2

=============================================================



=============================================================
JBoss Messaging clusters JMS queues and topics transparently  across the cluster. Messages sent to
a distributed queue or topic on one node are consumable on other nodes. To designate that a particular destination is clustered, simply set the Clustered attribute in the destination deployment descriptor to true:
=============================================================



=============================================================
<mbean code="org.jboss.jms.server.destination.QueueService"
name="jboss.messaging.destination:service=Queue,name=clusteredQueue"
xmbean-dd="xmdesc/Queue-xmbean.xml">
<depends optional-attribute-name="ServerPeer">
jboss.messaging:service=ServerPeer
</depends>
<depends>jboss.messaging:service=PostOffice</depends>
<attribute name="Clustered">true</attribute>
</mbean>
=============================================================
 

=============================================================
Configuring EJB 3.0 Stateful Session Bean cache
The @org.jboss.ejb3.annotation.CacheConfig Annotation

@Stateful
@Clustered
@CacheConfig(name="new-sfsb-cache")
@Remote(StatefulRemote.class)

Configuring entity caching

<properties>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.region.factory_class"
value="org.hibernate.cache.jbc2.JndiMultiplexedJBossCacheRegionFactory"/>
<property name="hibernate.cache.region.jbc2.cachefactory" value="java:CacheManager"/>
<property name="hibernate.cache.region.jbc2.cfg.entity" value="mvcc-entity"/>
<property name="hibernate.cache.region.jbc2.cfg.collection" value="mvcc-entity"/>
</properties>



=============================================================



=============================================================

import javax.persistence.*;
import org.hibernate.annotations.*;
@Entity
@Cache (usage=CacheConcurrencyStrategy.TRANSACTIONAL)
public class ProductEntity implements Serializable {
}
Refer
//deploy\cluster\jboss-cache-manager.sar\META-INF\jboss-cache-configs.xml & jboss-cache-manager-jboss-beans.xml

=============================================================
 

=============================================================
Clustering web applications

Configuring HTTP replication

In web.xml add adding the<distributable /> tag

<web-app>
. . . . .
<distributable />
</web-app>

Refer :jbossweb.deployer\META-INF\war-deployers-jboss-beans.xml

The jboss-web.xml

<!DOCTYPE jboss-web PUBLIC
-//JBoss//DTD Web Application 5.0//EN
http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd>
<jboss-web>
<replication-config>
<cache-name>custom-web-cache</cache-name>
<replication-trigger>SET</replication-trigger>
<replication-granularity>ATTRIBUTE</replication-granularity>
<max-unreplicated-interval>30</max-unreplicated-interval>
<snapshot-mode>instant</snapshot-mode>
<snapshot-interval>1000</snapshot-interval>
</replication-config>
</jboss-web>


=============================================================
 

=============================================================

Jboss  clustering Example
Clustering Web Using Jboss
JMS Clustering Example
Running Jboss in Clustering Mode

--
Anish

Thursday, October 7, 2010

JtaTransactionManager Bean

JtaTransactionManager Bean
=============================================================
 


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
...
<bean id="jtaTransactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager"/>
...
</beans>

By default, the JtaTransactionManager will attempt to automatically detect a UserTransaction
bound to the java:comp/UserTransaction JNDI name; if the java:comp/UserTransaction object also
implements the TransactionManager, the JtaTransactionManager will use that; if the java:comp/
UserTransaction does not implement the TransactionManager, the JtaTransactionManager will attempt
to find the TransactionManager under these JNDI names:
  1. • java:comp/UserTransaction: The default JNDI name, used by Resin 2.x, Oracle OC4J (Orion),
  2. JOnAS (JOTM), BEA WebLogic, and IBM WebSphere
  3. • java:pm/TransactionManager: JNDI name for TransactionManager in Borland Enterprise Server and Sun Application Server (Sun ONE 7 and later)
  4. • java:comp/TransactionManager: JNDI name used in Resin 3.x
  5. • java:/TransactionManager: The name used in the JBoss Application Server

===========================================================================================



jtatransactionmanager example
jtatransactionmanager spring example
jtatransactionmanager hibernate
ANish

Thursday, September 23, 2010

REST Authentication and Authorization example

Authentication and Authorization in JAX-RS
REST Authentication and Authorization example

Folder Structure

 

example Programe
=============================================================
 

package com.test;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import org.jboss.resteasy.annotations.Form;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
/**
 *
 * @author NathA1
Spring will use any class annotated with the @Controller annotation as
a Controller in Spring MVC support
The @Produces is used to map a client request and match it up to the client's Accept header.
The Accept HTTP header is sent by the client and defines the media types the client prefers to
receive from the server
 */
@RolesAllowed({"admin","tomcat"})
@Controller
@Path(ProductsResource.CONTACTS_URL)
public class ProductsResource
{
   public static final String CONTACTS_URL = "/products";
   @Autowired
   ProductService service;

   @RolesAllowed("admin")
   @GET
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data")
   public Products getAll()
   {
      return service.getAll();
   }

   @PermitAll
   @PUT
   @POST
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data")
   public Response saveProduct(@Context UriInfo uri, Product product)
         throws URISyntaxException
   {
       System.out.println("Inside -->> saveProduct");
      service.save(product);
      URI newURI = UriBuilder.fromUri(uri.getPath()).path(product.getLongName()).build();
      return Response.created(newURI).build();
   }

   @RolesAllowed("tomcat")
   @GET
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data/{shortName}")
   public Product get(@PathParam("shortName") String shortName)
   {
      return service.getProduct(shortName);
   }

   @PermitAll
   @POST
   @PUT
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   @Produces(MediaType.TEXT_HTML)
   public ModelAndView saveContactForm(@Form Product product)
         throws URISyntaxException
   {
       System.out.println("Inside -->> saveContactForm");
      service.save(product);
      return viewAll();
   }
  

   @PermitAll
   @GET
   @Produces(MediaType.TEXT_HTML)
   public ModelAndView viewAll()
   {
      // forward to the "contacts" view, with a request attribute named
      // "contacts" that has all of the existing contacts
      return new ModelAndView("products", "products", service.getAll());
   }
}
/**
 * END OF PROGRAM
 * =======================================================================
package com.test;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
When a class is annotated with a @XmlRootElement annotation, RESTEasy
will select the JAXBXmlRootElementProvider. This provider handles basic marhaling and and
unmarshalling of custom JAXB entities
@author Anish Nath
 *
 */

@XmlRootElement
public class Products
{
   private Collection<Product> products;
   public Products()
   {
      this.products = new ArrayList<Product>();
   }
   public Products(Collection<Product> products)
   {
      this.products = products;
   }
   /**
    *  @XmlElement annotation to embed other JAXB-annotated classes.
    * @return
    */
   @XmlElement(name="product")
   public Collection<Product> getProducts()
   {
      return products;
   }
   public void setProducts(Collection<Product> product)
   {
      
      this.products = product;
   }
}

/**
 * END OF PROGRAM
 * =======================================================================
 */
package com.test;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Service;
/**
 *
 * Anish Nath
The @Service annotation marks classes that implement a part of the business
logic of the application
 *
 */
@Service
public class ProductService
{
   private Map<String, Product> productMap = new ConcurrentHashMap<String, Product>();
   public void save(Product product)
   {
       productMap.put(product.getShortName(), product);
   }
   public Product getProduct(String shortName)
   {
      return productMap.get(shortName);
   }
   public Products getAll()
   {
      return new Products(productMap.values());
   }
}

/**
 * END OF PROGRAM
 * =======================================================================
 */
 Web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/products/*</url-pattern>
    </servlet-mapping>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>product creation</web-resource-name>
            <url-pattern>/products</url-pattern>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>admin</role-name>
        </auth-constraint>
    </security-constraint>
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>jaxrs</realm-name>
    </login-config>
    <security-role>
        <role-name>admin</role-name>
    </security-role>

</web-app>

==========================================================================
springmvc-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    ">
    <context:component-scan base-package="com.test" />
    <context:annotation-config />
    <import resource="classpath:springmvc-resteasy.xml" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>


==========================================================================================
tomcat-users.xml
<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
  <role rolename="manager"/>
  <role rolename="tomcat"/>
  <role rolename="admin"/>
  <role rolename="role1"/>
  <user password="tomcat" roles="tomcat,role1" username="both"/>
  <user password="tomcat" roles="tomcat" username="tomcat"/>
  <user password="admin" roles="admin,manager" username="admin"/>
  <user password="tomcat" roles="role1" username="role1"/>
</tomcat-users>
===========================================================================================

spring rest services
spring rest example

RESTfull web service Example
restlet spring security
RestEasy with EJB Integration Example
RESTEasy and Spring MVC

ANish