USN
1 / P / E
/ PESIT Bangalore South Campus
Hosur road, 1km before Electronic City, Bengaluru -100
Department of Computer Science And Engineering

INTERNAL ASSESSMENT TEST – 1

Date : 29/08/17 Max Marks : 50

Subject & Code : JAVA and J2EE (10CS753) Section : A,B,C

Name of faculty : Ms. Neeta, Ms. Lakshmi NPR Time : 8:00 am to 10:30am

1. / a
b / List and Discuss the Java Buzzwords
Ans:
1.  Simple
a.  No pointers
b.  Automatic Garbage collection
c.  Rich Pre-defined class library
2.  Object Oriented
a.  Focus on the data (Objects) and methods manipulating the data
b.  All functions are associated with objects
c.  Almost all data types are objects (files, strings, etc.)
3.  Interpreted
a.  Java complier generates byte-codes, not native machine code
b.  The complied byte-codes are platform independent
c.  Java byte-codes are translated on the fly to machine readable instructions in runtime (Java Virtual Machine)
4.  Portable
a.  Same application runs on all platforms
b.  The sizes of the primitive data types are always the same
c.  The libraries define portable interfaces
5.  Reliable
a.  Extensive compile time and runtime error checking
b.  Automatic garbage collection tracks object usage over time
6.  Secure
a.  Usage in networked environments requires more security
b.  Memory allocation model is a major defense
c.  Access restrictions are forced (private, public)
7.  Multithreaded
a.  Multiple concurrent threads of executions can run simultaneously
b.  Utilizes a sophisticated set of synchronization primitives to achieve this
8.  Dynamic
a.  Java is designed to adapt to evolving environment
b.  Libraries can freely add new methods and instance variables without any effect on their clients
What is Java Bytecode? Explain
Ans:
·  The key that allows Java to solve both the security and the portability problems.
·  the output of a Java compiler is not executable code
·  Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system,
·  which is called the Java Virtual Machine (JVM)
·  JVM was designed as an interpreter for bytecode
·  Translating a Java program into bytecode makes it much easier to run a program in a wide variety of environments because only the JVM needs to be implemented for each platform.
/ 5
5
2 / A
B / Explain how arrays are defined and used in Java with suitable examples.
Declaration
datatype var-name[ ] = new datatype[size];
ex:
int a[ ] = new int[10];
Initialize
Method 1
a[0]=12;
a[1]=23;
Method 2
int a[] = {12,13,14,23,34};
Displaying an array:
Individual elements
System.out.println(a[0]);
Whole array
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
Example:
// Demonstrate a one-dimensional array.
class arrayloop {
public static void main(String args[]) {
int num[]={12,13,14,15,16};
System.out.println("The array values are:");
for(int i=0;i<num.length;i++)
{
System.out.println(num[i]);
}
}
}
Explain the syntax of for-each loop. Write a Java program to search a key element by using for-each loop.
  The For-Each Version of the for Loop
for(type itr-var : collection) {
statement-block }
Example:
// Use a for-each style for loop.
class ForEach {
public static void main(String args[])
{
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int key;
Scanner in = new Scanner(System.in);
System.out.println("enter the element to be found:");
key=in.nextInt();
// use for-each style for to display and sum the values
for(int x : nums) {
if(x==key){
System.out.println("Element Found!");
System.out.println("Value is: " + x);
}
}
}
} / 4
6
3 / A
B / Define type casting. Explain with an example
  In Java, type casting is classified into two types,
  Widening Casting(Implicit)

  Narrowing Casting(Explicitly done)

  Conditions for automatic type conversions
  The two types are compatible
  The destination type is larger than the source type
  Casting incompatible types
(target-type) value
int a; int i=257;
byte b; double j=323.142;
// … i= (int) j;
b=(byte)a;
Widening (implicit type casting)
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Narrowing (Explicit type casting):
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
What are access specifiers? List and explain the access specifiers in Java
Ans:
Encapsulation provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. For example, allowing access to data only through a welldefined set of methods, you can prevent the misuse of that data.
Java’s access specifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved.
/* This program demonstrates the difference between
public and private.
*/
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " +
ob.b + " " + ob.getc());
}
}
/ 5
5
4. / A
b / Write a program to explain the Inheritance properties of Java
Ans: To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.
Note: Variables decalred private in the super class cannot be inherited
// A simple example of inheritance.
// 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();
}
}
Explain with examples, constructors in Java
Ans: A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes
Types of constructors:
Parameterized
Non parameterized / default
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// This is the parameterized constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box(10, 20, 15);double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
} / 7
5
5 / a / What is overloading and overriding? Explain
Ans:
Method Overloading Rules:
·  Method signatures must be different
o  method signature is made of
§  number of arguments,
§  type of arguments
§  order of arguments, if they are of different types
·  Return type of method is not part of method signature, so just changing the return type will not overload a method in Java
·  Java will employ automatic type conversion only if no exact match is found
// Automatic type conversions apply to overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a,int b) {
System.out.println("Inside test(int) a: "+a+" b:"+b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("Inside test(double) a: "+a);
return a*2;
}
}
class Overload1 {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double i = 88;
ob.test();
ob.test(10);
i = (int) ob.test(i); // this will invoke test(double)
System.out.println(i/2+"*2 is :"+i);
ob.test(123.2); // this will invoke test(double)
}
}
Method Overriding:
  The argument list should be exactly the same as that of the overridden method
  The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass
  If a method cannot be inherited (accessible), then it cannot be overridden
  Constructors cannot be overridden
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
} / 10
6 / a
b / Write a note on the following keywords:
i)  Super
ii)  Thesuperkeyword is similar tothiskeyword
iii)  Keyword super is used in two ways:
a.  To invoke the superclass’ constructor
b.  It is used todifferentiate the membersof superclass from the members of subclass, if they have same names
1.  super must always be the FIRST statement executed inside a subclass constructor
To invoke a Superclass Constructor:
class BoxWeight extends Box {
double weight; // weight of box
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}
To Access hidden members:
class A {
int i;
}
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
ii)  Final
1)  Using Final with variables
// Using Final Variables
class A {
final int i=10;
int j;
A(int a,int b) {
i=a;
j = b;
}
// display i and j
void show() { // not accessible in a subclass
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a,int b, int c) {
super(a,b);
k = c;
}
void show() {
super.show();
System.out.println("k: " + k);
}
}
class FinalVal {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show();
}
}
2)  Using Final with Inheritance
a.  To prevent overriding
To prevent overriding
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
b.  To prevent Inheritance
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
} / 5*2
7. / What is an Exception? Given an example for nested try statements
Ans:
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. When an exceptional condition arises, an object representing
that exception is created and thrown in the method that caused the error. That method may
choose to handle the exception itself, or pass it on. Either way, at some point, the exception
is caught and processed.
Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method.
Java exception handling is managed via five keywords:
  try
  catch
  throw
  throws
  finally
The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is
unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception
// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
} / 10
8. / Write a Java program to perform addition of two complex numbers by using the method add() by passing object as parameter and display the result using the method display(). Initialize the real and imaginary values of the complex number using parameterized constructors
class complex{
double real;
double imaginary;
complex(int x,int y)
{
real=x;
imaginary=y;
}
void add(complex obj1)
{
real=obj1.real+real;
imaginary=obj1.imaginary+imaginary;
}
void display()
{
System.out.println("The sum of two complex numbers
are:"+real+"+i"+imaginary);
}
}
class examcode{
public static void main(String args[])
{
complex num1=new complex(1,2);
complex num2=new complex(3,4);
num1.add(num2);
num1.display();
}
} / 10

B.E/MBA/MCA/M.Tech <Semester Number>