Java Questions 41 - 50  «Prev  Next»

Data Types and Casting (Interview Questions)

  1. Are char and short smaller datatypes than int (Meaning their capacity to hold data is less than that of int)?
    Answer:
    Yes.
  2. What is the result of an expression involving anything int-sized or smaller?
    Answer:
    The result of an expression involving anything int-sized or smaller is always an int.
  3. What is the correct way to cast two byte data types that you are adding?
    Suppose you are given
    byte a= 3; 
    byte b= 5; 
    byte c= a + b; 
    

    Answer:
    The correct way to cast is by using the datatype byte
    c = (byte)(a + b);
    
  4. The following is an example of an explicit cast.
    Answer:
    float a = 100.001f;
    int b = (int) a; //
    
  5. Can an integer value fit in a 64-bit double data type?
    Answer:
    An integer value can fit in a 64-bit double as shown by the following code.
    double d1 = 64.0;
    int i1 = 13;
    d1 = i1;
    
  6. How do you initialize a double with a long value?
    Answer
    : The long value must be cast to double.
    Double d= (double) 100L;
  7. Can you assign an int data type to a float without casting.
    Answer:
    Yes.
    float f1 = 34.0f;
    int j = 13;
    f1 = j;
    
  8. What must be done, in order to assign a floating-point literal to a float variable, you must either 1) cast the value or 2) append a f to the end of the literal.
    Answer:
    float h = 498.47F;
    
  9. Show two examples of the byte datatype where the compilation succeeds and the compilation fails?
    Answer:
    byte a= 127; //Compilation succeeds
    byte b = 128;	//Compilation fails
    
  10. What happens when you narrow a primitive in Java?
    Answer:
    When you narrow a primitive, Java simply truncates the high-order bits that will not fit. In other words, it loses all the bits to the left of the bits you are narrowing to.