Spring 2012
Bachelor of Science in Information Technology (BScIT) – Semester 3
BT0074 – OOPS with Java – 4 Credits (Book ID: B1002)
Assignment Set – 1 (60 Marks)
1. Give the features of Java.
Ans.-The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language.
Platform Independent:-The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language. Not even a single language is idle to this feature but java is more closer to this feature. The programs written on one platform can run on any platform provided the platform must have the JVM.
Simple:-There are various features that makes the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system but we cannot say about the other programming languages. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and deallocation system.
Object Oriented:-To be an Object Oriented language, any language must follow at least the four characteristics. Inheritance: It is the process of creating the new classes and using the behavior of the existing classes by extending them just to reuse the existing code and adding the additional features as needed. Encapsulation: It is the mechanism of combining the information and providing the abstraction.
Polymorphism: As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the functions having the same name based on the signatures of the methods.
Dynamic binding: Sometimes we don't have the knowledge of objects about their specific types while writing our code. It is the way of providing the maximum functionality to a program about the specific type at runtime. As the languages like Objective C, C++ fulfills the above four characteristics yet they are not fully object oriented languages because they are structured as well as object oriented languages. But in case of java, it is a fully Object Oriented language because object is at the outer most level of data structure in java. No standalone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into object by using the wrapper class.
Robust:-Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.
Distributed:-The widely used protocols like HTTP and FTP are developed in java. Internet programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system.
Portable:-The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM. Java also has the standard data size irrespective of operating system or the processor. These features make the java as a portable language.
Dynamic:-While executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet.
Secure:-Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading.
Performance:-Java uses native code usage, and lightweight process called threads. In the beginning interpretation of bytecode resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance.
Multithreaded:-As we all know several features of Java like Secure, Robust, Portable, dynamic etc.; you will be more delighted to know another feature of Java which is Multithreaded. Java is also a multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time. Multiple threads execute instructions according to the program code in a process or a program. Multithreading works the similar way as multiple processes run on one computer. Multithreading programming is a very interesting concept in Java. In multithreaded programs not even a single thread disturbs the execution of other thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUs. This is how Multithreading works in Java which you will soon come to know in details in later chapters.
Interpreted:-We all know that Java is an interpreted language as well. With an interpreted language such as Java, programs run directly from the source code. The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program. The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent. Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.
Architecture Neutral:-The term architectural neutral seems to be weird, but yes Java is an architectural neutral language as well. The growing popularity of networks makes developers think distributed. In the world of network it is essential that the applications must be able to migrate easily to different computer systems. Not only to computer systems but to a wide variety of hardware architecture and operating system architectures as well. The Java compiler does this by generating byte code instructions, to be easily interpreted on any machine and to be easily translated into native machine code on the fly. The compiler generates an architecture-neutral object file format to enable a Java application to execute anywhere on the network and then the compiled code is executed on many processors, given the presence of the Java runtime system. Hence Java was designed to support applications on network. This feature of Java has thrived the programming language.
2. How do you execute a Java program?
Ans.-Most often in your Java programs you will find a need to execute system DOS commands. You can execute any system commands that are OS specific and then read the output of the system command from your Java program for further processing within the Java program.
This sample Java Program executes the 'dir' command reads the output of the dir command prints the results. This is just for understanding the concept, however, you may execute just about any command using this Runtime.getRuntime().exec() command.
3. What are the different types of operators used in Java?
Ans.-Operators play an important role in Java. There are three kinds of operators in Java. They are (i) Arithmetic Operators (ii) Comparison / Relational Operators and (iii) Logical Operators
1. Arithmetic Operators:-Addition, Subtraction, Multiplication, Division and Modulus are the various arithmetic operations that can be performed in Java.
List of Arithmetic Operators
Operator
|
Meaning
|
Use
|
Meaning
|
+
|
Addition
|
op1+op2
|
Adds op1 and op2
|
-
|
Subtraction
|
op1-op2
|
Subtracts op2 from op1
|
*
|
Multiplication
|
op1*op2
|
Multiplies op1 and op2
|
/
|
Division
|
op1/op2
|
Divides op1 by op2
|
%
|
Modulus
|
op1 % op2
|
Computes the remainder of dividing op1 by op2
|
2. Increment and Decrement Operators:-The increment operator is ++ and decrement operator is – -. This is used to add 1 to the value of a variable or subtract 1 from the value of a variable. These operators are placed either before the variable or after the variable name. The example below shows the use of these operators.
Program Compilation and Running
When the operator ++ is placed after the variable name, first the assignment of the value of the variable takes place and then the value of the variable is incremented. This operation is also called post increment. Therefore the value of y1 will remain as 5 and the value of x1 will be 6. When the operator is placed before the variable, first increment of the variable takes place and then the assignment occurs. Hence the value x2 and y2 both will be 6. This operation is also called as pre increment. Similarly – – operator can be used to perform post decrement and pre decrement operations. If there is no assignment and only the value of variable has to be incremented or decremented then placing the operator after or before does not make difference.
3. Comparison Operators:-Comparison operators are used to compare two values and give the results.
List of Comparison Operators in Java
Operator
|
Meaning
|
Example
|
Remarks
|
= =
|
Equal
|
op1 = = op2
|
Checks if op1 is equal to op2
|
!=
|
Not Equal
|
op1 != op2
|
Checks if op1 is not equal to op2
|
<
|
Less than
|
op1 < op2
|
Checks if op1 is less than op2
|
>
|
Greater than
|
op1 > op2
|
Checks if op1 is greater than op2
|
<=
|
Less than or equal
|
op1 <= op2
|
Checks if op1 is less than or equal to op2
|
>=
|
Greater than or equal
|
op1 >= op2
|
Checks if op1 is greater than or equal to op2
|
4. Logical Operators:-Logical operators are used to perform Boolean operations on the operands.
List of Logical Operators in Java
Operator
|
Meaning
|
Example
|
Remarks
|
&&
|
Short-circuit AND
|
op1 && op2
|
Returns true if both are true. If op1 is false, op2 will not be evaluated and returns false.
|
||
|
Short-circuit OR
|
op1 || op2
|
Returns true if anyone is true. If op1 is true, op2 will not be evaluated and returns true.
|
!
|
Logical unary NOT
|
!op
|
Returns true if op is false.
|
&
|
Logical AND
|
Op1 & op2
|
Returns true if both are true. Always op1 and op2 will be evaluated.
|
|
|
Logical OR
|
Op1 | op2
|
Returns true if anyone is true. Always op1 and op2 will be evaluated.
|
4. What are the various character extraction functions available in Java?
Ans.-
charAt( ) :-To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method. It has this general form:
char charAt(int where)
Here, where is the index of the character that you want to obtain. The value of where must be nonnegative and specify a location within the string. charAt( ) returns the character at the specified location. For example,
char ch;
ch = "abc".charAt(1);
assigns the v0alue "b" to ch.
ch = "abc".charAt(1);
assigns the v0alue "b" to ch.
getChars( ) :-If you need to extract more than one character at a time, you can use the getChars( ) method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. Thus, the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring. The following program demonstrates getChars( ):
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
Here is the output of this program:
demo
getBytes( ) :-There is an alternative to getChars( ) that stores the characters in an array of bytes. This method is called getBytes( ), and it uses the default character-to-byte conversions provided by the platform. Here is its simplest form:
byte[ ] getBytes( )
Other forms of getBytes( ) are also available. getBytes( ) is most useful when you are exporting a String value into an environment that does not support 16-bit Unicode characters. For example, most Internet protocols and text file formats use 8-bit ASCII for all text interchange.
toCharArray( ) :-If you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ). It returns an array of characters for the entire string. It has this general form:
char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to use getChars( ) to achieve the same result.
5. What are the various types of relationships?
Ans.-Java represents two types of relationships:-
1.IS-A relationship
2.HAS-A relationship
2.HAS-A relationship
IS-A Relationship:-In programming, theconcept of IS-A is a totally based on Inheritance (extends) and Interface implementation (implements).It is just like saying "A is a B type of thing”. For example, 5-Star is a chocolate; Subaru Impreza is a car etc.
It is key point to note that you can easily identify the IS-A relationship .Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to be passed IS-A relationship.
It is key point to note that you can easily identify the IS-A relationship .Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to be passed IS-A relationship.
For Example:-
class Car{
// lots of complex work
}
class Impreza extends Car{
//Impreza extends and thus inherits all methods from Car (except final and static)
//Impreza can also define all his specific functionality
}
//Impreza extends and thus inherits all methods from Car (except final and static)
//Impreza can also define all his specific functionality
}
From the above code we can say "Car is a Vehicle","Impreza is a Car"; this in turn reflects a transitive relationship that "Impreza is a Vehicle".
The relationship can be shown as below:-
Arrow direction from subclass to super class
The relationship can be shown as below:-
Arrow direction from subclass to super class
HAS-A Relationship:-HAS-A relationship has nothing to do with Inheritance rather it is based on the usage of various variables and methods of other class. We can say "A HAS-A B if the code in class A has reference to an instance of B". Make it clearer look at following example:-
public class Car{}
class Impreza extends Car{
private Subaru_feature subaru_features;
}
As you can see Impreza HAS-An instance variable of type Subaru. That is we can say "Impreza HAS-A Subaru_feature ".Simply here Impreza has a reference type of Subaru_feature. Impreza can use the reference variable to invoke the subaru features without caring about the Subaru_feature code. HAS-A relationship is indicated by following figure:-
class Impreza extends Car{
private Subaru_feature subaru_features;
}
As you can see Impreza HAS-An instance variable of type Subaru. That is we can say "Impreza HAS-A Subaru_feature ".Simply here Impreza has a reference type of Subaru_feature. Impreza can use the reference variable to invoke the subaru features without caring about the Subaru_feature code. HAS-A relationship is indicated by following figure:-
HAS-A relationship makes each and every class a specialist class. Making specialists classes has numerous benefits including reduction in bugs, easily tractable errors ,Less complex code, reduction in code redundancy and most of code is easily understandable. The more specialist a class is the code reuse is even better. Its a good Object Oriented practice to use HAS-A relationship
6. Differentiate between errors and exceptions.
Ans.-An error is an irrecoverable condition occurring at runtime. Such as Out Of Memory error. These JVM errors and you can not repair them at runtime. Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.
While exceptions are conditions that occur because of bad input etc. e.g. File Not Found Exception will be thrown if the specified file does not exist. Or a Null Pointer Exception will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)
7. Give the syntax for FilelnputStream and FileOutputStream classes.
FileInputStream.read
public native int read() throws IOException
Returns
the next byte of data, or -1 if the end of the file is reached.
Description
Reads a byte of data from this input stream. This method blocks if no input is yet available.
Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream
public FileOutputStream( String name ) throws IOException
Parameters
name
the system-dependent filename.
Description
Creates an output file stream to write to the file with the specified name.
Exceptions
IOException if the file could not be opened for writing.
Exceptions
SecurityException if a security manager exists, its checkWrite method is called with the name argument to see if the application is allowed write access to the file.
8. What is an applet? Explain with an example.
Ans.-Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can't access system resources on the local computer. Applets are used to make the web site more dynamic and entertaining.
Example program
import java.awt.*;
import java.applet.*;
public class HelloJavaProgram extends Applet{
String str;
Public void init()
{
str=getParameter (“String”);
if(str==null)
str=”Java”;
str=”Hello” + str;
}
public void paint(Graphics g)
{
g.drawString (str,10,100);
}
}
import java.applet.*;
public class HelloJavaProgram extends Applet{
String str;
Public void init()
{
str=getParameter (“String”);
if(str==null)
str=”Java”;
str=”Hello” + str;
}
public void paint(Graphics g)
{
g.drawString (str,10,100);
}
}
Compile this program and the .class file will be generated.
HTML file for HelloJavaProgram applet
HTML file for HelloJavaProgram applet
<html>
<head>
<title> Welcome to Java Applet </title>
</head>
<body>
<applet code=” HelloJavaProgram.class” width= 400 height=200>
<param name=”String” value=”Applet!”>
</applet>
</body>
</html>
<head>
<title> Welcome to Java Applet </title>
</head>
<body>
<applet code=” HelloJavaProgram.class” width= 400 height=200>
<param name=”String” value=”Applet!”>
</applet>
</body>
</html>
Save this file as HelloJavaParam.html and then run applet using the applet viewer as follows:
appletviewer HelloJavaProgram.html
appletviewer HelloJavaProgram.html
9. Give the use of adapter class.
Ans.-In java programming language, adapter class is used to implement an interface having a set of dummy methods. The developer can then further subclass the adapter class so that he can override to the methods he requires. Implementing an interface directly, requires to write all the dummy methods. In general an adapter class is used to rapidly construct your own Listener class to field events.
Java programming language also have a design adapter named adapter. The Adapter design pattern is also used to join to two unrelated interfaces so that can work together. The joint between these two interfaces is termed as Adapter. This is something like the conversion of interface of one class into interface. This is done by using an Adapter.
Java programming language also have a design adapter named adapter. The Adapter design pattern is also used to join to two unrelated interfaces so that can work together. The joint between these two interfaces is termed as Adapter. This is something like the conversion of interface of one class into interface. This is done by using an Adapter.
10. What is JDBC? Explain.
Ans.-JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystems Java Database Connectivity in short called as JDBC. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the database in tabular format from Java code using a set of standard interfaces and classes written in the Java programming language.
JDBC has been developed under the Java Community Process that allows multiple implementations to exist and be used by the same application. JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc. The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture. Generally all Relational Database Management System supports SQL and we all know that Java is platform independent, so JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three programming activities:
1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to your query.
1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to your query.
Spring 2012
Bachelor of Science in Information Technology (BScIT) – Semester 3
BT0074 – OOPS with Java – 4 Credits (Book ID: B1002)
Assignment Set – 2 (60 Marks)
1. What is bytecode? Explain.
Ans.- Bytecode, also known as p-code (portable code), is a form of instruction set designed for efficient execution by a software interpreter. Unlike human-readable source code, bytecodes are compact numeric codes, constants, and references (normally numeric addresses) which encode the result of parsing and semantic analysisof things like type, scope, and nesting depths of program objects. They therefore allow much better performance than direct interpretation of source code.
The name bytecode stems from instruction sets which have one-byte opcodes followed by optional parameters. Intermediate representations such as bytecode may be output by programming languageimplementations to ease interpretation, or it may be used to reduce hardware and operating system dependence by allowing the same code to run on different platforms. Bytecode may often be either directly executed on a virtual machine (i.e. interpreter), or it may be further compiled into machine code for better performance.
Since bytecode instructions are processed by software, they may be arbitrarily complex, but are nonetheless often akin to traditional hardware instructions; virtual stack machines are the most common, but virtual register machineshave also been built. Different parts may often be stored in separate files, similar to object modules, but dynamically loaded during execution.
A bytecode program may be executed by parsing and directly executing the instructions, one at a time. This kind of bytecode interpreter is very portable. Some systems, called dynamic translators, or "just-in-time" (JIT) compilers, translate bytecode into machine language as necessary at runtime: this makes the virtual machine unportable, but doesn't lose the portability of the bytecode itself. For example, Javaand Smalltalkcode is typically stored in bytecoded format, which is typically then JIT compiled to translate the bytecode to machine code before execution. This introduces a delay before a program is run, when bytecode is compiled to native machine code, but improves execution speed considerably compared to direct interpretation of the source code—normally by several magnitudes. Please note that bytecode as mandatory step for performance improvement is currently challenged, ex: Google's V8and DartVM do direct translation of source code to JITed machine code without bytecode intermediary.
Because of its performance advantage, today many language implementations execute a program in two phases, first compiling the source code into bytecode, and then passing the bytecode to the virtual machine. Therefore, there are virtual machines for Java, Python, PHP, Forth, and Tcl. The implementation of Perl and Ruby 1.8instead work by walking an abstract syntax treerepresentation derived from the source code.
2. How do you compile a Java program?
Ans.- First, we should have JDK installed on our PC.. any version will do as long as it is JDK.
After installing JDK, we can now start to program.
1. Coding the Java Program.. here's a very simple java program. the HELLOWORLD program.. (copy the code below and paste it on a notepad. save it as HelloWorld.java, make sure the classname and the filename must be the same, java is case sensitive. and make sure you saved it as in .java file extension and not in .txt)
After installing JDK, we can now start to program.
1. Coding the Java Program.. here's a very simple java program. the HELLOWORLD program.. (copy the code below and paste it on a notepad. save it as HelloWorld.java, make sure the classname and the filename must be the same, java is case sensitive. and make sure you saved it as in .java file extension and not in .txt)
Code:
|
/** * The HelloWorld class implements an application that * simply prints \\"Hello World!\\" to standard output. */ class HelloWorld { public static void main(String[] args) { System.out.println(\\"Hello World!\\"); // Display the string. } } |
Notice the /**/ -- this is a block comment.. and the
// -- this is a line comment, the characters after // and along the line, will not display..
it's a great help if you put comments on your programs.. you'll not be confused when you are programming a huge java program..
2. Compiling Java Program
- click start >> run >>> type cmd.. then the command prompt should be there.
type in there, "cd C:\\Program Files\\Java\\jdk1.6.0_06\\bin" and press return(without quotes)
where C:\\Program Files\\Java\\jdk1.6.0_06\\bin is the directory path of my bin folder where my JDK is installed..
you will notice that from C:\\Documents and Settings\\onatlheen\\> will
become C:\\Program Files\\Java\\jdk1.6.0_06\\bin\\> [see figure below]
type in "javac C:\\java\\HelloWorld.java" [without quotes] and press return
*where C:\\java is the directory path of my java file.. and HelloWorld.java is the filename that i am compiling.
to know if it was compiled, a .class file with a same filename will create on the same folder where HelloWorld.java resides..
If you do not have the HelloWorld.class file, it was not compiled. repeat steps from the beginning CAREFULLY.. do not proceed on the next step, because you can't.. lol..
3. Running the Java Program
-on the command prompt, type in there "cd C:\\java" [without quotes] and press return
*where C:\\java is the directory path of my java program.
*to know the directory path of your java program, look at the address bar of the folder.
and finally type "java HelloWorld" [without quotes] and press return
// -- this is a line comment, the characters after // and along the line, will not display..
it's a great help if you put comments on your programs.. you'll not be confused when you are programming a huge java program..
2. Compiling Java Program
- click start >> run >>> type cmd.. then the command prompt should be there.
type in there, "cd C:\\Program Files\\Java\\jdk1.6.0_06\\bin" and press return(without quotes)
where C:\\Program Files\\Java\\jdk1.6.0_06\\bin is the directory path of my bin folder where my JDK is installed..
you will notice that from C:\\Documents and Settings\\onatlheen\\> will
become C:\\Program Files\\Java\\jdk1.6.0_06\\bin\\> [see figure below]
type in "javac C:\\java\\HelloWorld.java" [without quotes] and press return
*where C:\\java is the directory path of my java file.. and HelloWorld.java is the filename that i am compiling.
to know if it was compiled, a .class file with a same filename will create on the same folder where HelloWorld.java resides..
If you do not have the HelloWorld.class file, it was not compiled. repeat steps from the beginning CAREFULLY.. do not proceed on the next step, because you can't.. lol..
3. Running the Java Program
-on the command prompt, type in there "cd C:\\java" [without quotes] and press return
*where C:\\java is the directory path of my java program.
*to know the directory path of your java program, look at the address bar of the folder.
and finally type "java HelloWorld" [without quotes] and press return
3. What do you mean by operator precedence?
Ans.- Multiplication/Division vs. Addition/Subtraction:- Examine the Mathematica expression below. Try to predict what its value will be before you ask Mathematica to evaluate it. There seem to be two possibilities. If the addition is performed first, the result will be 4/2, which is 2. If the division is performed first the result will be 5/2. Which is it? Try it out and see.
1 + 3/2
The second possibility was correct: the division was performed first. We say that division takes precedence over addition.
Now consider this expression. What are two reasonable possible values? Which do you think Mathematica will find?
2 - 3 * 4
Here, the multiplication was performed prior to the subtraction. (Had the subtraction been performed first, the answer would have been -4.) We say that multiplication takes precedence over addition.
Now try the following experiments:
(1) In the first expression above, replace the + operator with a - operator and reevaluate. Which operator takes precedence, subtraction or division?
(2) In the second expression above, replace the - operator with a + operator and reevaluate. Which operator takes precedence, addition or multiplication?
(1) In the first expression above, replace the + operator with a - operator and reevaluate. Which operator takes precedence, subtraction or division?
(2) In the second expression above, replace the - operator with a + operator and reevaluate. Which operator takes precedence, addition or multiplication?
Your experiments should reveal that in Mathematica(as in most other programming languages) multiplication and division take precedence over addition and subtraction. We say that multiplication and division are at a higher level of precedence than are addition and subtraction.
Multiplication vs. Division and Addition vs. Subtraction:- What happens when an expression involves more than operator at the same level of precedence? (For example, more than one multiplication and division or more than one addition and subtraction.)
What would be two possible values for this expression?
2/3 * 4
The division was performed first (to obtain 2/3), and the result was then multiplied by 4 (to obtain 8/3). Had the multiplication been performed before the division, the result would have been 1/6.
This does not mean that multiplication takes precedence over division, however. In the absence of parentheses, multiplication and division are performed left to right. We say that multiplication and division are left associative.
Try to predict the outcome of each of the following calculations before you try it. If your prediction turns out to be incorrect, be sure to figure out where the flaw in your reasoning occurred.
2 * 3/4
2/3/4
4/3 * 2/5
6 * 3/4 * 5
Addition and subtraction are also left associative. In the absence of parentheses, addition and multiplication is performed from left to right. In rational arithmetic (at least in the absence of overlow) this does not make any difference, but in floating-point arithmetic it can become important.
The following two expressions are mathematically identical; they differ only in the fact that their last two terms have been interchanged. Evaluate them.
1 - 1 + 10.^-20
1 + 10.^-20 - 1
The answers are not the same! Why?
In the first expression, the subtraction is performed first and the result is zero. When zero is added to the number 10^-20, we end up with the result 10^-20.
In the second expression, the addition is performed first. With only 16 digits of mantissa, however, the number 10^-20 is the lost in the roundoff and the result is 1. The subtraction thus yields a result of zero. (This example shows that floating-point arithmetic need not satisfy the associative rule.)
Exponentiation:- What about the precedence of the exponentiation operator? See if you can figure out the rule by evaluating the following expressions:
4 * 3^2
1 + 3^2
5/2^3
3/10^3 * 7
Notice that in each of these examples, the exponentiation was performed first. This is indeed the way that it works: exponentiation has higher precedence than multiplication and division, which in turn have higher precedence than addition and multiplication.
Now try this expression.
2^3^4
The exponentiation operator is right-associative. Thus, the expression above is equivalent to
2^(3^4)
and not
(2^3)^4
Parentheses:- You can override Mathematica's precedence rules by using parentheses to group expressions in the order that you wish Mathematica to evaluate them. Here are some examples where we use parentheses to force a different evaluation order than Mathematicawould otherwise use.
2 * (3 + 4)
2^(3 * 4)
2/(3/3)
If you have any doubt, use parentheses to make sure Mathematica executes your expressions in the order in which you intend.
4. What is an array? Explain with examples.
Ans.- A collection of variables which are all of the same type. It is a data structure, which provides the facility to store a collection of data of same type under single variable name. Just like the ordinary variable, the array should also be declared properly. The declaration of array includes the type of array that is the type of value we are going to store in it, the array name and maximum number of elements.
Examples:
short val[ 200 ];
val[ 12 ] = 5;
Arrays have the same data types as variables, i.e., short, long, float etc.They are similar to variables: they can either be declared global or local.They are declared by the given syntax:
Datatype array_name[dimensions]={element1,element2,….,element}
5. How will you implement inheritance in Java?
Ans.- The extends keyword is used to derive a class from a superclass, or in other words, extend the functionality of a superclass.
Syntax
public class <subclass_name> extends <superclass_name>
Example
public class Confirmed extends Ticket {
}
Rules for Overriding Methods
· The method name and the order of arguments should be identical to that of the superclass method.
· The return type of both the methods must be the same.
· The overriding method cannot be less accessible than the method it overrides. For example, if the method to override is declared as public in the superclass, you cannot override it with the private keyword in the subclass.
· An overriding method cannot raise more exceptions than those raised by the superclass.
Example
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() { System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:"); subOb.sum();
}
}
The output from this program is shown here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
As you can see, the subclass B includes all of the members of its superclass, A. This is why subOb can access i and j and call showij ( ). Also, inside sum ( ), i and j can be referred to directly, as if they were part of B.
Even though A is a superclass for B, it is also a completely independent, stand-alone class. Being a superclass for a subclass does not mean that the superclass cannot be used by itself. Further, a subclass can be a superclass for another subclass.
The general form of a class declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}
You can only specify one superclass for any subclass that you create. Java does not support the inheritance of multiple superclasses into a single subclass. (This differs from C++, in which you can inherit multiple base classes.) You can, as stated, create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass. However, no class can be a superclass of itself.
6. Explain different kinds of Exceptions in Java.
Ans.- Java has several predefined exceptions. The most common exceptions that you may encounter are described below.
Arithmetic Exception:- This exception is thrown when an exceptional arithmetic condition has occurred. For example, a division by zero generates such an exception.
NullPointer Exception:- This exception is thrown when an application attempts to use null where an object is required. An object that has not been allocated memory holds a null value. The situations in which an exception is thrown include:
· Using an object without allocating memory for it.
· Calling the methods of a null object.
· Accessing or modifying the attributes of a null object.
ArrayIndexOutOfBounds Exception:- This exception is thrown when an attempt is made to access an array element beyond the index of the array. For example, if you try to access the eleventh element of an array that has only ten elements, the exception will be thrown.
7. What are the uses of stream class?
Ans.- Stream classes are described as following-
The FileInputStream and FileOutputStream Classes:- These streams are classified as mode streams as they read and write data from disk files. The classes associated with these streams have constructors that allow you to specify the path of the file to which they are connected. The FileInputStream class allows you to read input from a file in the form of a stream. The FileOutputStream class allows you to write output to a file stream.
Example:
FileInputStream inputfile = new FileInputStream (“Employee.dat”);
FileOutputStream outputfile = new FileOutputStream (“binus.dat”);
The BufferedInputStream and BufferedOutputStream Classes:- The BufferedInputStream class creates and maintains a buffer for an input stream. This class is used to increase the efficiency of input operations. This is done by reading data from the stream one byte at a time. The BufferedOutputStream class creates and maintains a buffer for the output stream. Both the classes represent filter streams.
The DataInputStream and DataOutputStream Classes:- The DataInputStream and DataOutputStream classes are the filter streams that allow the reading and writing of Java primitive data types. The DataInputStream class provides the capability to read primitive data types from an input stream. It implements the methods presents in the DataInput interface.
8. What is AWT? Explain.
Ans.- The Abstract Windowing Toolkit, also called as AWT is a set of classes, enabling the user to create a user friendly, Graphical User Interface (GUI). It will also facilitate receiving user input from the mouse and keyboard. The AWT classes are part of the java.awt package. The user interface consists of the following three:
· Components – Anything that can be put on the user interface. This includes buttons, check boxes, pop-up menus, text fields, etc.
· Containers – This is a component that can contain other components.
· Layout Manager – These define how the components will be arranged in a container.
The statement import java.awt.*; imports all the components, containers and layout managers necessary for designing the user interface.
9. What are the different components of an event?
Ans.- An event comprises of three components:
· Event Object – When the user interacts with the application by pressing a key or clicking a mouse button, an event is generated. The operating system traps this event and the data associated with it, for example, the time at which the event occurred, the event type (like a keypress or a mouseclick). This data is then passed on to the application to which the event belongs.
In Java, events are represented by objects that describe the events themselves. Java has a number of classes that describe and handle different categories of event.
· Event Source – An event source is an object that generates an event. For example, if you click on a button, an ActionEvent object is generated. The object of the ActionEvent class contains information about the event.
· Event-handler – An event-handler is a method that understands the event and processes it. The event-handler method takes an event object as a parameter.
10. Draw and explain the JDBC Application Architecture.
Ans.- JDBC is an API specification developed by Sun Microsystems that defines a uniform interface for accessing various relational databases. JDBC is a core part of the Java platform and is included in the standard JDK distribution.
The primary function of the JDBC API is to provide a means for the developer to issue SQL statements and process the results in a consistent, database-independent manner. JDBC provides rich, object-oriented access to databases by defining classes and interfaces that represent objects such as:
The primary function of the JDBC API is to provide a means for the developer to issue SQL statements and process the results in a consistent, database-independent manner. JDBC provides rich, object-oriented access to databases by defining classes and interfaces that represent objects such as:
· Database connections
· SQL statements
· Result Set
· Database metadata
· Prepared statements
· Binary Large Objects (BLOBs)
· Character Large Objects (CLOBs)
· Callable statements
· Database drivers
· Driver manager
The JDBC API uses a Driver Manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The Driver Manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC drivers and the servlet is shown in Figure 1.
Layers of the JDBC Architecture
Layers of the JDBC Architecture
A JDBC driver translates standard JDBC calls into a network or database protocol or into a database library API call that facilitates communication with the database. This translation layer provides JDBC applications with database independence. If the back-end database changes, only the JDBC driver need be replaced with few code modifications required. There are four distinct types of JDBC drivers.
Type 1 JDBC-ODBC Bridge. Type 1 drivers act as a "bridge" between JDBC and another database connectivity mechanism such as ODBC. The JDBC- ODBC bridge provides JDBC access using most standard ODBC drivers. This driver is included in the Java 2 SDK within the sun.jdbc.odbc package. In this driver the java statements are converted to a jdbc statements. JDBC statements calls the ODBC by using the JDBC-ODBC Bridge. And finally the query is executed by the database. This driver has serious limitation for many applications. (See Figure 2.)
Type 1 JDBC Architecture
Type 1 JDBC Architecture
Type 3 Java to Network Protocol Or All- Java Driver.Type 3 drivers are pure Java drivers that use a proprietary network protocol to communicate with JDBC middleware on the server. The middleware then translates the network protocol to database-specific function calls. Type 3 drivers are the most flexible JDBC solution because they do not require native database libraries on the client and can connect to many different databases on the back end. Type 3 drivers can be deployed over the Internet without client installation. (See Figure 4.)
Java-------> JDBC statements------> SQL statements ------> databases.
Type 3 JDBC Architecture
Java-------> JDBC statements------> SQL statements ------> databases.
Type 3 JDBC Architecture
Type 4 Java to Database Protocol.Type 4 drivers are pure Java drivers that implement a proprietary database protocol (like Oracle's SQL*Net) to communicate directly with the database. Like Type 3 drivers, they do not require native database libraries and can be deployed over the Internet without client installation. One drawback to Type 4 drivers is that they are database specific. Unlike Type 3 drivers, if your back-end database changes, you may save to purchase and deploy a new Type 4 driver (some Type 4 drivers are available free of charge from the database manufacturer). However, because Type drivers communicate directly with the database engine rather than through middleware or a native library, they are usually the fastest JDBC drivers available. This driver directly converts the java statements to SQL statements.
No comments:
Post a Comment