42
Master of Science in Information Technology (MScIT- NEW) – Semester 3 MT0045 –: Java– 2 Credits (Book ID: B0831) Assignment Set – 2 (20 Marks) 1. Explain the following features of java Multithreaded Distributed Multithreaded Multithreading allows two parts of the same program to run concurrently. This article discusses how to pull off this performance-improving feat in J A program or process can contain multiple threads that execute instructions according to program code. Like multiple processes that can run on one computer, multiple threads appear to be doing their work in parallel. Implemented on a multi-processor machine, they actually can work in parallel. Unlike processes, threads share the same address space; that is, they can read and write the same variables and data structuresava. In a multithreaded program, threads are obtained from the pool of available ready-to-run threads and run on the available system CPUs. The OS can move threads from the processor to either a ready or blocking queue, in which case

Master of Science in Information Technology (MScIT-NEW) – Semester 3

Embed Size (px)

Citation preview

Page 1: Master of Science in Information Technology (MScIT-NEW) – Semester 3

Master of Science in Information Technology (MScIT-NEW) –

Semester 3

MT0045 –: Java– 2 Credits

(Book ID: B0831)

Assignment Set – 2 (20 Marks)

1. Explain the following features of java

Multithreaded

Distributed

Multithreaded

Multithreading allows two parts of the same program to run concurrently. This article discusses how to pull off this performance-improving feat in J A program or process can contain multiple threads that execute instructions according to program code. Like multiple processes that can run on one computer, multiple threads appear to be doing their work in parallel. Implemented on a multi-processor machine, they actually can work in parallel. Unlike processes, threads share the same address space; that is, they can read and write the same variables and data structuresava.

In a multithreaded program, threads are obtained from the pool of available ready-to-run threads and run on the available system CPUs. The OS can move threads from the processor to either a ready or blocking queue, in which case the thread is said to have "yielded" the processor. Alternatively, the Java virtual machine (JVM) can manage thread movement -- under either a cooperative or preemptive model -- from a ready queue onto the processor, where the thread can begin executing its program code.

Cooperative threading allows the threads to decide when they should give up the processor to other waiting threads. The application developer determines exactly when threads will yield to other threads, allowing them to work very efficiently with one another. A disadvantage is that a malicious or poorly written thread can starve other threads while it consumes all available CPU time.

Page 2: Master of Science in Information Technology (MScIT-NEW) – Semester 3

Under the preemptive threading model, the OS interrupts threads at any time, usually after allowing them to run for a period of time (known as a time-slice). As a result, no thread can ever unfairly hog the processor. However, interrupting threads at any time poses problems for the program developer. Using our office example, consider what would happen if a worker preempts another worker making copies halfway through her copy job: the new worker would start his copy job on a machine that already has originals on the glass or copies in the output tray. The preemptive threading model requires that threads use shared resources appropriately, while the cooperative model requires threads to share execution time. Because the JVM specification does not mandate a particular threading model, Java developers must write programs for both models. We'll see how to design programs for either model after looking a bit at threads and communication among threads

DistributedJava Distributed Computing offers a general introduction to distributed computing, meaning programs that run on two or more systems. It focuses primarily on how to structure and write distributed applications and discusses issues like designing protocols, security, working with databases, and dealing with low bandwidth situations

Features of Distributed Object SystemsFrom our exercise in the previous section, we uncovered some of the features that distributed object systems need. These features, plus some others, are illustrated in Figure 3-1. An object interface specification is used to generate a server implementation of a class of objects, an interface between the object implementation and the object manager, sometimes called an object skeleton, and a client interface for the class of objects, sometimes called an object stub. The skeleton will be used by the server to create new instances of the class of objects and to route remote method calls to the object implementation. The stub will be used by the client to route transactions (method invocations, mostly) to the object on the server. On the server side, the class implementation is passed through a registration service, which registers the new class with a naming service and an object manager, and then stores the class in the server's storage for object skeletons.

1

Page 3: Master of Science in Information Technology (MScIT-NEW) – Semester 3

Figure 3-1. General architecture for distributed object systems

 With an object fully registered with a server, the client can now request an instance of the class through the naming service. The runtime transactions involved in requesting and using a remote object are shown in Figure 3-2. The naming service routes the client's request to the server's object manager, which creates and initializes the new object using the stored object skeleton. The new object is stored in the server's object storage area, and an object handle is issued back to the client in the form of an object stub interface. This stub is used by the client to interact with the remote object.

2. Write a simple Java program to convert rupees to dollars.

public static String toCurrency(double a){ //Format for money use //Variales String b = String.valueOf(a).replace(",", "."); //Is there a decimal symbol? if (b.indexOf(".") == -1){b = b+".";} //Format string if (b.indexOf(".") == 0){b = "0"+b;} if(b.length() - b.indexOf(".") >= 4){ //More than 2 decimals

2

Page 4: Master of Science in Information Technology (MScIT-NEW) – Semester 3

int unit = Integer.parseInt(b.substring(0, b.indexOf("."))); int first = Integer.parseInt(b.substring(b.indexOf(".")+1, b.indexOf(".")+2)); int second = Integer.parseInt(b.substring(b.indexOf(".")+2, b.indexOf(".")+3)); int third = Integer.parseInt(b.substring(b.indexOf(".")+3, b.indexOf(".")+4)); if (third >= 5){ //Round third = 0;second += 1; if (second >= 10){ second = 0;first += 1; if (first >= 10){ first = 0;unit += 1; } } } b = unit + "." + first + second; } else{ if (b.indexOf(".") == b.length()-1){b = b+"00";} //0 decimal if (b.indexOf(".") == b.length()-2){b = b+"0";} //1 decimal } //Return result return b; }

3. What is array? Explain with example

An array is an ordered set of values grouped together under a single variable name created by using an Array object constructor. You can create an Array literal by specifying the name of the array and the values of all its elements. The following example creates an array of three elements

The elements of an array are indexed using their ordinal number, starting with 0. You could, therefore, refer to the second element in the above array ("Ford") as 'cars[1]'. You can specify the number of elements in a new array by using a single numeric parameter with the Array constructor.  For example, the following code creates an array of 7 elements:  Code: fruit = new Array(7)

3

Page 5: Master of Science in Information Technology (MScIT-NEW) – Semester 3

 If you create an array with a single numeric parameter, that number is stored in the length property, and the array doesn't actually have any elements until some are specifically assigned to it. If, however, the parameter is not a number, an array of 1 element is created and that value assigned to it. You can easily increase the size of an array by assigning a value to an element higher than its current length.  NOTE:  If you specify 'language="Javascript1.2"' in the <SCRIPT> tag and use a single numeric parameter with the Array constructor, it will be seen as the value of a single element of the array rather than the number of elements you want that array to contain.  PROPERTIES  constructor Property The constructor property contains the function that created an object's prototype.  Syntax: object.constructor  index Property The read-only index property for an array created by a regular expression match and containing the zero-based index of that match.  Syntax: object.index  input Property The read-only input property for an array created by a regular expression match and containing the original string against which the match was made.  Syntax: object.input  length Property The length property holds an unsigned 32 bit integer representing the length of the array. It can be altered independently of the number of elements in the array.  Syntax: object.length  prototype Property The prototype property allows the addition of properties to an array.  Syntax: object.prototype

4

Page 6: Master of Science in Information Technology (MScIT-NEW) – Semester 3

 METHODS  concat Method The concat method joins two or more Array objects producing one new one. The original Array objects are unaffected by this but, if one copy of a string or number is altered, it is not reflected in the other, whereas a change to an object reference can be seen in both copies.  Syntax: Array.concat(arrayName2, arrayName3, ..., arrayNameN)  join Method The join method is used to join all the elements of an array into a single string separated by a specified string separator (if none is specified, the default is a comma).  Syntax: Array.join(separator)  

pop Method The pop method is used to remove and return the last element of an array. This affects the length of the array.  Syntax: Array.pop()  

push Method The push method is used to add one or more elements to an array, returning the new length of it. This affects the length of the array.  Syntax: Array.push(element1, ..., elementN)  reverse Method The reverse method, as the name implies, reverses the order of the elements in an array making the first last and the last first. Syntax: Array.reverse()  

shift Method The shift method removes and returns the first element of an array. This affects the length of the array.  Syntax: Array.shift()  

slice Method 5

Page 7: Master of Science in Information Technology (MScIT-NEW) – Semester 3

The slice method creates a new array from a selected section of an array.  Syntax: Array.slice(begin[,end])  

splice Method The splice method is used to add and/or remove elements of an array.  Syntax; Array.splice(index, howMany, [element1][, ..., elementN])  sort Method The sort method sorts the elements of an array.  Syntax: Array.sort(compareFunction)  

toSource Method The toSource method is inherited from the Object object and returns the source code of the array. For details see the Object.toSource method.  Syntax: Array.toSource()  toString Method The toString method is inherited from the Object object and returns a string representing the specified array and its elements. For more details see the Object.toString method.  Syntax: Array.toString()  

unshift Method The unshift method adds one or more elements to the beginning of an array and returns the new length.  Syntax: Array.unshift(element1,..., elementN)  valueOf Method The valueOf method is inherited from the Object object and returns a primitive value for a specified array. For details see the Object.valueOf method.  Syntax: Array.valueOf()

JavaScript Array

6

Page 8: Master of Science in Information Technology (MScIT-NEW) – Semester 3

An array is a variable that can store many variables within it. Many programmers have seen arrays in other languages, and they aren't that different in JavaScript.

The following points should always be remembered when using arrays in JavaScript:

← The array is a special type of variable. ← Values are stored into an array by using the array name and by stating the location

in the array you wish to store the value in brackets. Example: myArray[2] = "Hello World";

← Values in an array are accessed by the array name and location of the value. Example: myArray[2];

← JavaScript has built-in functions for arrays, so check out these built-in array functions before writing the code yourself!

Creating a JavaScript Array

Creating an array is slightly different from creating a normal variable. Because JavaScript has variables and properties associated with arrays, you have to use a special function to create a new array. This example shows how you would create a simple array, store values to it, and access these values.

JavaScript Code:

<script type="text/javascript">

<!—

var myArray = new Array();

myArray[0] = "Football";

myArray[1] = "Baseball";

myArray[2] = "Cricket";

document.write(myArray[0] + myArray[1] + myArray[2]);

//-->

</script>

7

Page 9: Master of Science in Information Technology (MScIT-NEW) – Semester 3

Notice that you set values and get values from an array by specifying the position, in brackets, of the value you want to use.

JavaScript Array Sorting

Imagine that you wanted to sort an array alphabetically before you wrote the array to the browser. Well, this code has already been written and can be accessed by using the Array's sort method.

JavaScript Code:

<script type="text/javascript">

<!--

var myArray2= new Array();

myArray2[0] = "Football";

myArray2[1] = "Baseball";

myArray2[2] = "Cricket";

myArray2.sort();

document.write(myArray2[0] + myArray2[1] + myArray2[2]);

//-->

</script>

JavaScript Array: Other ResourcesArrays are a very complex area of programming, especially in JavaScript. This lesson cannot possibly cover all the areas of JavaScript arrays, but we have compiled some useful resources for you to check out!

8

Page 10: Master of Science in Information Technology (MScIT-NEW) – Semester 3

4. Write a program to explain the Exception Handling mechanisms in Java using the keywords: try, catch and finally

The exception handling mechanisms in Java provide a clean way to check for errors without cluttering code. Exceptions also provide a means to signal errors directly rather than use flags or side effects such as fields that must be checked. Exceptions make the error conditions that a method can signal an explicit part of the methods contract. The list of exceptions can be seen by the programmer, checked by the compiler and preserved by extended classes that override the method.

Traditional error handling methods include Boolean functions (which return TRUE/FALSE), integer functions (returns –1 on error) and other return arguments and special values [1] . Some of the drawbacks associated with these methods are that the programmer must remember to check for the return codes, it can lead to diminished readability of the source code, and one cannot rely on the functions being consistent [2].

In Java, an exception is thrown when an unexpected error condition is encountered. The exception is then caught by an encompassing clause further up the method stack. If the exception is not caught, a default exception handler takes effect, usually printing useful information about where the exception was thrown (such as a call stack). However, this method of handling exceptions is not a silver bullet.

Exceptions in Java are objects. All exception types must extend the Java language class Throwable or one of its subclasses. By convention, new exception types extend Exception, a subclass of Throwable. Java exceptions are primarily checked exceptions i.e. the compiler verifies that methods throw only exceptions that they have declared.

Java also avoids some of the problems with the exception handling mechanisms of C++, by providing a finally clause. In C++, when an exception leaves the scope of a function, all objects which are allocated on the stack are reclaimed, and their destructors are called. Thus, if you want to free a resource or otherwise clean something up when an exception passes by, you must put that code in the destructor of an object. This is artificial, error prone, and inconvenient [4]. Every scope in Java can have a 'finally' clause. Any time a scope is exited, regardless of the reason for that exit (e.g. the function could simply return, or an exception could pass through it) the code in the finally clause is executed. Thus, cleanup code does not have to be artificially put into some destructor. This makes Java exceptions much easier to use than C++ exceptions.

Exceptions are thrown using a throw statement, which takes an object as a parameter [5]. An exception can also be generated by invoking a method that itself throws an exception. The throws clause takes a comma separated list of exception types. The contract defined

9

Page 11: Master of Science in Information Technology (MScIT-NEW) – Semester 3

by the throws clause is strictly enforced i.e. one can only throw an exception that has been declared in the throws clause. This helps avoid bugs that result from not handling errors since this states which exceptions are being thrown by methods and makes sure they are dealt with in some way by the invoker.

Exceptions are caught by enclosing code in try blocks [5]. The body of the try statement is executed until either an exception is thrown or it finishes successfully. If an exception is thrown, each catch clause is examined in turn from first to last to see whether the type of the exception object is assignable to the type declared in catch. Any number of catch clauses can be associated with a particular try as long as each clause catches a different type of exception.

If a finally clause is present in a try, its code is executed after all the processing in the try is complete [5]. This happens regardless of how the completion was achieved i.e. normally, through an exception or through a control flow statement like return or break.

A significant deficiency in Java’s exception handling mechanism is the absence of Design by Contract. One of the goals of this project is to examine its impact on Java, describe how Design By Contract can be used to complement Java’s exception mechanism and provide an overview of the various techniques of implementing Design by Contract in Java

Java Exception - Exception Handling in Java

Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs that occurs during the program execution. During the program execution if any error occurs and you want to print your own message or the system message about the error then you write the part of the program which generate the error in the try{} block and catch the errors using catch() block. Exception turns the direction of normal flow of the program control and send to the related catch() block. Error that occurs during the program execution generate a specific object which has the information about the errors occurred in the program.

In the following example code you will see that how the exception handling can be done in java program. This example reads two integer numbers for the variables a and b. If you enter any other character except number ( 0 - 9 ) then the error is caught by NumberFormatException object. After that ex.getMessage() prints the information about the error occurring causes.

10

Page 12: Master of Science in Information Technology (MScIT-NEW) – Semester 3

Code of the program : 

import java.io.*;

public class exceptionHandle{  public static void main(String[] args) throws Exception{    try{      int a,b;      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));      a = Integer.parseInt(in.readLine());      b = Integer.parseInt(in.readLine());    }    catch(NumberFormatException ex){      System.out.println(ex.getMessage() + " is not a numeric value.");      System.exit(0);    }  }}

11

Page 13: Master of Science in Information Technology (MScIT-NEW) – Semester 3

Master of Science in Information Technology (MScIT-NEW) –

Semester 3

MT0045 –: Java– 2 Credits

(Book ID: B0831)

Assignment Set – 2 (20 Marks)

1. What are the uses of stubs and skeleton?

DESCRIPTIONjavah generates C header and source files that are needed to implement native methods. The generated header and source files are used by C programs to reference an object's instance variables from native source code. The .h file contains a struct definition whose layout parallels the layout of the corresponding class. The fields in the struct correspond to instance variables in the class.

The name of the header file and the structure declared within it are derived from the name of the class. If the class passed to javah is inside a package, the package name is prepended to both the header file name and the structure name. Underscores (_) are used as name delimiters.

By default javah creates a header file for each class listed on the command line and puts the files in the current directory. Use the -stubs option to create source files. Use the -o option to concatenate the results for all listed classes into a single file.

The new native method interface, Java Native Interface (JNI), does not require header information or stub files. javah can still be used to generate native method function proptotypes needed for JNI-style native methods. javah produces JNI-style output by default, and places the result in the .h file.

javah_g is a non-optimized version of javah suitable for use with debuggers like jdb.

OPTIONS-o outputfile

Concatenates the resulting header or source files for all the classes listed on the command line into outputfile. Only one of -o or -d may be used.

-d directory

12

Page 14: Master of Science in Information Technology (MScIT-NEW) – Semester 3

Sets the directory where javah saves the header files or the stub files. Only one of -d or -o may be used.

-stubs Causes javah to generate C declarations from the Java object file.

-verbose Indicates verbose output and causes javah to print a message to stdout concerning the status of the generated files.

-help Print help message for javah usage.

-version Print out javah version information.

-jni Causes javah to create an output file containing JNI-style native method function prototypes. This is the default output, so use of -jni is optional.

-classpath path Specifies the path javah uses to look up classes. Overrides the default or the CLASSPATH environment variable if it is set. Directories are separated by semi-colons. Thus the general format for path is: .;<your_path>

For example: .;C:\users\dac\classes;C:\tools\java\classes

As a special convenience, a class path element containing a basename of * is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR (a java program cannot tell the difference between the two invocations).

For example, if directory foo contains a.jar and b.JAR, then the class path element foo/* is expanded to a A.jar:b.JAR, except that the order of jar files is unspecified. All jar files in the specified directory, even hidden ones, are included in the list. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory. The CLASSPATH environment variable, where defined, will be similarly expanded. Any classpath wildcard expansion occurs before the Java virtual machine is started -- no Java program will ever see unexpanded wildcards except by querying the environment. For example; by invoking System.getenv("CLASSPATH").

-bootclasspath path Specifies path from which to load bootstrap classes. By default, the bootstrap classes are the classes implementing the core Java platform located in jre\lib\rt.jar and several other jar files.

-old 13

Page 15: Master of Science in Information Technology (MScIT-NEW) – Semester 3

Specifies that old JDK1.0-style header files should be generated. -force

Specifies that output files should always be written. -Joption

Pass option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes.

ENVIRONMENT VARIABLESCLASSPATH

Used to provide the system a path to user-defined classes. Directories are separated by semi-colons, for example, .;C:\users\dac\classes;C:\tools\java\classes

Creating stubs for Java components

Stubs are classes that provide replacement implementations for the actual classes that the code you are testing interacts with. You can define a stub of a Java™ class and reuse that stub in multiple tests. Once you create the stub, you define its behavior in the stub data table or you enter code in the user code class that is associated with the stub.

To create a stub for a Java component:1. Click File > New > Other > Component Test > Java > Java Component Stub and click Next. 2. On the first wizard page, do one of the following:

o Select the test project that will contain the stub and click Next. o Or click New to create a new test project.

3. Select the Java source files or libraries that you want to stub and click Finish. If the stub component already exists, the wizard prompts you to replace the existing stub. If you select Yes or Yes to All, then any changes you have made to the existing stub will be overwritten. If you select No or No to All, then the existing files remain unchanged and a new stub is not generated.

4. In the Test Navigator view, double-click the test suite that you want to add the stub to. This opens the Test Suite editor.

5. In the Test Suite editor, click the Stubs tab, click Add, select the stub you want to add to the test suite, and click Finish. Note: To create a new stub and add it automatically to the test suite, click New and proceed with Step 3.

To replace the stub with the real class at any time, simply remove the stub from the test suite

2. Interface Skeleton

Deprecated. no replacement. Skeletons are no longer required for remote method calls in the Java 2 platform v1.2 and greater. public interface Skeleton

14

Page 16: Master of Science in Information Technology (MScIT-NEW) – Semester 3

The Skeleton interface is used solely by the RMI implementation.

Every version 1.1 (and version 1.1 compatible skeletons generated in 1.2 using rmic -vcompat) skeleton class generated by the rmic stub compiler implements this interface. A skeleton for a remote object is a server-side entity that dispatches calls to the actual remote object implementation.

RMI (Remote Method Invocation) -Java Core RMI concept.This is an illustration of howto use RMI in form of a sampleexample.RMI is useful in multi JVM orclustered environment, wherea single object is referencedfrom one or more JVMs.Object of type Remote, areMarshalled and unmarshalledand moved from JVM to JVM,in multiple server instances.

Let us examine a sample rmiexample for understandinghow rmi functions. We requirethree Java files, such asTestRemote.java, a remoteinterface, acts like an interfaceto the client.

A TestRemoteObj.java, a Remote Object, thatprovides implementation to the remote interface and isserialized and used for storing into the registry.We require a client I2WRemoteServer.java file as clientfor this example.Now one can rewrite or copy and create two java files,as shown below:

TestRemote.java/*** This code is provided "AS IS", without warranty of any kind.* This is a sample code, might be not completely error free.* This site or author of this code doesn't take any responsibility* what so ever resulting out of usage of this code.*/

import java.rmi.*;

public interface TestRemote extends Remote{ public void setName(String argName) throws RemoteException; public String getName() throws RemoteException;}

15

Page 17: Master of Science in Information Technology (MScIT-NEW) – Semester 3

This is the interface that is of type Remote (extends java.rmi.Remote)and has all the business methods implemented.

Now a Remote object TestRemoteObj.java, is implementing thisremote interface (TestRemote) and extendsjava.rmi.server.UnicastRemoteObject

TestRemoteObj.java/*** This code is provided "AS IS", without warranty of any kind.* This is a sample code, might be not completely error free.* This site or author of this code doesn't take any responsibility* what so ever resulting out of usage of this code.*/

import java.rmi.*;import java.rmi.server.*;

public class TestRemoteObj extends UnicastRemoteObject implements TestRemote { String name; public TestRemoteObj() throws RemoteException { super(); } public void setName(String argName) { name=argName; } public String getName() { return name; }}

This class implements all the business methods and is usedfor binding to rmi registry purposes.

Now we require a client java file, namely I2WRemoteServer.java.

I2WRemoteServer.java/*** This code is provided "AS IS", without warranty of any kind.* This is a sample code, might be not completely error free.* This site or author of this code doesn't take any responsibility* what so ever resulting out of usage of this code.*/

import java.rmi.*;import java.rmi.server.*;import java.rmi.registry.*;

public class I2WRemoteServer{public I2WRemoteServer()

16

Page 18: Master of Science in Information Technology (MScIT-NEW) – Semester 3

{try{

Registry reg = LocateRegistry.getRegistry(9999);TestRemoteObj testRemote = new TestRemoteObj();testRemote.setName("some name");reg.bind("testremote",testRemote);System.out.println((reg.list()).length);TestRemote testRemote1 = (TestRemote)reg .lookup("testremote");System.out.println(testRemote1.getName());System.exit(0);

}catch(Exception ex){

ex.printStackTrace();}

}

public static void main(String[] args){

new I2WRemoteServer();}}

This class is self explanatory, there is LocateRegistry class,that find the registry at 9999 port.By creating an object of TestRemoteObj, setting some initialvalues for name and binding this to the registry and then,looking up for the same object and printing out the value ofthe name variable.

Before really executing the client, one has to compile allthese Java files, thereby creating STUB (represents server) andskeleton (represents client), by using rmic.exe, as below:

rmic.exe TestRemoteObject

After successfully running rmic, one shall see two additionalclass files are created,namely "TestRemoteObj_Stub.class","TestRemoteObj_Skel.class".If wanted to see the implementation of these two files,use -keep option while running rmic , like as shown below:

rmic -keep TestRemoteObj

Now starting the rmiregistry with a port number 9999, by a command

rmiregistry 9999

Now opening up another command prompt and going to the directoryAnd setting appropriate classpath, (set classpath=.;%classpath%),if not set already and then running the client (I2WRemoteServer.java)

one can see the following output,

17

Page 19: Master of Science in Information Technology (MScIT-NEW) – Semester 3

2. Write a Java program demonstrating the usage of all the primitive / standard data types.

Primitive data type

a basic type is a data type provided by a programming language as a basic building block. Most languages allow more complicated composite types to be recursively constructed starting from basic types.

a built-in type is a data type for which the programming language provides built-in support.

In most programming languages, all basic data types are built-in. In addition, many languages also provide a set of composite data types. Opinions vary as to whether a built-in type that is not basic should be considered "primitive".[citation needed]

Depending on the language and its implementation, primitive data types may or may not have a one-to-one correspondence with objects in the computer's memory. However, one usually expects operations on basic primitive data types to be the fastest language constructs there are.[citation needed] Integer addition, for example, can be performed as a single machine instruction, and some processors offer specific instructions to process sequences of characters with a single instruction. In particular, the C standard mentions that "a 'plain' int object has the natural size suggested by the architecture of the execution environment". This means that int is likely to be 32 bits long on a 32-bit architecture. Basic primitive types are almost always value types.

Most languages do not allow the behavior or capabilities of primitive (either built-in or basic) data types to be modified by programs. Exceptions include Smalltalk, which permits all data types to be extended within a program, adding to the operations that can be performed on them or even redefining the built-in operations.

Overview

Almost all programming languages explicitly include the notion of data type, though different languages may use different terminology. Most programming languages also allow the programmer to define additional data types, usually by combining multiple elements of other types and defining the valid operations of the new data type. For example, a programmer might create a new data type named "Person" that specifies that data interpreted as Person would include a name and a date of birth. Common data types may include:

integers ,

18

Page 20: Master of Science in Information Technology (MScIT-NEW) – Semester 3

floating-point numbers (decimals), and alphanumeric strings.

Primitive Data TypesThe Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen: int gear = 1;Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.

long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.

float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large

19

Page 21: Master of Science in Information Technology (MScIT-NEW) – Semester 3

arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

II . Standard Data Types, Predefined Operators, and Functions

C-XSC provides the simple numerical data types

real, interval, complex, and cinterval (complex interval)

with their appropriate arithmetic and relational operators and mathematical standard functions. All predefined arithmetic operators deliver results with an accuracy of at least 1 ulp (unit in the last place). Thus, they are of maximum accuracy in the sense of scientific computing. The rounding of the arithmetic operators may be controlled using the data types interval and cinterval. Type casting functions are available for all mathematically useful combinations. Literal constants may be converted with maximum accuracy. All mathematical standard functions for the simple numerical data types may be called by their generic names and deliver results with guaranteed high accuracy for arbitrary permissible arguments. The standard functions for the data types interval and cinterval provide range inclusions which are sharp bounds.

20

Page 22: Master of Science in Information Technology (MScIT-NEW) – Semester 3

  Table 1: Mathematical Standard Functions

For the scalar data types presented above, vector and matrix types are available:

rvector, ivector, cvector, and civector,rmatrix, imatrix, cmatrix, and cimatrix. The user can allocate or deallocate storage space for a dynamic array (vector or matrix) at run time. Thus, without recompilation, the same program may use arrays of size restricted

21

Page 23: Master of Science in Information Technology (MScIT-NEW) – Semester 3

only by the storage of the computer. Furthermore, the memory is used efficiently, since the arrays are stored only in their required sizes. When accessing components of the array types, the index range is checked at run time to provide increased security during programming by avoiding invalid memory accesses.

  Table 2: Predefined Arithmetic Operators

Example: Allocation and resizing of dynamic matrices:

... int n, m; cout << "Enter the dimensions n, m:"; cin >> n >> m;

imatrix B, C, A(n, m); /* A[1][1] ... A[n][m] */

22

Page 24: Master of Science in Information Technology (MScIT-NEW) – Semester 3

Resize(B, m, n); /* B[1][1] ... B[m][n] */... C = A * B; /* C[1][1] ... C[n][n] */

Defining a vector or a matrix without explicitly indicating the index bounds results in a vector of length 1 or in a 1x1 matrix. The storage for the object is not allocated until run time. Here, we use the Resize statement (see example above) to allocate an object of the desired size. Alternatively, the index bounds may be determined when defining the vector or matrix as we did in the example above with matrix A.

An implicit resizing of a vector or a matrix is also possible during an assignment: If the index bounds of the object on the right-hand side of an assignment do not correspond to those of the left-hand side, the object is changed correspondingly on the left side as shown in the example above with the assignment C = A * B.

The storage space of a dynamic array that is local to a subprogram is automatically released before control returns to the calling routine.

The size of a vector or a matrix may be determined at any time by calling the functions Lb() and Ub() for the lower and upper index bounds, respectively.

3. What are the difference between an interface and an abstract class.

Introduction: There are lost of discussion on the internet about the Interface vs Abstract class. Also, as base class whether we have to use interface, abstract class or normal class. I am trying to point out few considerations on which we can take decision about Interface vs Abstract class vs Class. Abstract Class vs Interface I am assuming you are having all the basic knowledge of abstract and interface keyword. I am just briefing the basics.We can not make instance of Abstract Class as well as Interface. Here are few differences in Abstract class and Interface as per the definition.Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract. 

23

Page 25: Master of Science in Information Technology (MScIT-NEW) – Semester 3

            //Abstarct Classpublic abstract class Vehicles

      {        private int noOfWheel;        private string color;        public abstract string Engine        {               get;            set;        }        public abstract void Accelerator();      }      //Interface

public interface Vehicles       {        string Engine        {               get;            set;        }        void Accelerator();      } 

We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed.We use abstract class and Interface for the base class in our application.  This is all about the language defination. Now million doller question: How can we take decision about when we have to use Interface and when Abstract Class.Basicly abstact class is a abstract view of any realword entity and interface is more abstract one. When we thinking about the entity there are two things one is intention and one is implemntation. Intention means I know about the entity and  also may have idea about its state as well as behaviour but don’t know about how its looks or works or may know partially. Implementation means actual state and behaviour of entity.   Enough theory lets take an example.I am trying to make a Content Management System where content is a genralize form of article, reviews, blogs etc.

 

24

Page 26: Master of Science in Information Technology (MScIT-NEW) – Semester 3

So content is our base class now how we make a decision whether content class should be Abstract class, Interface or normal class.First normal class vs other type (abstract and interface). If content is not a core entity of my application means as per the business logic if content is nothing in my application only Article, Blogs, Review are the core part of business logic then content class should not be a normal class  because I’ll never make instance of that class. So if you will never make instance of base class then Abstract class and Interface are the more appropriate choice.

As you can see content having behavior named “Publish”. If according to my business logic Publish having some default behavior which apply to all I’ll prefer content class as an Abstract class. If there is no default behavior for the “Publish” and every drive class makes their own implementation then there is no need to implement “Publish” behavior in  the base case I’ll prefer Interface.These are the in general idea of taking decision between abstract class, interface and normal class. But there is one catch. As we all know there is one constant in software that is “CHANGE”. If I made content class as Interface then it is difficult to make changes in base class because if I add new method or property in content interface then I have to implement new method in every drive class. These problems will over come if you are using abstract class for content class and new method is not an abstract type. So we can replace interface with abstract class except multiple inheritance.CAN-DO and IS-A relationship is also define the deference between Interface and abstract class. As we already discuss Interface can be use for multiple inheritance for example we have another interface named “ICopy” which having behavior copy and every drive class have to implements its own implementation of Copy. If “Article” class drive from abstract class Content as well as ICopy then article “CAN-DO” copy also.IS-A is for “generalization” and “specialization” means content is a generalize form of Article, Blogs, Review and Article, Blogs, Review are a specialize form of Content.So, abstract class defines core identity. If we are thinking in term of speed then abstract is fast then interface because interface requires extra in-direction. So as per my view Abstract class having upper-hand in compare to interface. Using interface having only advantage of multiple inheritance. If you don’t understand the things then don’t worry because it’s my mistake because I am not able to describe the topic.

25

Page 27: Master of Science in Information Technology (MScIT-NEW) – Semester 3

4. explain the procedure for connecting to the database

UseThis procedure enables you to connect to a remote database and display an installed AS Java configuration.

Procedure...

Start the Config Tool by double clicking the configtool script file in <SAP_install_dir>/<system_name>/<instance_name>/j2ee/configtool directory.

In the Connection settings dialog window, choose “Yes” if you want to connect to the default database, or “No” to connect to a different one.

The default database connecting is via the Secure Store.

1. If you set the “Do not ask me again” indicator, the next time you start the Config Tool, it will automatically connect to the default database.

To connect to a different database, remove the config.properties file from the configtool directory and restart the Config Tool.

1. If you want the Connection settings dialog box to appear again on startup, select View ® Startup options. Then, in the dialog window, set the Show connection dialog indicator.

The other way to reset the startup options is when you delete the visual.propertiesfile. Then, start the Config Tool.

In the Connect dialog window, choose whether to connect via secure store or via direct login and enter the required data in the relevant fields.

Connection Settings

Secure Store Settings

Description Example

Secure Store File

Contains the path to the secure store properties file. This file is encrypted for security reasons.

C:/usr/sap/CE1/SYS/global/security/data/ SecStore.properties

Secure Store Key File

Contains the path to the secure store key file. The key file contains the password for the encrypted store file.

C:/usr/sap/CE1/SYS/global/security/data/ SecStore.key

26

Page 28: Master of Science in Information Technology (MScIT-NEW) – Semester 3

System Name

Displays the name of the system to which this data applies.

CE1

Secure Store Lib

Specifies the security directory. It contains IAIK JAR files you need to use to open the Secure Store.

C:/usr/sap/CE1/SYS/global/security/lib

RDBMS Connections

A property key, by which the value contains the DB connection settings.

jdbc/pool/CE1

Direct Login Settings

Description Example

RDBMS URL

Specifies the URL for the database connection in the correct format for the corresponding driver.

jdbc:sapdb://sofD60163517A/CE1?timeout=0&spaceoption=true&unicode=true

Driver name

Specifies the class name of the JDBC driver to be used for database connections.

com.sap.dbtech.jdbc.DriverSapDB

RDBMS user

Specifies the user name for this database connection.

SAPCE1DB

RDBMS password

Specifies the password for the user of this database connection.

<Instalation SAP NetWeaver AS Java password>

IAIK Library

Specifies the IAIK JAR files directory. It enables the encrypting and decrypting of the properties file.

;C:\usr\sap\CE1\SYS\global\security\lib\tools\iaik_jce.jar; C:\usr\sap\CE1\SYS\global\security\lib\tools\iaik_jsse.jar; C:\usr\sap\CE1\SYS\global\security\lib\tools\iaik_smime.jar; C:\usr\sap\CE1\SYS\global\security\lib\tools\iaik_ssl.jar

General Settings

Description Example

RDBMS Driver Location

Contains the path to the RDBMS driver.

C://sapdb/programs/runtime/jar/sapdbc.jar

RDBMS Initial Connections

Specifies the number of database connections to be created initially in the connection pool.

1

RDBMS Maximum

Specifies the maximum number of database

10

27

Page 29: Master of Science in Information Technology (MScIT-NEW) – Semester 3

Connections

connections to be kept in the connection pool.

 

After filling the connection fields, you have the following options:

1. Directly connect to the relevant database. Choose Connect to DB.

2. Save the connection properties you have just set:

Choose Save Connection As.

Enter a file name with the extension “properties”, for example user.properties.

Choose Save.

1. Open a previously saved “.properties” file to connect to a particular database. Choose Load Connection Set

28