Sunday, October 14, 2007

JAVA JDBC QUESTIONS

1. What's the JDBC 2.0 API?

A) The JDBC 2.0 API is the latest update of the JDBC API. It contains many new features, including scrollable result sets and the new SQL:1999 (formerly SQL 3) data types. There are two parts to the JDBC 2.0 API:
the JDBC 2.0 core API (the java.sql package), which is included in the JavaTM 2 SDK, Standard Edition
the JDBC 2.0 Optional Package API (the javax.sql package), which is available separately or as part of the Java 2 SDK, Enterprise Edition


2. Does the JDBC-ODBC Bridge support the new features in the JDBC 2.0 API?

No, the JDBC-ODBC Bridge that is included in the Java 2 Platform initial release does not support the new features in the JDBC 2.0 API. However, Sun and Merant are working to produce a new version of the Bridge that does support the new features. Note that we do not recommend using the Bridge except for experimental purposes or when you have no other driver available.

3. Can the JDBC-ODBC Bridge be used with applets?

A) Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security reasons. This is good because it means that an untrusted applet that is downloaded by the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called, the Java programming language can't guarantee that a security violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not require any client-side configuration.
Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be run in appletviewer since appletviewer assumes that applets are trusted. It is also possible to use the JDBC-ODBC bridge with applets that are run in the HotJavaTM browser (available from Java Software), since HotJava provides an option to turn off applet security. In general, it is dangerous to turn applet security off, but it may be appropriate in certain controlled situations, such as for applets that will only be used in a secure intranet environment. Remember to exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to avoid security problems.

4. How do I start debugging problems related to the JDBC API?

A) A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system that is related to JDBC operations.
If you use the DriverManager facility to establish your database connection, you use the DriverManager.setLogWriter method to enable tracing of JDBC operations. If you use a DataSource object to get a connection, you use the DataSource.setLogWriter method to enable tracing. (For pooled connections, you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use the XADataSource.setLogWriter method.)

5. How can I use the JDBC API to access a desktop database like Microsoft Access over the network?

A) Most desktop databases currently require a JDBC solution that uses ODBC underneath. This is because the vendors of these database products haven't implemented all-Java JDBC drivers.
The best approach is to use a commercial JDBC driver that supports ODBC and the database you want to use. See the JDBC drivers page for a list of available JDBC drivers.
The JDBC-ODBC bridge from Sun's Java Software does not provide network access to desktop databases by itself. The JDBC-ODBC bridge loads ODBC as a local DLL, and typical ODBC drivers for desktop databases like Access aren't networked. The JDBC-ODBC bridge can be used together with the RMI-JDBC bridge , however, to access a desktop database like Access over the net. This RMI-JDBC-ODBC solution is free.

6. Does the JDK include the JDBC API and the JDBC-ODBC Bridge?

A) Yes, the JDK 1.1 and the Java 2 SDK, Standard Edition (formerly known as the JDK 1.2), contain both the JDBC API and the JDBC-ODBC Bridge. The Java 2 SDK, Standard Edition, contains the JDBC 2.0 core API, which is the latest version. It does not include the JDBC 2.0 Optional Package, which is part of the Java 2 SDK, Enterprise Edition, or which you can download separately.
Note that the version of the JDBC API and the JDBC-ODBC Bridge provided for separate download on the JDBC download page are only for use with the JDK 1.0.2.

7. What JDBC technology-enabled drivers are available?

A) See our web page on JDBC technology-enabled drivers for a current listing.

8. What documentation is available for the JDBC API?

A) See the JDBC technology home page for links to information about JDBC technology. This page links to information about features and benefits, a list of new features, a section on getting started, online tutorials, a section on driver requirements, and other information in addition to the specifications and javadoc documentation.

9. Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge?

A) Most ODBC 2.0 drivers should work with the Bridge. Since there is some variation in functionality between ODBC drivers, the functionality of the bridge may be affected. The bridge works with popular PC databases, such as Microsoft Access and FoxPro.

10. Does the JDBC-ODBC Bridge work with Microsoft J++?

A) No, J++ does not support the JDBC-ODBC bridge since it doesn't implement the Java Native Interface (JNI). Any all-Java JDBC driver should work with J++, however.

11. What causes the "No suitable driver" error?

A) "No suitable driver" is an error that usually occurs during a call to the DriverManager.getConnection method. The cause can be failing to load the appropriate JDBC drivers before calling the getConnection method, or it can be specifying an invalid JDBC URL--one that isn't recognized by your JDBC driver. Your best bet is to check the documentation for your JDBC driver or contact your JDBC driver vendor if you suspect that the URL you are specifying is not being recognized by your JDBC driver.
In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or more the the shared libraries needed by the Bridge cannot be loaded. If you think this is the cause, check your configuration to be sure that the shared libraries are accessible to the Bridge.

12. Why isn't the java.sql.DriverManager class being found?

A) Running a JDBC applet in a browser that supports the JDK 1.0.2, such as Netscape Navigator 3.0, can cause this problem. The JDK 1.0.2 does not contain the JDBC API, so the DriverManager class typically isn't found by the Java virtual machine running in the browser.
Here's a solution that doesn't require any additional configuration of your web clients. Remember that classes in the java.* packages cannot be downloaded by most browsers for security reasons. Because of this, many vendors of all-Java JDBC drivers supply versions of the java.sql.* classes that have been renamed to jdbc.sql.*, along with a version of their driver that uses these modified classes. If you import jdbc.sql.* in your applet code instead of java.sql.*, and add the jdbc.sql.* classes provided by your JDBC driver vendor to your applet's codebase, then all of the JDBC classes needed by the applet can be downloaded by the browser at run time, including the DriverManager class.
This solution will allow your applet to work in any client browser that supports the JDK 1.0.2. Your applet will also work in browsers that support the JDK 1.1, although you may want to switch to the JDK 1.1 classes for performance reasons. Also, keep in mind that the solution outlined here is just an example and that other solutions are possible.

13. Why doesn't calling the method Class.forName load my JDBC driver?

A) There is a bug in the JDK 1.1.x that can cause the method Class.forName to fail. A workaround is to explicitly call the method DriverManager.registerDriver(new YourDriverClass()). The exact problem in the JDK is a race condition in the class loader that prevents the static section of code in the driver class from executing and registering the driver with the DriverManager.

14. Why do the java.sql and java.math packages fail to download java.* packages? Is there a workaround?

A) For security reasons, browsers will not download java.* packages. In order to use the JDBC API with browsers that have not been upgraded to JDK1.1 or beyond, we recommend that the java.sql and java.math packages be renamed jdbc.sql and jdbc.math. Most vendors supplying JDBC technology-enabled drivers that are written purely in the Java programming language already provide versions of these renamed packages. When JDK 1.1 support has been added to your browser, you should convert your applets back to the java.* package names.

15. Why is the precision of java.math.BigDecimal limited to 18 digits in the JDK 1.0.2 add-on version of the JDBC API?

A) In JDK 1.1, java.math.BigInteger is implemented in C. It supports a precision of thousands of digits. The same is true for BigDecigmal.
The version of BigInteger provided with the JDK 1.0.2 add-on version of the JDBC API is a simplified version written in the Java programming language, and it is limited to 18 digits. Because the implementation of BigDecimal is based on BigInteger, it also is limited to this precision.
In the JDBC 2.0 API, you can use a new version of the method ResultSet.getBigDecimal that does not take a scale parameter and returns a BigDecimal with full precision.

16. Can the JDBC API be added to JDK 1.0.2?

A) Yes. Download the JDBC 1.22 API from the JDBC download page and follow the installation instructions in the release notes.
If you are using any version of the JDK from 1.1 on, the JDBC API is already included, and you should not download the JDBC 1.22 API.

17. How do I retrieve a whole row of data at once, instead of calling an individual ResultSet.getXXX method for each column?

A) The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which means that you have to make a method call for each column of a row. It is unlikely that this is the cause of a performance problem, however, because it is difficult to see how a column could be fetched without at least the cost of a function call in any scenario. We welcome input from developers on this issue.

18. Why does the ODBC driver manager return 'Data source name not found and no default driver specified Vendor:?

A) This type of error occurs during an attempt to connect to a database with the bridge. First, note that the error is coming from the ODBC driver manager. This indicates that the bridge-which is a normal ODBC client-has successfully called ODBC, so the problem isn't due to native libraries not being present. In this case, it appears that the error is due to the fact that an ODBC DSN (data source name) needs to be configured on the client machine. Developers often forget to do this, thinking that the bridge will magically find the DSN they configured on their remote server machine

19. Are all the required JDBC drivers to establish connectivity to my database part of the JDK?

A) No. There aren't any JDBC technology-enabled drivers bundled with the JDK 1.1.x or Java 2 Platform releases other than the JDBC-ODBC Bridge. So, developers need to get a driver and install it before they can connect to a database. We are considering bundling JDBC technology- enabled drivers in the future.

20. Is the JDBC-ODBC Bridge multi-threaded?

A) No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading. In addition, deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are thinking about removing the synchronized methods in the future. They were added originally to make things simple for folks writing Java programs that use a single-threaded ODBC driver.

21. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?

A) No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

22. Does the JDBC-ODBC Bridge developed by Merant and Sun support result sets that contain Japanese Characters (DBCS)?

A) Yes, but we haven't tested this ourselves. The version of the Bridge in the Java 2 SDK, Standard Edition, and Java 2 SDK, Enterprise Edition, also supports a new charSet Connection property for specifying the character encoding used by the underlying DBMS.

23. Why can't I invoke the ResultSet methods afterLast and beforeFirst when the method next works?

A) You are probably using a driver implemented for the JDBC 1.0 API. You need to upgrade to a JDBC 2.0 driver that implements scrollable result sets. Also be sure that your code has created scrollable result sets and that the DBMS you are using supports them.

24. How can I retrieve a String or other object type without creating a new object each time?

A) Creating and garbage collecting potentially large numbers of objects (millions) unnecessarily can really hurt performance. It may be better to provide a way to retrieve data like strings using the JDBC API without always allocating a new object.
We are studying this issue to see if it is an area in which the JDBC API should be improved. Stay tuned, and please send us any comments you have on this question.

25. There is a method getColumnCount in the JDBC API. Is there a similar method to find the number of rows in a result set?

A) No, but it is easy to find the number of rows. If you are using a scrollable result set, rs, you can call the methods rs.last and then rs.getRow to find out how many rows rs has. If the result is not scrollable, you can either count the rows by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause.

26. I would like to download the JDBC-ODBC Bridge for the Java 2 SDK, Standard Edition (formerly JDK 1.2). I'm a beginner with the JDBC API, and I would like to start with the Bridge. How do I do it?

A) The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no need to download it separately.

27. If I use the JDBC API, do I have to use ODBC underneath?

A) No, this is just one of many possible solutions. We recommend using a pure Java JDBC technology-enabled driver, type 3 or 4, in order to get all of the benefits of the Java programming language and the JDBC API.

28. Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need to connect to a database?

A) You still need to get and install a JDBC technology-enabled driver that supports the database that you are using. There are many drivers available from a variety of sources. You can also try using the JDBC-ODBC Bridge if you have ODBC connectivity set up already. The Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require any extra setup itself. The Bridge is a normal ODBC client. Note, however, that you should use the JDBC-ODBC Bridge only for experimental prototyping or when you have no other driver available.

JAVA J2EE QUESTIONS

J2EE JavaLive Chat Transcripts


Q: What is the JavaTM 2 Platform, Enterprise Edition (J2EE)?

A) Java 2 Platform, Enterprise Edition (J2EE) is a platform that enables solutions for developing, deploying and managing multi-tier server-centric applications. J2EE utilizes Java 2 Platform, Standard Edition to extend a complete, stable, secure, fast Java platform to the enterprise level. It delivers value to the enterprise by enabling a platform which significantly reduces the cost and complexity of developing multi-tier solutions, resulting in services that can be rapidly deployed and easily enhanced.


Q: What are the main benefits of J2EE?

A) J2EE provides the following:
A unified platform for building, deploying and managing enterprise-class software without locking users into a vendor specific-architecture and saves IT time.
A platform that will allow enterprise-class application the ability to run anywhere.
A platform with a complete range of readily available enterprise-class services.
A single easy-to-learn blueprint programming model for J2EE.
A platform that is built upon and leverages existing IT investments and guarantees that enterprise-class software will work on multiple platforms.

Q: What technologies are included in J2EE?

A) The primary technologies in J2EE are: Enterprise JavaBeansTM, JavaServer PagesTM, servlets, the Java Naming and Directory InterfaceTM (JNDI), the Java Transaction API (JTA), CORBA, and the JDBCTM data access API.

Q: How does J2EE relate to Enterprise JavaBeans technology?

A) Enterprise JavaBeans (EJB) technology is the basis of J2EE. EJB technology provides the scaleable architecture for executing business logic in a distributed computing environment. J2EE makes the life of an enterprise developer easier by combining the EJB component architecture with other enterprise technologies to solutions on the Java platform for seamless development and deployment of server side applications.

Q: Who needs J2EE?

A) ISVs need J2EE because it gives them a blueprint for providing a complete enterprise computing solution on the Java platform. Enterprise developers need J2EE because writing distributed business applications is hard, and they need a high-productivity solution that allows them to focus only on writing their business logic and having a full range of enterprise-class services to rely on, like transactional distributed objects, message oriented middleware, and naming and directory services.

Q: Will J2EE be available under the community source program?

A) Yes. When the Java 2 SDK, Enterprise Edition is released, it will be available under Sun's Community Source Licensing program. For more information on Sun's community source program see http://www.sun.com/communitysource.

Q: Are there compatibility tests for J2EE?

A) Yes. A full compatibility test suite will be available when the reference implementation ships. This test suite will test compatibility across Enterprise JavaBeans technology, servlets and JavaServer Pages technology.

Q: What is the J2EETM Blueprints?

A) The J2EETM Blueprints are the best practices philosophy for the design and building of J2EE-based applications. The design guidelines document provides 2 things. First, it provides the philosophy of building n-tier applications on the Java 2 platform. Second, it provides a set of design patterns for designing these applications, as well as a set of examples or recipes on how to build the applications.

Q: What happened to the J2EE application programming model?

A) The J2EE application programming model has qualified as part of the Sun BluePrintsTM best practices program, and has been renamed the "J2EETM Blueprints"

Q: What is the purpose of the Reference Implementation?

A) The purpose of the reference implementation is to validate the specifications. In short, it is to prove that the specifications can be implemented.

Q: Why don`t you allow the binary reference implementation to be deployed or redistributed?

A) We do not allow the binary reference implementation to be deployed or redistributed at the request of our partners. The J2EE reference implementation is essentially a full-featured application server. To make it available on the market would provide a product that competes with the companies that we want to adopt the technology. In this light, we set up the licensing terms to honor this request.

Q: Is XML supported in J2EE?

XML is an essential component in the J2EE platform. J2EE will provide a framework for business-to-business data interchange using XML. Currently, JavaServer Pages framework can be used to generate and consume XML between servers or between server and client. In addition, Enterprise JavaBeans component architecture uses XML to describe its deployment properties, giving Enterprise JavaBeans data portability in addition to its code portability. For more info, see http://java.sun.com/xml/.

JAVA QUESTIONS

25)What are inner class and anonymous class?

A) Inner class : classes defined in other classes, including those defined in methods are called inner classes.
An inner class can have any accessibility including private.
Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.

26)What is a package?

A) A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.

27) What is a reflection package?
Ans: java.lang.reflect package has the ability to analyze itself in runtime.

28) What is interface and its use?

A) Interface is similar to a class which may contain method's signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for:
a)Declaring methods that one or more classes are expected to implement
b)Capturing similarities between unrelated classes without forcing a class relationship.
c)Determining an object's programming interface without revealing the actual body of the class.

30) What is the difference between Integer and int?

A)
a) Integer is a class defined in the java.lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other.
b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.

32) What is the difference between abstract class and interface?

A)
a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract.
b) In abstract class, key word abstract must be used for the methods
whereas interface we need not use that keyword for the methods.
c) Abstract class must have subclasses whereas interface can't have subclasses.

33) Can you have an inner class inside a method and what variables can you access?

A) Yes, we can have an inner class inside a method and final variables can be accessed.

34) What is the difference between exception and error?

A) The exception class defines mild error conditions that your program encounters.
Ex: Arithmetic Exception, FilenotFound exception
Exceptions can occur when
-- try to open the file, which does not exist
-- the network connection is disrupted
-- operands being manipulated are out of prescribed ranges
-- the class file you are interested in loading is missing
The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.
Ex: Running out of memory error, Stack overflow error.

35) What is the class and interface in java to create thread and which is the most advantageous method?

A) Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.

36) When you will synchronize a piece of your code?

A) When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.

37) What is daemon thread and which method is used to create the daemon thread?

A) Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

38) Are there any global variables in Java, which can be accessed by other part of your program?

A) No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here.

39)What is the difference between applications and applets?

A)
a)Application must be run on local machine whereas applet needs no explicit installation on local machine.
b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser.
d)Application starts execution with its main method whereas applet starts execution with its init method.
e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

40)How does applet recognize the height and width?

A) Using getParameters() method.

41)When do you use codebase in applet?

A) When the applet class file is not in the same directory, codebase is used.

42)How do you set security in applets?

A) using setSecurityManager() method

43) What is an event and what are the models available for event handling?

A) An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are:
a) event-inheritance model and b) event-delegation model

44)What is source and listener ?

A)
source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way.
listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.

45) What is adapter class?

A) An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested.

46)What is meant by controls and what are different types of controls in AWT?

A) Controls are components that allow a user to interact with your application and the AWT supports the following types of controls:
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components.
These controls are subclasses of Component.

47) What is the difference between choice and list?

A) A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice.
A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items.

48) What is a layout manager and what are different types of layout managers available in java.awt?

A) A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.

49) Which containers use a Border layout as their default layout?

A) Window, Frame and Dialog classes use a BorderLayout as their layout.

50) Which containers use a Flow layout as their default layout?

A) Panel and Applet classes use the FlowLayout as their default layout.

51) What are wrapper classes?

A) Wrapper classes are classes that allow primitive types to be accessed as objects.

52) What is the difference between set and list?

A) Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.

what is the basic difference in rmi & corba.
1. both are distributed technologies.
2. rmi is used when both client & server are in java.
3. corba is used when client & server are written in different lang.
4. IDL comes into picture. as it changes native calls to java or vice versa.


53) what does class.forName(driver) do?

A) it requests for the driver & loads the driver.
statement.execute() returns resultset.
what type of resultset is it?
---> sql result set

JAVA QUESTIONS IN RMI and JSP

Q) What is RMI and steps involved in developing an RMI object?

A) Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine.
The steps involved in developing an RMI object are:
a) Define the interfaces
b) Implementing these interfaces
c) Compile the interfaces and their implementations with the java compiler
d) Compile the server implementation with RMI compiler
e) Run the RMI registry
f) Run the application

Q) What is RMI architecture?

a) Application layer ---- contains the actual object definition
b) Proxy layer ---- consists of stub and skeleton
c) Remote Reference layer ---- gets the stream of bytes from the transport layer and sends it to the proxy layer
d) Transportation layer ---- responsible for handling the actual machine-to-machine communication

Q) what is UnicastRemoteObject?

A) All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.

Q) Explain the methods, rebind( ) and lookup() in Naming class?

A) rebind( ) of the Naming class(found in java.rmi) is used to update the RMI registry on the server machine. Naming. rebind("AddSever", AddServerImpl);
lookup( ) of the Naming class accepts one argument, the rmi URL and returns a reference to an object of type AddServerImpl.

Q) What is a Java Bean?

A) A Java Bean is a software component that has been designed to be reusable in a variety of different environments.

Q) What is BDK?

A) BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code.

Q) What is JSP?

A) JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology - you can't do any client side validation with it.
The advantages are:
a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process.
b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.

Q) What are JSP scripting elements?

A) JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page.
There are three forms:
a) Expressions of the form <%= expression %> that are evaluated and inserted into the output,
b) Scriptlets of the form <% code %> that are inserted into the servlet's service method, and
c) Declarations of the form <%! Code %> that are inserted into the body of the servlet class, outside of any existing methods.

Q) What are JSP Directives?

A) A JSP directive affects the overall structure of the servlet class. It usually has the following form: <%@ directive attribute="value" %>
However, you can also combine multiple attribute settings for a single directive, as follows: <%@ directive attribute1="value1" attribute 2="value2" ... attributeN ="valueN" %>
There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet

Q) What are Predefined variables or implicit objects?

A) To simplify code in JSP expressions and scriptlets, we can use eight automatically defined variables, sometimes called implicit objects. They are request, response, out, session, application, config, pageContext, and page.

Q) What is Bootstrapping in RMI?

Dynamic loading of stubs and skeletons is known as Boot Strapping.

Q) What are different types of Exceptions?.

Runtime exceptions, Errors, Program Exceptions

Q) What is servlet tunnelling?.

Used in applet to servlet communications, a layer over http is built so as to enable object serialization.

Q) What is the frontend in Java?.Also what is Backend?.

Frontend: Applet
Backend : Oracle, Ms-Access(Using JDBC).



Access Modifiers: Which gives additional meaning to data, methods and classes.

Q) Tools provided by JDK

(i) javac - compiler
(ii) java - interpretor
(iii) jdb - debugger
(iv) javap - Disassembles
(v) appletviewer - Applets
(vi) javadoc - documentation generator
(vii) javah - 'C' header file generator

Q) Hostile Applets:Its an applet which when downloaded attempts to exploit your system's resources in an inappropriate manner.It performs or causes you to perform an action which you would not otherwise care to perform.

Q) RemoteObjects: Objects that have methods that can be called accross virtual machines are Remote Objects.An object becomes Remote by implementing Remote Interface.

Q) Compiling: Conversion of Programmer-readable Text into Bytecodes,which are platform independent,is known as Compiling.

Q) Java Primitive Data Types:
Byte-8-bit, short-16-bit, int-32-bit, Long-64-bit, Float-32-bit floating point, Bouble-64-bit floating point, Char-16-bit Unicode

Q) What is a unicode?

Unicode is a standard that supports International Characters.

Q) What are blocks?.

They are statements appearing within braces {}.

35. What are types of Java applications?.

(i) Standalone applications(No browser).
(ii) Applets(Browser).

Q) What is the method that gets invoked first in a stand alone application?.

The main()method.

Q) What is throwing an Exception?.

The act of passing an Exception Object to the runtime system is called Throwing an Exception.

Q) What are the packages in JDK?.

There are 8 packages
(i) java.lang(ii)java.util(iii)java.io(iv)java.applet(v) java.awt
(vi) java.awt.image(vii)java.awt.peer(viii)java.awt.net

Q) What is runnable?.

Its an Interface through which Java implements Threads.The class can extend from any class but if it implements Runnable,Threads can be used in that particular application.

Q) What is preemptive and Non-preemptive Time Scheduling?.

Preemptive: Running tasks are given small portions of time to execute by using time-slicing.
Non-Preemptive: One task doesn't give another task a chance to run until its finished or has normally yielded its time.

Q) What is synchronization?.

Two or more threads trying to access the same method at the same point of time leads to synchronization.If that particular method is declared as synchronized only one thread can access it at a time. Another thread can access it only if the first thread's task is complete.

1. executeQuery() returns ResultSet.

2 .Throwable class is a sub-class of object and implements Serializable.

3 . Skeletons are server side proxies and stubs are client side proxies. True

4 . Netscape introduced JScript language - True

5 . EventDelegation model was introduced by JDK 1.1 - False

6 . StringTokenizer provides two constructors - False

7 . java.applet is one of the smallest package in Java API - True


Q) What is IP?.

IP is Internet Protocol. It is the network protocol which is used to send information from one computer to another over the network over the internet in the form of packets.

MIME(Multipurpose Internet Mail Extension) is a general method by which the content of different types of Internet objects can be identified.

Q) What is an abstract class?.

A class which cannot be Instantiated.

Q) How many standard ports are available?.

1024.

Q) What are different ways of Session-Tracking?.

(i) User-Authorization
(ii) Hidden Files
(iii) Persistant Cookies
(iv) URL Rewriting.

Q) What is a Swing?.

It is a GUI component with a pluggable look and feel.

Q) What is default Look-and-Feel of a Swing Component?.

Java Look-and-Feel.

1 Awt Components and Swing Components can be inter-mingled in an Application - False

2 What does x mean in javax.swing?. Extension of java.

3 Images can be displayed on Swing Components - True

4 Borders can be changed or added for a LightWeight Components - True

5 Swing Components are always rectangular - False

Q) When Swing components overlap with Heavyweight components, it is the latter that is on the
top - True

Q) What are invisible components?.

They are light weight components that perform no painting, but can take space in the GUI.

Q) What are the borders provided by Swing?.

(i) Simple (ii) Matte iii) Titled iv) Compound.

Q) What are the restrictions imposed by a Security Manager on Applets?.

i) cannot read or write files on the host that's executing it.
ii) cannot load libraries or define native methods.
iii) cannot make network connections except to the host that it came from
iv) cannot start any program on the host that's executing it.
v) cannot read certain system properties.
vi) windows that an applet brings up look different than windows that an application brings up.

Q) what is the difference between Procedural and OOPs?
A)
a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOPs program, unit of program is object, which is nothing but combination of data and code.
b) In procedural program,data is exposed to the whole program whereas in OOPs program,it is accessible with in the object and which in turn assures the security of the code.

Q) What is the difference between Assignment and Initialization?

A) Assignment can be done as many times as desired whereas initialization can be done only once.

Q) What are Class, Constructor and Primitive data types?

A) Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform.

Constructor is a special kind of method that determines how an object is initialized when created.

Primitive data types are 8 types and they are:
byte, short, int, long
float, double
boolean
char

Q) What is an Object and how do you allocate memory to it?

A) Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.

Q) What is the difference between constructor and method?

A) Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.

Q) What are methods and how are they defined?

A) Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes.
Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method's signature is a combination of the first three parts mentioned above.

Q) What is the use of bin and lib in JDK?

A) Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.

Q) What is casting?
A) Casting is used to convert the value of one type to another.

Q) What is the difference between an argument and a parameter?

A) While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

Q) What is Garbage Collection and how to call it explicitly?

A) When an object is no longer referred to by any variable, java automatically reclaims memory used by that
object. This is known as garbage collection.
System.gc() method may be used to call it explicitly.
Q) What is finalize() method ?

A) finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.

Q) What are Transient and Volatile Modifiers?

A) Transient: The transient modifier applies to variables only and it is not stored as part of its object's
Persistent state. Transient variables are not serialized.
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by
volatile can be changed unexpectedly by other parts of the program.

Q) What is method overloading and method overriding?

A) Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading.
Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.

Q) What is difference between overloading and overriding?

A) a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method.
b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass.
c) In overloading, separate methods share the same name whereas in overriding,subclass method replaces the superclass.
d) Overloading must have different method signatures whereas overriding must have same signature.

Q) What is meant by Inheritance and what are its advantages?

A) Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.

Q) What is the difference between this() and super()?

A) this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.

Q) What is the difference between superclass and subclass?

A) A super class is a class that is inherited whereas sub class is a class that does the inheriting.

Q) What modifiers may be used with top-level class?

A) public, abstract and final can be used for top-level class.

JAVA QUESTIONS1

JAVA QUESTIONS


1. ODBC Ans. Open Database Connectivity.
2. HTML Ans. Hyper Text Markup Language
3. RISC Ans. Reduced Instruction Set Computing
4. ASCII Ans. American Standard Code For Information Interchange
5.ANSI Ans. American National Standard Institute.
6. XML Ans. Extended Markup Language
7. FLOPS Ans. Floating Point Operating Per Second
8. SQL Ans. Sequential Query Language
9. QBE Ans. Query By Example
10. ALE Ans. Address Latch Enable
12. RPC Remote procedure call
11. What is lagging in DBMS ? Ans. Reduced Redundancy.


What is JAVA ?

Java is a pure object oriented programming language, which has derived C syntax and C++ object oriented programming features.
Is a compiled and interpreted language and is platform independent and
Can do graphics, networking, multithreading. It was initially called as OAK.

What r the four cornerstones of OOP ?

Abstraction :
Can manage complexity through abstraction. Gives the complete overview of a particular task and the details are handled by its derived classes. Ex : Car.
Encapsulation : Nothing but data hiding, like the variables declared under private of a particular class are accessed only in that class and cannot access in any other the class.
Inheritance : Is the process in which one object acquires the properties of another object, ie., derived object.
Polymorphism : One method different forms, ie., method overriding and interfaces are the examples of polymorphism.

what is downcasting ?

Doing a cast from a base class to a more specific class. The cast does not convert the object, just asserts it actually is a more specific extended object.
e.g. Dalamatian d = (Dalmatian) aDog;
Most people will stare blankly at you if you use the word downcast. Just use cast.

What is Java Interpreter ?

It is Java Virtual Machine. ie., a java program compiles the Unicode to intermediary code called as Bytecode which is not an executable code. that is executed by Java interpreter.

What are Java Buzzwords ?

Simple : Easy to learn.
Secure : Provided by firewalls between networked applications.
Portable : Can be dynamically downloaded at various platforms connect to internet.
OOP : Four Corner stones.
Multithread : Can perform more than one task concurrently in a single program.
Robust : overcomes problems of de-allocation of memory and exceptions.
Interpreted : Convert into byte code and the executes by JVM.
Distributed : Concept of RMI.
Dynamic : Verifying and accessing objects at run time.


What are public static void main(String args[]) and System.out.println() ?

Public keyword is an access specifier.
Static allows main() to be called without having to instantiate a particular instance of class.
Void does not return any value.
main() is the method where java application begins.
String args[] receives any command line arguments during runtime.

System is a predefined class that provides access to the system.
out is output stream connected to console.
println displays the output.

What are identifiers and literals ?

Identifiers are the variables that are declared under particular datatype.
Literals are the values assigned to the Identifiers.

What is Typed language ?

This means that the variables are at first must be declared by a particular datatype whereas this is not the case with javascript.

Scope and lifetime of variables ?

scope of variables is only to that particular block
lifetime will be till the block ends.
variables declared above the block within the class are valid to that inner block also.

Casting Incompatible types ?

Can be done either implicitly and explicitly. ie., int b = (int) c; where c is float.
There are two types of castings related to classes : 1) unicast and 2)multicast.

Declaration of Arrays ?

int a[] = new int[10]; int a[][] = new int[2][2];

What does String define ?

String is an array of characters, but in java it defines an object.
and the variable of type string can be assigned to another variable of type String.

What r bitwise operators and bitwise logical operators ?

~, &, |, ^, >>, >>>, <<, &=, != and ~, &, | How do you define break and Label ? We can declare as break

"C" Questions2

1. How much space does a variable of type int occupy in memory?

The size of int data type is not fixed. It depends upon the operating system you are using. On 16-bit operating systems like DOS, its size is 2-bytes (16-bits) and on 32 bit operating systems such as Windows, and Linux, it is 4-bytes (32-bits).

2. What do you mean by typecasting?

Typecasting is a mechanism used to convert a value from one data type into another.

This is how you can typecast an expression. Let us assume that the variables i and j as integers. By writing the following expression

f=(float) i/j;

you are forcibly converting the numerator (i) into a float.


3. Why should one declare variables?

There are several reasons for declaring variables:

• When all the variables are in one place it becomes easy for a reader to quickly understand what the program is about.

• As a programmer, having to declare the variables forces you to do some planning before writing the program. You have to think about what information the program needs; what exactly you want the program to produce as output; the best way to represent the data; and so on.

• Declaring variables also helps to prevent a common but hard-to-find bug — a misspelled variable name. If you make a mistake in the spelling of a variable name, and enter LENGTHl instead of LENGTH1, the compiler complains that an undeclared variable has turned up.

• Your C program will not be compiled if you don’t declare variables.

4. Why is an & needed before a variable name in the scanf() function?

When you place an '&' before a variable, you inform the compiler of the memory address reserved for the variable in the computer’s main memory. This is similar to an address that tells the postman where to deliver a letter. Using this memory address, the scanf() function will store the value entered by the user from the keyboard in that location.

5. What is initialization?

Initialization is a process by which a variable is assigned an initial value after it is declared. Initialization is required in the program when you know in advance the value a variable is going to contain. Also initialization is useful in programs that manipulate the initial value contained in a variable and results in a different value later. For example, if you are writing a program to find the sum of the first 5 natural numbers, you initialize a variable, say, sum to 1 and add to it the remaining numbers resulting in the final result of 15.

6. What do you mean by operator precedence?

When you are evaluating an arithmetic expression that has two or more operators, you may not be clear about how it gets executed. For example, does the expression a*b/c correspond to (a*b)/c or a*(b/c)? A programmer is confused regarding this. So, to resolve this confusion, you need to understand the ‘hierarchy’ of operations, which only means the priority or precedence in which the operations in an expression are performed.

The table given here shows the hierarchy of commonly used arithmetic operators.

Priority Operators Description

I * / % Multiplication, Division, and Modulo division

II + - Addition, and Subtraction

III = Assignment


7. What is operator association?

Take a look at the expression:

X=3 * 16 % 11 / 4;

In this expression, you will find that the operators * and % share the operand 16 and similarly % and / share the operand 11. In such cases, C uses left-to-right association rule, which means that the operator to the left of the operand is evaluated first and then the one on the right.

If you consider the assignment operator, its association is right-to-left, which means that the value on the right of the operator is finally assigned to the variable on the left and not the other way round. The table shows you the association of all the arithmetic operators.

Operators Association
* / % Left to right
+ - Left to right
= Right to left.


8. What does logical NOT operator do?

Logical NOT (!) operator is a unary operator. This means it will operate on only one operand. This operator is used to negate a condition or a value. What this means is that using this operator you can make a condition FALSE, if it is TRUE and vice versa. Consider the following example.

"C" Questions

1. Why there are so many data types in C?

Ans: Let us assume that there is only one data type that can hold any kind of data and its size in memory is say, 10 bytes. Now, to store a character, as you might know only 1-byte is enough. This causes 9 bytes of memory to go waste. Similarly if you want to store a number between 1 and 10000, 2-bytes are sufficient, again wasting 8-bytes of memory. Memory is a precious resource and in any case it should not be wasted. This is the reason why there are so many data types, each addressing the specific requirements.

2. What is the difference between float and double?

Ans: Both float and double are data types in C/C++. They are used to represent fractional numbers. However, they differ in what is called precision. Precision refers to the number of digits after the decimal point. While float gives a precision of 6-digits, the double data type gives a precision of 15, which is more than double of what a float offers. That is the reason why the double is always referred to as double precision floating point. For normal computations float data type is sufficient. However, in the programs that require greater precision the double data type is used.

3. How do I find out the size of a particular data type?

Ans: C and C++ has an operator called sizeof, using which one can find the amount of space occupied by a variable of a particular type in computers’ memory. For example, if you have declared a float variable, say, f in your program. To find the amount of space it occupies in memory, write a statement in your program as follows:

printf(“The size of float=%d”,sizeof(f));

4. What does the % operator do?

Ans: The % operator is called modulus operator. It returns the remainder after integer division. For example, consider the following statement:

a=5%2;

In this expression, the variable a is going to contain 1, because when 5 is divided by 2, the remainder is 1. You cannot use % operator with float and double data types.

5. Which format specifier should I use to represent a long double?

Ans: The format specifier that is used to represent a long double is %Lf.

6. I heard that increment (++) and decrement (--) operators are used differently in different situations. Could you please explain?

Ans: The increment (++) operator and decrement (--) operator in C/C++ always increment and decrement respectively, the value of a variable by 1. They can be used in two forms: postfix and prefix.

In postfix form, the operators are used after the variable, for example, a++, a--. In the prefix form, the operators are used before the variable, for example, ++a, --a. In both the cases the value of a variable is simply incremented or decremented by 1. However, when these operators are used in conjunction with other operators or in a large expression, their behavior slightly differs. Consider the following cases:

Case-1:

int a=10,b;
b=++a;

Observe the second statement in the above two statements. In this case, first the value of the variable a increments to 11, and this value is assigned to the variable b. Now, the variable a contains 11 and the variable b also contains 11.

Case-2:

int a=10,b;
b=a++;

Observe the second statement in the above two statements. In this case, first the value of the variable a, i.e., 10 is assigned to the variable b first and then the value of variable a increments to 11. Now, the variable a contains 11, and the variable b contains 10.

The decrement operator also behaves in the same manner, when it is used in a large expression.

sorting

Like selection sort, which you saw in the previous article, sorting using bubble sort technique is accomplished through several rounds of comparison. To sort the array containing 5 elements, you might need at least 4 rounds of comparison. In each round again there will be several comparisons. The sorting process is as follows:

1. Select the first element in the array and compare it with the second. If the second element is less than the first element, then interchange their positions. Now compare second and third and interchange if third is less than second. Continue this process of comparison and interchanging till the last element in the array. This marks the end of, the first round. After this round you will find the biggest element in the array at the last position.

2. Select the first element again in the array and repeat the process of comparison and interchanging as above. This completes the second round. After this round you will find the second largest element in the last but one position.

3. Note that during each round the largest elements will go to the end of the array. So you should write your program in such a way that in each round of comparison these elements should not be taken into account. Unlike selection sort here the successive elements are compared during every round and that’s the reason why this technique is called bubble sorting.


Examine the following figures to understand the sorting process for a set of 4 numbers — 8,5,2, and 3


Round-I
Here, since 8 is greater than 5, they
interchange their positions.

Here, since 8 is greater than 2, they
interchange their positions.
Here, since 8 is greater than 3, they
interchange their positions. Observe that the
highest value has come to the last position.



Round – II

Here, since 5 is greater than 2, they
interchange their positions.

Here, since 5 is greater than 3, they
interchange their positions.

Observe that the second highest value has
reached the last but one position in the array.



Round - III

Here, since 2 is not greater than 3, they
will not interchange their positions.

This is the final sorted array.

Arrays in "c"

The Indigenous Automobiles in Hyderabad is the largest car-manufacturing company. Its managing director wanted to find out how many cars were sold in the previous year. His idea was to assess the performance of the company and make future projections. He wanted the programmers at his sister concern, the Indigenous Software Solutions to generate the annual sales report for the previous year. He provided them with the following data.


Month Sales

1 100
2 150
3 127
4 246
… ….
… ….
11 193
12 200









If, you were a programmer at Indigenous Software Solutions, how would you go about this task?

To generate a report like the one you saw above, first of all you should store the data in the computer memory and then display it in the form of a table. There are two ways to do this.

In the first method, you will use 12 variables, say, sales1, sales2,…,sales12, store the values in them, and display the values. The code you write would be as shown below:


What would happen if there were so many variables! Wouldn’t it become tedious?

To overcome this problem C provides a data structure (a way of organizing data in the computer’s memory) called Array.

An array is a group of adjacent memory locations, referred to by a single name. This is used to store a set of similar data items. These similar data items could be all ints, floats, and chars, but not a combination of these.

Understand the concept of arrays with the help of this example.

Suppose there is a set of 5 books (B):

B={Computers, History, Math, Electronics, Physics}

If you want to refer to the History book in this set, how do you do it? You will say B2. Here the suffix 2 indicates that it is the second book in the set.

C uses a similar scheme to refer to individual elements of an array. This number called index or subscript is written inside square brackets ([]). The index number in C always begins with a zero (0).

Now, let us come back to our example of generating annual sales report. To store the 12 sales figures in an array you will write a statement as follows:

int sales[12];

This statement is called array declaration statement. When the C compiler sees this statement, it will reserve 12 adjacent memory locations as shown in the figure below.



sales
0 1 2 3 4 5 6 7 8 9 10 11

In this figure, sales refers to the name of the array, and the numbers 0 through 11 are referred to as index or subscript. You will use this number to refer to a particular memory location in the array. For example, if you want to store a number in the 1st cell of this array, you will write a statement sales[0]=120; similarly, if you want to store a number in the 8th cell, you will write sales[7]=300; and so on.

Storing and printing data in an array

One way to fill the sales figures in the array is to initialize the array just as other variables are initialized. This is very simple as you can see from the following statement.

int sales[12]={100, 150, 127, 246, 267, 298, 278,265, 255, 124, 193, 200};

However, you need not mention the array’s size. You could simply say:

int sales[ ]={100, 150, 127, 246, 267, 298, 278, 265, 255, 124, 193, 200};

NOTE: Till specific values are given, the array contains unpredictable values.


Another way of storing data in an array is to enter it using the keyboard while the program is running.

The program below shows you how to write the code that accepts data from the user and stores it in an array, while the program is being executed.

Input-output functions

Suppose you develop a piece of software to be used for computerizing a bank’s operations. In the code for this software, you would write a program to store details of the bank’s customers. In this program let us assume that you have used the assignment operator (refer to the previous article) for storing customer details such as name, age and telephone number in the respective variables. How would you enter the details of a new customer?

You would do this by opening the program, assigning the values to variables, and compiling the program again. However, this is a cumbersome process, as you have to recompile the program each time that you make a change. Moreover, when using an assignment operator, you may not know in advance the values that you want to assign to the variables.

Data and input functions

For the reasons mentioned above, almost every program should include statements used to request input from users while the program is running. Such statements are called input statements. The C compiler has built-in input functions for storing data (entered through a keyboard) in variables while the program is running. These input functions facilitate interactive programming, i.e., you can interact with a running program. One such widely used function in C is scanf().

The scanf() function

The syntax of scanf() and that of printf() look alike except that an ‘&’ symbol precedes every variable in the case of scanf(). This function is used to input different kinds of values — int, float, and char.

Read the following code. It demonstrates the use of the scanf() function:

main()
{
1. int a;
2. float b;
3. char c;
4. printf(“Enter an integer:”);
5. scanf(“%d”,&a);
6. printf(“Enter a float:”);
7. scanf(“%f”,&b);
8. printf(“Enter a character:”);
9. scanf(“%c”,&c);
10. printf(“You entered %d %f %c”, a, b, c);


When you run this program, it prompts you to enter first an integer, then a float, and finally a character. After you enter these values, the last printf() function displays all the three values entered.

Other input functions

Apart from the scanf() function, there are also other functions such as getchar() and gets() to store characters and strings (set of characters). The following program demonstrates the use of these functions.



#include
main ()
{
1. char a;
2. printf (“Enter any character:”);
3. a=getchar();
4. printf(“The character you entered is:%c”,a);


Observe how the function getchar() is used in this program. This function receives a character entered by the user and stores it in the variable a. The printf() function written below the getchar() statement displays on the screen the character that you entered from the keyboard. C, however, also provides a function called putchar() to display the character on the screen. You can use this function in the above program instead of printf(). The following statement is written to use putchar() in the above program.

putchar(a);

Accepting strings using gets() function

In the previous articles, you saw a program that displayed a string (Hello, World) on the screen using the printf() function. Now you will see how to accept a string from keyboard and display it.

In this program:

 The first statement — char a[25]; — informs the compiler to set aside 25 locations to store 25 characters.
 The second statement prompts the user by displaying the message “Enter a string” on the screen.
 The third statement accepts the string from the keyboard.
 The fourth statement displays the string that you entered on the screen.
 %s stands for ‘format string’ to print strings.

You can also get the same result for the above program by using another kind of output function, puts(). This function is used exclusively for handling strings. It can’t be used for printing numeric data. The following statement would be written to use puts() in the above program.
Try it out:

1. Write a program to accept and store the values 15, 30.5 and ‘A’ in the variables i, f, and c using the function scanf(), and to display them using the printf() function.

2. Write a program to accept and store a character (say, ‘$’) in the variable ch using the function getchar() and t display it on the screen using the function putchar().

3. Write a program to accept and store a string (say, “Hi-Tech City”) in the variable city and to display it on the screen using the function puts().

Conditions in "C"

Branching in C

You will use the following statements in C to facilitate branching.

1. The if statement

2. The if-else statement

Let us learn about each.

The if statement

The if statement is similar to the if statement in English. Consider the following statements.

- if it is raining, I will not go to school.

- if tomorrow is a holiday, I will watch a movie.

In the above two statements, a decision is taken (I will not go to school, I will watch a movie) based on some conditions (if it is raining, if tomorrow is a holiday). In these two statements the condition is introduced by the word if. Similarly in C, the keyword if introduces a condition. Based on whether the condition is true or false, the appropriate decision is taken.

Consider the following program, which decides which number is bigger among the two.



#include

main()

{

int num1=10, num2=20;

if(num1>num2)

{

printf(“num1 is big”);

}

if(num2>num1)

{

printf(“num2 is big”);

}

if(num1==num2)

{

printf(“The two are equal”);

}

}


The output of this program is num2 is big. Let us find out how we got this output:

- The first if statement checks whether the value in the variable num1 is greater than the value in num2. If it is, then the printf() statement within the braces prints “num1 is big” on the screen.

- The second if statement checks whether the value in the variable num2 is greater than that of num1. If it is, the printf() statement within the braces prints “num2 is big” on the screen. In our program, since the value in num2 is greater than that in num1, we got the output, as num2 is big.

- The third if statement checks whether the value in the variable num1 equals that in num2. If it does, the printf() statement within the braces prints “The two are equal”.

In general, the syntax of the if statement is as follows:

if(condition)

{

statement1;

statement2;

………………..;

…………………;

}

The compiler executes the statements within the braces only when the condition is evaluated to be true. If the condition is false, the control simply transfers to the statement next to the if statement.

Relational operators

Observe the three new symbols (>, <, and ==) in the above program. These are called relational operators. These are used to construct a condition. In the above program there are three conditions, num1>num2, num2>num1, and num1==num2. The first condition is evaluated to be true only when the value in the variable num1 is greater than that of num2, the second is reckoned as true only when the value in the variable num2 is greater than that of num1, and the third is evaluated to be true only when the values in both num1 and num2 are equal.

The following table gives a list of all the relational operators in C.

Operator

Description

==

Equals to

!=

Not equals to

>

Greater than

<

Less than

>=

Greater than or equals to

<=

Less than or equals to

Note: = and == are different in C. If you write = in place of ==, it is a logical error.

Writing programs using if-else

Let us suppose you purchased a book on C programming from a bookstall. The shopkeeper bought that book from a distributor at Rs.X and he sold it to you at Rs.Y. The following C program helps you to decide whether the shopkeeper made a gain or suffered a loss in the transaction.

#include

main()

{

int cp,sp;

printf(“Enter cost price:”);

scanf(“%d”,&cp);

printf(“Enter selling price:”);

scanf(“%d”,&sp);

if(sp>cp)

printf(“Gain”);

else

printf(“Loss”);

}

Observe how the if-else statement is used in this program. This statement is used when there are only two alternatives and you have to choose one of them.

Try it out

1. Write a program to check whether a given number is even or odd? (Hint: An even number is a number which when divided by 2 gives the remainder 0. So use % operator to find the remainder and compare it with 0.)

2. Write a program to accept a number (other than 0) from a keyboard and display whether it is positive or negative.

Saturday, October 13, 2007

Writing a program to print values in variables

Storing data in variables

The easiest way to store a value in a variable named ‘num is by writing the statement num=value.

Here, ‘= is called an assignment operator because it assigns a value to the variable. Writing

num=10;

indicates to the complier that the value ‘10’ should be stored in the ‘num’ variable.

Note: You can use the assignment operator to store a value in a variable you are declaring. For example:

int number=10;

Writing a program to print values in variables

Now that you know how to store values in variables, let us write a program to print stored values on the screen. Consider this program:

/* Author: Globarena

Date: 15/10/2003

Purpose: To print values stored in variables

*/

#include

main()

{

int a=10;

float b=3.1412;

char ch=’A’;

printf(“%d\n%f\n%c”,a,b,ch);

}


When you run this program, the following output will be displayed on screen:

10

3.1412

A

Observe how the printf() function is used in the program. Doesn’t it look different from the printf() used to print messages ? (See article 2.) You might also be wondering what those strange characters (%d, %f, \n, etc.) are.

The characters %d, %f, and %c are called format specifiers or simply format strings. The ‘%’ symbol alerts the compiler that a variable is to be printed at that location and the letter that follows tells it to print the value as an int, float, char, and so on.

The character ‘\n’ is called a newline character. It is used to insert a new line so that the values in variables mentioned after it are printed on a new line (as shown above). If this character is not used, the output will look as shown below:

103.1412A

This would be difficult to comprehend.

Note: Characters like the ‘\n’ character that start with ‘\’ are called escape sequences.

The following tables gives you a partial list of format strings and escape sequences that you will frequently come across in C programs.

Table 2 Table 3

Sl. No

Data type

Format Specifier

1.

int

d

2.

float

f

3.

char

c

4.

unsigned int

u

5.

string

s

6.

long int

ld

7.

double

lf

Sl. No

Escape sequence

Purpose

1.

\n

Newline

2.

\t

Tab

3.

\a

Beep

4.

\b

Backspace

5.

\r

Return


Try it out:

  1. Write a program to store 10, 12.5, and a character ‘Z’ in integer, float, and character variables respectively and display the values on the screen.

Write a program to store 15, 3,14, and ’X’ in integer, float, and character variables respectively and display the values on separate lines on the screen