Inretview Questions

Wednesday, April 1, 2009

1.What is the difference between apache webserver, java webserver and tomcat server?

Apache is an HTTP server written in C that can be compiled and run on many platforms. Java WebServer is an HTTP server from Sun written in Java that also supports Servlets and JSP.
Tomcat is an open-source HTTP server from the Apache Foundation, written in Java, that supports Servlets and JSP. It can also be used as a "plug-in" to native-code HTTP servers, such as Apache Web Server and IIS, to provide support for Servlets (while still serving normal HTTP requests from the primary, native-code web server).
Tomcat behind Apache with a connector .apache web server is a webserver where as tomcat is a servlet container.
Apache is what your browser connects to, tomcat is what apache connects
to to ask for servlets to be processed. However, tomcat now includes a
webserver so you can cut out the middle man. You might not want to do
this on a large production environment.
Apache is a general-purpose http server, which supports a number of advanced options that Tomcat doesn't. Although Tomcat can be used as a general purpose http server, you can also set up Apache and Tomcat to work together with Apache serving static content and forwarding the requests for dynamic content to Tomcat. This is generally prefered when using tomcat because the overhead from serving static content directly from Apache is much lower than having Tomcat handle all of the requests

2.What is the difference between Web Site and Web Browser?


Web site is the client base system( or said to collection of web pages contains information interact with user or client) use to interact over the network
Web Browser is the applicaction or tool use to run web pages or web site.

3.Difference between web server and application server?


Webserver:
A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser.
Application Server:
As for the application server, according to our definition, an application server exposes business logic to client applications through various protocols, possibly including HTTP. While a Web server mainly deals with sending HTML for display in a Web browser, an application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on an object

Exception Handling

Exception handling
Exception can be generated by Java-runtime system or they can be manually generated by code.

Error-Handling becomes a necessary while developing an application to account for exceptional situations that may occur during the program execution, such as
Run out of memory
Resource allocation Error
Inability to find a file
Problems in Network connectivity.
If the Resource file is not present in the disk, you can use the Exception handling mechanisim to handle such abrupt termination of program.

Exception class : is used for the exceptional conditions that are trapped by the program.
An exception is an abnormal condition or error that occur during the execution of the program.
Error : the error class defines the conditions that do not occur under normal conditions.
Eg: Run out of memory, Stack overflow error.

Java.lang.Object
+….Java.Lang.Throwable Throwable
+…. Java.lang.Error
| +…. A whole bunch of errors
| Exception Error
+….Java.Lang.Exception (Unchecked, Checked)
+….Java.Lang.RuntimeException
| +…. Various Unchecked Exception
|
+…. Various checked Exceptions.

Two types of exceptions:
1. Checked Exceptions : must be declare in the method declaration or caught in a catch block.
Checked exception must be handled at Compile Time. Environmental error that cannot necessarly be detected by Testing, Eg: disk full, brocken Socket, Database unavailable etc.

2. Un-checked Exceptions: Run-time Exceptions and Error, does’t have to be declare.(but can be caught).
Run-time Exceptions : programming errors that should be detectd in Testing ,
Arithmetic, Null pointer, ArrayIndexOutofBounds, ArrayStore, FilenotFound, NumberFormate, IO, OutofMemory.
Errors: Virtual mechine error – class not found , out of memory, no such method , illegal access to private field , etc.

Java Exception handling can be managed by five keywords:
Try : The try block governs the statements that are enclosed within it and defines the scope of exception handler associated with it. Try block follows catch or finally or both.

Catch: This is a default exception handler. since the exception class is the base class for all the exception class, this handler id capable of catching any type of exception.
The catch statement takes an Object of exception class as a parameter, if an exception is thrown the statement in the catch block is executed. The catch block is restricted to the statements in the proceeding try block only.
Try {
// statements that may cause exception
}
catch(Exception obj)
{

}
Finally : when an exception is raised, the statement in the try block is ignored, some times it is necessary to process certain statements irrespective of wheather an exception is raised or not, the finally block is used for this purpose.
Throw : The throw class is used to call exception explicitly. You may want to throw an exception when the user enters a wrong login ID and pass word, you can use throw statement to do so.
The throw statement takes an single argument, which is an Object of exception class.

Throw
If the Object does not belong to a valid exception class the compiler gives error.

Throws :The throws statement species the list of exception that has thrown by a method.
If a method is capable of raising an exception that is does not handle, it must specify the exception has to be handle by the calling method, this is done by using the throw statement.
[] [] []

Eg: public void accept password( ) throws illegalException
{
System.out.println(“Intruder”);
Throw new illegalAccesException;
}

Basic Concepts of CoreJava

Tuesday, March 31, 2009

JAVA

Abstraction: Showing the essential and hiding the non-Essential is known as Abstraction.

Encapsulation: The Wrapping up of data and functions into a single unit is known as Encapsulation.
Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessed via the interface of the object.

Inheritance: is the Process by which the Obj of one class acquires the properties of Obj’s another Class.
A reference variable of a Super Class can be assign to any Sub class derived from the Super class.
Inheritance is the method of creating the new class based on already existing class , the new class derived is called Sub class which has all the features of existing class and its own, i.e sub class.
Adv: Reusability of code , accessibility of variables and methods of the Base class by the Derived class.

Polymorphism: The ability to take more that one form, it supports Method Overloading & Method Overriding.

Method overloading: When a method in a class having the same method name with different arguments (diff Parameters or Signatures) is said to be Method Overloading. This is Compile time Polymorphism.
o Using one identifier to refer to multiple items in the same scope.

Method Overriding: When a method in a Class having same method name with same arguments is said to be Method overriding. This is Run time Polymorphism.
o Providing a different implementation of a method in a subclass of the class that originally defined the method.
1. In Over loading there is a relationship between the methods available in the same class ,where as in Over riding there is relationship between the Super class method and Sub class method.
2. Overloading does not block the Inheritance from the Super class , Where as in Overriding blocks Inheritance from the Super Class.
3. In Overloading separate methods share the same name, where as in Overriding Sub class method replaces the Super Class.
4. Overloading must have different method Signatures , Where as Overriding methods must have same Signatures.

Dynamic dispatch: is a mechanism by which a call to Overridden function is resolved at runtime rather than at Compile time , and this is how Java implements Run time Polymorphism.

Dynamic Binding: Means the code associated with the given procedure call is not known until the time of call the call at run time. (it is associated with Inheritance & Polymorphism).

Bite code: Is a optimized set of instructions designed to be executed by Java-run time system, which is called the Java Virtual machine (JVM), i.e. in its standard form, the JVM is an Interpreter for byte code.
JIT- is a compiler for Byte code, The JIT-Complier is part of the JVM, it complies byte code into executable code in real time, piece-by-piece on demand basis.

Final classes : String, Integer , Color, Math
Abstract class : Generic servlet, Number class
o variable:An item of data named by an identifier.Each variable has a type,such as int or Object,andascope
o class variable :A data item associated with a particular class as a whole--not with particular instances of the class. Class variables are defined in class definitions. Also called a static field. See also instance variable.
o instance variable :Any item of data that is associated with a particular object. Each instance of a class has its own copy of the instance variables defined in the class. Also called a field. See also class variable.
o local variable :A data item known within a block, but inaccessible to code outside the block. For example, any variable defined within a method is a local variable and can't be used outside the method.
o class method :A method that is invoked without reference to a particular object. Class methods affect the class as a whole, not a particular instance of the class. Also called a static method. also instance method.
o instance method :Any method that is invoked with respect to an instance of a class. Also called simply a method. See also class method.


Interface: Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy. Using Interface, you can specify what a class must do but not how it does.
A class can implement more than one Interface.
An Interface can extend one or more interfaces, by using the keyword extends.
All the data members in the interface are public, static and Final by default.
An Interface method can have only Public, default and Abstract modifiers.
An Interface is loaded in memory only when it is needed for the first time.
A Class, which implements an Interface, needs to provide the implementation of all the methods in that Interface.
If the Implementation for all the methods declared in the Interface are not provided , the class itself has to declare abstract, other wise the Class will not compile.
If a class Implements two interface and both the Intfs have identical method declaration, it is totally valid.
If a class implements tow interfaces both have identical method name and argument list, but different return types, the code will not compile.
An Interface can’t be instantiated. Intf Are designed to support dynamic method resolution at run time.
An interface can not be native, static, synchronize, final, protected or private.
The Interface fields can’t be Private or Protected.
A Transient variables and Volatile variables can not be members of Interface.
The extends keyword should not used after the Implements keyword, the Extends must always come before the Implements keyword.
A top level Interface can not be declared as static or final.
If an Interface species an exception list for a method, then the class implementing the interface need not declare the method with the exception list.
If an Interface can’t specify an exception list for a method, the class can’t throw an exception.
If an Interface does not specify the exception list for a method, he class can not throw any exception list.
The general form of Interface is
Access interface name {
return-type method-name1(parameter-list);
type final-varname1=value;
}
-----------------------
Marker Interfaces : Serializable, Clonable, Remote, EventListener,

Java.lang is the Package of all classes and is automatically imported into all Java Program
Interfaces: Clonable , Comparable, Runnable
Abstract Class: Abstract classes can be used to implement the inheritance relationship between the classes that belongs same hierarchy.
Classes and methods can be declared as abstract.
Abstract class can extend only one Class.
If a Class is declared as abstract , no instance of that class can be created.
If a method is declared as abstract, the sub class gives the implementation of that class.
Even if a single method is declared as abstract in a Class , the class itself can be declared as abstract.
Abstract class have at least one abstract method and others may be concrete.
In abstract Class the keyword abstract must be used for method.
Abstract classes have sub classes.
Combination of modifiers Final and Abstract is illegal in java.

Abstract Class means - Which has more than one abstract method which doesn’t have method body but at least one of its methods need to be implemented in derived Class.

The general form of abstract class is :
abstract type name (parameter list);

The Number class in the java.lang package represents the abstract concept of numbers. It makes sense to model numbers in a program, but it doesn't make sense to create a generic number object.

Difference Between Interfaces And Abstract class ?
o All the methods declared in the Interface are Abstract, where as abstract class must have atleast one abstract method and others may be concrete.
o In abstract class keyword abstract must be used for method, where as in Interface we need not use the keyword for methods.
o Abstract class must have Sub class, where as Interface can’t have sub classes.
o An abstract class can extend only one class, where as an Interface can extend more than one.

What are access specifiers and access modifiers ?

Accesss specifiers Access modifiers
Public Public
Protected Abstract
Private Final
Static
Volatile Constant
Synchronized
Transient
Native

• Public : The Variables and methods can be access any where and any package.
• Protected : The Variables and methods can be access same Class, same Package & sub class.
• Private : The variable and methods can be access in same class only.

Same class - Public, Protected, and Private
Same-package & subclass - Public, Protected
Same Package & non-sub classes - Public, Protected
Different package & Sub classes - Public, Protected
Different package & non- sub classes - Public

Identifiers : are the Variables that are declared under particular Datatype.

Literals: are the values assigned to the Identifiers.

Static : access modifier. Signa: Variable-Static int b; Method- static void meth(int x)
When a member is declared as Static, it can be accessed before any objects of its class are created and without reference to any object. Eg : main(),it must call before any object exit.
Static can be applied to Inner classes, Variables and Methods.
Local variables can’t be declared as static.
A static method can access only static Variables. and they can’t refer to this or super in any way.
Static methods can’t be abstract.
A static method may be called without creating any instance of the class.
Only one instance of static variable will exit any amount of class instances.

Final : access modifier
All the Variables, methods and classes can be declared as Final.
Classes declared as final class can’t be sub classed.
Method ‘s declared as final can’t be over ridden.
If a Variable is declared as final, the value contained in the Variable can’t be changed.
Static final variable must be assigned in to a value in static initialized block.

Transient : access modifier
Transient can be applied only to class level variables.
Local variables can’t be declared as transient.
During serialization, Object’s transient variables are not serialized.
Transient variables may not be final or static. But the complies allows the declaration and no compile time error is generated.

Volatile: access modifier
Volatile applies to only variables.
Volatile can applied to static variables.
Volatile can not be applied to final variables.
Transient and volatile can not come together.
Volatile is used in multi-processor environments.

Native : access modifier
Native applies to only to methods.
Native can be applied to static methods also.
Native methods can not be abstract.
Native methods can throw exceptions.
Native method is like an abstract method. The implementation of the abstract class and native method exist some where else, other than the class in which the method is declared.

Synchronized : access modifier
Synchronized keyword can be applied to methods or parts of the methods only.
Synchronize keyword is used to control the access to critical code in multi-threaded programming.


Declaration of access specifier and access modifiers :

Class - Public, Abstract, Final
Inner Class - Public, Protected, Private, Final, Static,
Anonymous - Public, Protected, Private, Static
Variable - Public, Protected, Private, Final, Static, Transient, Volatile, Native
Method - Public, Protected, Private, Final, Abstract, Static, Native, Synchronized
Constructor - Public, Protected, Private
Free-floating code block - Static, Synchronized

Package : A Package is a collection of Classes Interfaces that provides a high-level layer of access protection and name space management.

Finalize( ) method:
All the objects have Finalize() method, this method is inherited from the Object class.
Finalize() is used to release the system resources other than memory(such as file handles& network connec’s.
Finalize( ) is used just before an object is destroyed and can be called prior to garbage collection.
Finalize() is called only once for an Object. If any exception is thrown in the finalize() the object is still eligible for garbage collection.
Finalize() can be called explicitly. And can be overloaded, but only original method will be called by Ga-collect.
Finalize( ) may only be invoked once by the Garbage Collector when the Object is unreachable.
The signature finalize( ) : protected void finalize() throws Throwable { }

Constructor( ) :
A constructor method is special kind of method that determines how an object is initialized when created.
Constructor has the same name as class name.
Constructor does not have return type.
Constructor cannot be over ridden and can be over loaded.
Default constructor is automatically generated by compiler if class does not have once.
If explicit constructor is there in the class the default constructor is not generated.
If a sub class has a default constructor and super class has explicit constructor the code will not compile.

Object : Object is a Super class for all the classes. The methods in Object class as follows.
Object clone( ) final void notify( ) Int hashCode( )
Boolean equals( ) final void notify( )
Void finalize( ) String toString( )
Final Class getClass( ) final void wait( )
Class : The Class class is used to represent the classes and interfaces that are loaded by the JAVA Program.

Character : A class whose instances can hold a single character value. This class also defines handy methods that can manipulate or inspect single-character data.
constructors and methods provided by the Character class:
Character(char) : The Character class's only constructor, which creates a Character object containing the value provided by the argument. Once a Character object has been created, the value it contains cannot be changed.
compareTo(Character) :An instance method that compares the values held by two character objects.
equals(Object) : An instance method that compares the value held by the current object with the value held by another.
toString() : An instance method that converts the object to a string.
charValue() :An instance method that returns the value held by the character object as a primitive char value.
isUpperCase(char) : A class method that determines whether a primitive char value is uppercase.

String: String is Immutable and String Is a final class. The String class provides for strings whose value will not change.
One accessor method that you can use with both strings and string buffers is the length() method, which returns the number of characters contained in the string or the string buffer. The methods in String Class:-
toString( ) equals( ) indexOff( ) LowerCase( )
charAt( ) compareTo( ) lastIndexOff( ) UpperCase( )
getChars( ) subString( ) trim( )
getBytes( ) concat( ) valueOf( )
toCharArray( ) replace( )
ValueOf( ) : converts data from its internal formate into human readable formate.
String Buffer : Is Mutable , The StringBuffer class provides for strings that will be modified; you use string buffers when you know that the value of the character data will change.
In addition to length, the StringBuffer class has a method called capacity, which returns the amount of space allocated for the string buffer rather than the amount of space used.
The methods in StringBuffer Class:-
length( ) append( ) replace( ) charAt( ) and setCharAt( )
capacity( ) insert( ) substring( ) getChars( )
ensureCapacity( ) reverse( )
setLength( ) delete( )

Wraper Classes : are the classes that allow primitive types to be accessed as Objects.
These classes are similar to primitive data types but starting with capital letter.
Number Byte Boolean
Double Short Character
Float Integer
Long
primitive Datatypes in Java :
According to Java in a Nutshell, 5th ed boolean, byte, char, short, long float, double, int.

Float class : The Float and Double provides the methods isInfinite( ) and isNaN( ).
isInfinite( ) : returns true if the value being tested is infinetly large or small.
isNaN( ) : returns true if the value being tested is not a number.

Character class : defines forDigit( ) digit( ) .
ForDigit( ) : returns the digit character associated with the value of num.
digit( ) : returns the integer value associated with the specified character (which is presumably) according to the specified radix.

String Tokenizer : provide parsing process in which it identifies the delimiters provided by the user, by default delimiters are spaces, tab, new line etc., and separates them from the tokens. Tokens are those which are separated by delimiters.

Observable Class: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update( ) method of each of its observers to notify the observers that it has changed state.
Observer interface : is implemented by objects that observe Observable objects.

Instanceof( ) :is used to check to see if an object can be cast into a specified type with out throwing a cast class exception.

IsInstanceof( ) : determines if the specified Object is assignment-compatible with the object represented by this class. This method is dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

Garbage Collection : When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection.
System.gc() method may be used to call it explicitly and does not force the garbage collection but only suggests that the JVM may make an effort to do the Garbage Collection.

• this() : can be used to invoke a constructor of the same class.
• super() :can be used to invoke a super class constructor.

Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private.

Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
What is reflection API? How are they implemented
Reflection package is used mainlyfor the purpose of getting the class name. by useing the getName method we can get name of the class for particular application. Reflection is a feature of the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program.

What is heap in Java
JAVA is fully Object oriented language. It has two phases first one is Compilation phase and second one is interpratation phase. The Compilation phase convert the java file to class file (byte code is only readable format of JVM) than Intepratation phase interorate the class file line by line and give the proper result.

main( ) : is the method where Java application Begins.
String args[ ] : receives any command line argument during runtime.
System : is a predefined Class that provides access to the System.
Out : is output stream connected to console.
Println :displays the output.

Downcasting : is the casting from a general to a more specific type, i.e casting down the hierarchy. Doing a cast from a base class to more specific Class, the cast does;t convert the Object, just asserts it actually is a more specific extended Object.

Upcasting : byte can take Integer values.

JVMJDKJRE

Topics covered

JVM
JDK
JRE
Class Files


What is JVM?
It’s the short form of Java Virtual Machine. It is a program that interprets the bytecode of class files in to the native( machine ) code. The Java virtual machine knows nothing of the Java programming language, only of a particular binary format, the class file format.

Why JVM is called a virtual machine and not by some other name.
JVM is called Java Virtual Machine because it doesn’t exist physically. It is a virtual thing which performs some action. That’s why it is named virtual machine.

Is JVM platform-dependant.
Yes JVM is platform dependent. Only Java is platform independent

Why can't we have the same JVM across all the OS’s.
JVM acts as a interface between your program and the operating system. It would be impossible to have one JVM for all operating systems because the JVM relies on operating system calls to provide many of the facilities which Java programs use. The JVM exposes a consistent interface to Java programs but it has to adapt those services to the actually operating system underneath. Moreover the CPU instruction sets vary wildly from OS to OS.

Is both JVM and 'Java' (JDK Tool) same ?
No, they are different things. The JDK (SDK) is the place to CODE applications and compile them to byte codes. The JVM can be built into a Computer, Browser (or computer chip in your car, or in a thermostat, or in your cell phone or whatever) and takes already compiled code(byte code) and executes it.
We use JRE (Java Runtime Environment) to execute compiled code outside of an browser(JVM), at the operating system.

In which language java compiler and JVM was written?
They can be written in any decent language like C, C++ or Java.
The point is that a JVM can be written by anyone. Sun maintains the specifications (rules that must be followed) and other companies follow the specifications when creating a JVM for their product. I would guess that the JVM in Internet Explorer, since it is a Microsoft Product, is written in Visual Basic.


What’s the difference between loading the class and instantiating the class.

Class c = Class.forName("com.raverun.foo");

Pulling in byte codes from storage (i.e. network, local hard drive) into the current JVM. Loading classes means just only Loading them. Usually this task is carried out by default Class Loader or you can define your own class loader to load it.

Instantiating a class means creating an Object in the Heap.

MyClass class = new MyClass();

Note: When a class is loaded, it loads all the static data too.

What is JDK. Why we need it?
To write a java program with java syntax you need to have a Java Development Kit (JDK) installed in your computer. When you install the JDK, you get the compiler which is used to compile the java program(.java) into a class file(.class).

When you install the JDK, you also get Java Runtime environment(JRE) which is required to actually run the program.

What is a class file? What is it comprised of?
You get a class file when you compile a java code. It contains Java virtual machine instructions (or bytecodes) and a symbol table, as well as other ancillary information.

What is JRE?
The JRE (Java Runtime Environment) is the equivalent of a JVM but for running applications outside of a browser (like from the DOS prompt). When you run an applet or servlet it is running in a built-in JVM in the browser.

JVM is a part of JREJDK = Java API + Java Compiler + JRE

JRE = Entire environment (including the JVM) necessary for running Java applications (this includes classes, native code, etc). &JVM = CLASS LOADER + BYTE CODE CHECKER + INTERPRETER + SECURITY MANAGER + GARBAGE COLLECTOR In simple words JRE provides the environment to run Java applications and implicitly JVM is also a part of it.

JAVAWEBSITES

www.javablackbelt.com
www.jchq.net
www.jmock.org
www.javaranch.com/mock.jsp
www.javacertificate.net
www.easymock.org
www.javacertificationexams.com/scjp-mock-exams.php
www.geocities.com/wahjava/mocklinks.html
http://java.about.com/cs/javacertification/tp/topscjpexams.htm
www.examulator.com/home/tigertamer.htm
www.javaprepare.com/links.html

Chapter 2: Operator and assignments

Chapter 2:
Operator and assignments
2.1) Which statements about the output of the following program are true? [1]
public class Logic {
public static void main(String args[]) {
int i = 0;
int j = 0;

boolean t = true;
boolean r;

r = (t && 0<(i+=1));
r = (t && 0<(i+=2));
r = (t && 0<(j+=1));
r = (t 0<(j+=2));

System.out.println( i + “ ” + j );
}
}
(a) The first digit printed is 1.
(b) The first digit printed is 2.
(c) The first digit printed is 3.
(d) The second digit printed is 1.
(e) The second digit printed is 2.
(f) The second digit printed is 3.

2.2) Which statements about the output of the following program are true? [6]
public static void main(String args[])
{
int i =0;
i = i++;
System.out.println(i);
}
(a) 0 is printed.
(b) 1 is printed.

2.3) Which statements about the output of the following program are true? [1]
public class EqualTest {
public static void main(String args[]) {
String s1 = “YES”;
String s2 = “YES”;
if ( s1 == s2 ) System.out.println(“equal”);
String s3 = new String(“YES”);
String s4 = new String(“YES”);
if ( s3 == s4 ) System.out.println(“s3 eq s4”);
}
}
(a) “equal” is printed, “s3 eq s4” is printed.
(b) “equal” is printed only.
(c) “s3 eq s4” is printed only.
(d) Nothing is printed.

2.4) What happens when you try to compile and run the following code?
public class EqualsTest {
public static void main(String args[]) {
char A = ‘\u0005’;
if ( A == 0x0005L )
System.out.println(“Equal”);
else
System.out.println(“Not Equal”);
}
}
(a) The compiler reports “Invalid character in input” in line 3
(b) The program compiles and prints “Not equal”.
(c) The program compiles and prints “Equal”.

2.5) What will happen when you attempt to compile and run the following code? [7]
public class As{
int i = 10;
int j;
char z= 1;
boolean b;

public static void main(String argv[]){
As a = new As();
a.amethod();
}

public void amethod(){
System.out.println(j);
System.out.println(b);
}
}
(a) Compilation succeeds and at run time an output of 0 and false.
(b) Compilation succeeds and at run time an output of 0 and true.
(c) Compile time error b is not initialised.
(d) Compile time error z must be assigned a char value.

2.6) Given the following code what will be the output? [7]
class ValHold {
public int i = 10;
}

public class ObParm {
public static void main(String argv[]) {
ObParm o = new ObParm();
o.amethod();
}

public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i=30;
another(v,i);
System.out.println(v.i);
} //End of amethod

public void another(ValHold v, int i){
i = 0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.println(v.i+ " "+i);
}//End of another
}
(a) 10,0,30
(b) 20,0,30
(c) 20,99,30
(d) 10,0,20

2.7) Here are three proposed alternatives to be used in a method to return false if the object reference x has the null value. Which statement will work? [3]
(a) if ( x == null ) return false;
(b) if ( x.equals(null) ) return false;
(c) if ( x instanceof null ) return false;

2.8) .What will be the result of compiling and running the given program? [8]
Select one correct answer.
1 class Q1
2 {
3 public static void main(String arg[])
4 {
5 int a[]={2,2};
6 int b=1;
7 a[b]=b=0;
8 System.out.println(a[0]);
9 System.out.println(a[1]);
10 }
11 }

(a) Compile time error at the line no. 5.
(b) Run time error at the line no. 5.
(c) Program compiles correctly and print 2,0 when executed.
(d) Program compiles correctly and print 0,2 when executed.

2.9) What will be the result of compiling and running the given program? [8]
Select one correct answer.

1 public class Q4
2 {
3 public static void main(String[] args)
4 {
5 boolean t1 = true, t2 = false, t3 = t1;
6 boolean t = false;
7 t &&= (t1 ( t2 && t3));
8 System.out.println(t);
9 }
10 }
(a) Program compiles correctly and print true when executed.
(b) Program compiles correctly and print false when executed.
(c) Compile time error.
(d) Run time error.

2.10) What will be the result of compiling and running the given program? [8]
Select one correct answer.
1 class AA{}
2 class BB extends AA{}
3 class Q6
4 {
5 public static void main(String arg[])
6 {
7 AA a=null;
8 BB b=(BB)a;
9 System.out.println(b);
10 System.out.println(b instanceof BB);
11 System.out.println(b instanceof AA);
12 }
13 }
(a) Program compiles correctly and print null,true,false.
(b) Program compiles correctly and print null,true,true.
(c) Program compiles correctly and print null,false,false.
(d) Program compiles correctly and print null,false,true.
(e) Compile time error at line no.8 as null value cannot be casted.
(f) Run time error at line no. 8 as null value cannot be casted.

2.11) Which one of the following are valid character contants? [8]
Select any two.
(a) char c = '\u000d' ;
(b) char c = '\u000a';
(c) char c = '\u0000';
(d) char c = '\uface' ;










Answers:
2.1) (c), (d)
Unlike & and operators, the && and operators short circuit the evaluation of their operands if the result of the operation can be determined just based on the value of the first operand. The second operand of the operation in the program is never evaluated. Variable i ends up with the value 3 which is the first digit printed, and j ends up with a value of 1 which is the second digit printed.

2.2) (a)
To explain u in a more simple way...

int k = 10;
int j;

Post increment :
j = k++;

In this statement the value of k is 10, & there is a ++ operator also
attached with it, so it will be assigned to j, so now j gets 10, but
k becomes as 11 because the ++ expression comes after the variable,
or if u see k as k++.

Pre-increment :
j = ++k;
In this case, k is having 10 as value, then the pre-increment
operation is being performed, so k becomes 11 in this case, & then it
is being assigned to j, so now j becomes 11 & k also becomes 11.

The thing which u have must have noticed in the post increment & pre-
increment is that the value of k is increased by 1, where as j in the
first case becomes 10 & in second case j becomes 11.

2.3) (b)
The compiler creates one String object for both s1 and s2, thus “equal” appears. But using the new String operator two distinct objects are created so “s3 eq s4” does not appear.

2.4) (c)
The compiler promotes variable A to a long before the comparison. The compiler does not report “Invalid character in input” in line 3 because this is correct form for initializing a char primitive. Therefore, answer (a) is incorrect. Because (c) is correct  (b) cannot possibly be correct.

2.5) (a)
The default value for a boolean declared at class level is false, and integer is 0, and 1 is within the range of the char and don’t need casting.

2.6) (d)
In the call another(v,i);
A COPY of the reference to v is passed and thus any changes will be intact after this call.

2.7) (a)
The ONLY correct way to check a reference for the null value. Answer (b) is incorrect because if x is null, there will not be an object whose equals method can be called. This statement would cause a NullPointerException at runtime when x is null. Answer (c) is incorrect because only a reference type, such as a class, or array, can be the right operand of the instanceof operator.

2.8) (c)
First of all value of b which is 1 is assigned to array index then rest of the code will be executed.

2.9) (c)
Compile time error: There is no operator like &&=

2.10) (c)
As null value can be casted but do remember it is of no use to cast null value that is why it is written in Khalid Mughal's book that we can not cast null value.Secondly,instanceof operator always return false for null value.

2.11) (c), (d)
'\u000d' and '\u000a' are not valid as these value do line break. Note:'\u000a' is not valid even when used behind single line comments (i.e. //.....),but offcourse for multiline comment it is valid. '\uface' is valid because we can use any character from range 0 - 9 or A - F or a - f.

Chapter 1: Language fundamentals

Chapter 1:
Language fundamentals

1.1) Which of the following lines are valid declarations? [1] [3]
(a)char a = ‘\u0061’;
(b)char \u0061 = ‘a’;
(c)ch\u0061r a = ‘a’;
(d)char a = (char) 65;

1.2) Is an empty file a valid source file? [1]
(a) True.
(b) False.

1.3) Which of these are valid declaration of the main() method? [1]
(a) static void main(String args[]) {/* … */}(b) public static int main(String args[]) {/* … */}(c) public static void main(String args) {/* … */}(d) final static public void main(String[] arguments) {/* … */}(e) public int main(String args[], int argc) {/* … */}(f) public void main(String args[]) {/* … */}
1.4) Which one of the following are not valid character constants? [8]
Select any two.
(a) char c = '\u00001' ;
(b) char c = '\101';
(c) char c = 65;
(d) char c = '\1001' ;



Answers:
1.1) (a), (b), (c), (d)
All are valid declarations. The \uxxxx notation can be used anywhere in the source to represent Unicode characters, and also casted integer to a char primitive type.

1.2) (a)
Although nonsensical, an empty file ia a valid source file. A source file can contain an optional package declaration, any number of import statements and any number of class and interface definitions.

1.3) (d)
A valid declaration of the main() method must be public and static, have void as return type and take a single array of String objects as arguments. The order of the static and public keywords is irrelevant. Also, declaring the method final does not affect the method’s potential to be used as a main() method.

1.4) (a), (d)
You cannot use five digits after \u."char c = 65" is valid because it will take it as ascii value. '\101' is representing a octal value which is equivalent to 65 which is valid but '\1001' is not valid as its decimal value is 513 and you can give only those values which represent 0 to 255 in decimal.