You are on page 1of 11

[HOMEWORK II] March 9, 2010

Modern Programming tools and Techniques
Homework Title / No. : Course Instructor : Date of Allotment : Student’s Roll No: RTb805A17 IInd BalRaj Kumar Course Code : Tutor (if applicable) : Date of submission : Section No – CAP 310 BalRaj Kumar 21-Feb-10 RTb805

Declaration: I declare that this assignment is my individual work. I have not copied from any other student’s work or from any other source except where due acknowledgment is made explicitly in the text, nor has any part been written for me by another person. Student’s Signature : Joginder singh

Evaluator’s comments: _____________________________________________________________________ Marks obtained : ___________ out of ______________________

Part-I Q:1 Explain the term:
a) Widening and Narrowing operand conversion b) Overflow, Underflow, and Exceptions

Ans (a) Widening and Narrowing operand conversion
A specific conversion from type S to type T allows an expression of type S to be treated at compile time as if it had type T instead. In some cases this will require a corresponding action at run time to check the validity of the conversion or to translate the run-time value of the expression into a form appropriate for the new type T. For example:

[HOMEWORK II] March 9, 2010

A conversion from type int to type long requires run-time sign-extension of a 32-bit integer value to the 64-bit long representation. No information is lost.

A conversion from type double to type long requires a nontrivial translation from a 64-bit floating-point value to the 64-bit integer representation. Depending on the actual run-time value, information may be lost. In every conversion context, only certain specific conversions are permitted. For convenience of description, the specific conversions that are possible in the Java programming language are grouped into several broad categories: • • • • • Identity conversions Widening primitive conversions Narrowing primitive conversions Widening reference conversions Narrowing reference conversions

Widening Primitive Conversion
The following 19 specific conversions on primitive types are called the widening primitive conversions:
• • • • • •

byte to short, int, long, float, or double short to int, long, float, or double char to int, long, float, or double int to long, float, or double long to float or double float to double

Widening primitive conversions do not lose information about the overall magnitude of a numeric value. Indeed, conversions widening from an integral type to another integral type do not lose any information at all; the numeric value is preserved exactly. Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value A widening conversion of a signed integer value to an integral type T simply sign-extends the two's-complement representation of the integer value to fill the wider format. A widening conversion of a char to an integral type T zero-extends the representation of the char value to fill the wider format.

[HOMEWORK II] March 9, 2010 Despite the fact that loss of precision may occur, widening conversions among primitive types never result in a run-time exception

An example of a widening conversion that loses precision:
class Test { public static void main(String[] args) { int b = 1234567890; float approx = b; System.out.println(b - (int)approx); } } which prints: -46 thus indicating that information was lost during the conversion from type int to type float because values of type float are not precise to nine significant digits.

Narrowing Primitive Conversions
The following 22 specific conversions on primitive types are called the narrowing primitive conversions:
• • • • • •

short to byte or char char to byte or short int to byte, short, or char long to byte, short, char, or int float to byte, short, char, int, or long double to byte, short, char, int, long, or float

Narrowing conversions may lose information about the overall magnitude of a numeric value and may also lose precision. The example: class Test { public static void main(String[] args) { float fmin = Float.NEGATIVE_INFINITY; float fmax = Float.POSITIVE_INFINITY;

[HOMEWORK II] March 9, 2010 System.out.println("long: " + (long)fmin + ".." + (long)fmax); System.out.println("int: " + (int)fmin + ".." + (int)fmax); System.out.println("short: " + (short)fmin + ".." + (short)fmax); System.out.println("char: " + (int)(char)fmin + ".." + (int)(char)fmax); System.out.println("byte: " + (byte)fmin + ".." + (byte)fmax); } } produces the output: long: -9223372036854775808..9223372036854775807 int: -2147483648..2147483647 short: 0..-1 char: 0..65535 byte: 0..-1

Ans (b) Overflow, Underflow, and Exceptions Overflow And Underflow
Overflow and underflow is a condition where you cross the limit of prescribed size for a data type. When overflow or underflow condition is reached, either the program will crash or the underlying implementation of the programming language will have its own way of handing things. In Java arithmetic operators don’t report overflow and underflow conditions. They simply swallow it! It is a very dangerous thing to do. If one doesn’t know how Java handles overflow

[HOMEWORK II] March 9, 2010 and underflow then he will not be aware of things happening behind while doing arithmetic operations.

Overflow and Underflow in Java int operators
Arithmetic integer operations are performed in 32-bit precision. When the resultant value of an operation is larger than 32 bits (the maximum size an int variable can hold) then the low 32 bits only taken into consideration and the high order bits are discarded. When the MSB (most significant bit) is 1 then the value is treated as negative.

Overflow and Underflow in Java floating point operators
While using java floating point operators, overflow will result in Infinity and underflow will result 0.0 As a general rule here also Java doesn’t throw an error or exception for overflow and underflow.


Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception. Java exception handling is used to handle error conditions in a program systematically by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Java exceptions are raised with the throw keyword and handled within a catch block. A Program Showing How the JVM throws an Exception at runtime public class DivideException { public static void main(String[] args) { division(100,4); division(100,0); System.out.println("Exit main()."); } public static void division(int totalSum, int totalNumber) { System.out.println("Computing Division.");

[HOMEWORK II] March 9, 2010 int average = totalSum/totalNumber; System.out.println("Average : "+ average); } } Q:2 Write a code segment that circularly shifts the values of int variable a, b, c and d, for example if the variable values are initially 10, 20, 30 and 40 respectively, then the final values are 40, 10, 20 and 30 respectively. It may be convenient to introduce a temporary variable to accomplish this task. Answer: class circularsfts { public static void main(String args[]) { int a[]={10,20,30,40}; int temp,i,c; temp=0; c=a[3]; for(i=3;i>0;i--) { a[i]=temp; a[i]=a[i-1]; } a[0]=c;System.out.println("the circular sifted aray is "); for(i=0;i<=3;i++) { System.out.println("\t"+a[i]); } } }

[HOMEWORK II] March 9, 2010 Q:3 How many parameters does a default constructor require? Why? Answer If we don't define a constructor for a class, a default parameter less constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super ()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for Booleans ). If you define any constructor for your class, no default constructor is automatically created. Thus default constructor requires no parameter.

Part B
Q:4 Write an array definition for an array coefficient that is initialized with the following values 1.4, 4.30, 5.12, 6.9, 6.21, 7.31, 11.4, 11.28 and 11.29.

Answer : import java.util.*; class array_float { public static void main(String args[]) { float arr1[]={1.4, 4.30, 5.12, 6.9, 6.21, 7.31, 11.4, 11.28 ,11.29}; for(i=0;i<=9;i++) { System.out.println("\t"+arr1[i]); } } }

Q:5 Write the code segment that does the following (a) Define an array score with 40 elements. The element type of the array is double.

[HOMEWORK II] March 9, 2010 (b) Sets the value of each element in score so that it matches its subscript value. (c) Displays the values of the last five elements of scores. (d) Is the value 3.1415 a legal subscript value for score? Explain. (e) Is the value 3.1415 a legal element value for score? Explain. Answer : Array score with 40 elements import java.util.*; class Ele_score { public static void main(String arg[]) { Scanner input=new Scanner(; double score[ ]=new double[40]; int n; System.out.print("array score:"); for(i=0;i<n;i++) { System.out.print("Enter the value of each element:"); b.) sets values of score. Score[i]=input.nextDouble(); } for(i=0;i<n;i++) { System.out.println ("a["+i+"]"+"="+score[i]); } c.) Last five elements of score. System.out.println (" last five values are:"); for (i=n-1;i>n-6;i--) { System.out.println ("The value of last five elements is:"+score[i]); } } } d.) The value 3.1415 is not legal subscript value for score because a subscript values must not be in floating number. It should be in integer’s number. Subscript values are used for counting the elements of an array. So it can not be floating values. e.) The value 3.1415 is a legal element value for score because it is define that the value in floating point or double.

[HOMEWORK II] March 9, 2010

Q:6 Program to input a set of names into an array and print each name with the no. of characters in it and print each name by replacing all occurrences of the alphabet ‘a’ and ‘A’ with the symbol ‘*’. Use at least two user-defined classes.

Answer : import java.util.*; class print _element { Void find(char a[ ][ ]) { int i,j; for(i=0;i<10;i++) { for(j=0;j<30;j++) { if(a[i][j]==’a’||a[i][j]==’A’) { a[i][j]=’*’; } } } } void show(char a[ ][ ]) { int i,j; for(i=0;i<10;i++) { for(j=0;j<30;j++) {

[HOMEWORK II] March 9, 2010 System.out.print ("\t"+a[i][j]); } } }


class jogin { public static void main(String args[]) { finda fa=new find(); Scanner input=new Scanner (); char name[ ][ ]=new int [10][30]; int ii.jj; for(ii=0;ii<10;ii++) { for(jj=0;jj<30;jj++) { name[ii][jj]=input.nextChar(); } } fa.find(name);; } }

[HOMEWORK II] March 9, 2010