Java by Nageswara Rao
Java by Nageswara Rao
Ans)
2. Pointers may crash a program easily, for example, when we add two pointers, the
program crashers immediately.
3. Pointers break security. Using pointers, harmful programs like Virus and other hacking
programs can be developed. Because of the above reasons, pointers have been
eliminated from java.
3) Which part of JVM will allocate the memory for a java program?
Ans). Class loader subsystem of JVM will allocate the necessary memory needed by
the java program.
Ans). Garbage collector uses many algorithms but the most commonly used
algorithm is mark and sweep.
Ans). Garbage collector is automatically invoked when the program is being run. It
can be also called by calling gc() method of Runtime class or System class in Java.
Ans). JIT compiler is the part of JVM which increases the speed of execution of a Java
program.
Ans). An API document is a .html file that contains description of all the features of a
softwar, a product, or a technology. API document is helpful for the user to
understand how to use the software or technology.
Ans). #include directive makes the compiler go to the C/C++ standard library and
copy the code from the header files into the program. As a result, the program size
increases, thus wasting memory and processor’s time.
import statement makes the JVM go to the Java standard library, execute the code
there , and substitute the result into the program. Here, no code is copied and
hence no waste of memory or processor’s time. so import is an efficient mechanism
than #include.
Ans). Both methods are used to display the results on the monitor. print( ) method
displays the result and then retains the cursor in the same line, next to the end of
the result. println( ) displays the result and then throws the cursor to the next line.
The code will compile but JVM cannot run the code because it cannot recognize the
main( ) as the method from where it should start execution of the Java program.
Remember JVM always looks for main( ) method with string type array as parameter.
Ans). Float can represent up to 7 digits accurately after decimal point, where as
double can represent up to 15 digits accurately after decimal point.
Ans). Unicode system is an encoding standard that provides a unique number for
every character, no matter what the platform, program, or language is. Unicode
uses 2 bytes to represent a single character.
Ans). Positive numbers are represented in binary using 1’s complement notation
and negative numbers are represented by using 2’s complement notation.
Ans). Both bitwise right shift operator ( >> ) and bitwise zero fill right shift operator
( >>> ) are used to shift the bits towards right. The difference is that >> will
protect the sign bit whereas the >>> operator will not protect the sign bit. It always
fills 0 in the sign bit.
Ans). Control statements are the statements which alter the flow of execution and
provide better control to the programmer on the flow of execution. They are useful
to write better and complex programs.
Ans). Return statement is used inside a method to come out of it. System.exit( 0) is
used in any method to come of the program.
Ans). System.out and System.err both represent the monitor by default and hence
can be used to send data or results to the monitor. But System.out is used to display
normal messages and results whereas System.err is used to display error messages
and System.in represents InputStream object, which by default represents standard
input device, i.e., keyboard.
Ans). Arrays are created on dynamic memory by JVM. There is no question of static
memory in Java; every thing( variables, array, object etc.) is created on dynamic
memory only.
23) Can you call the main( ) method of a class from another class ?
Ans). Yes , we can call the main( ) method of a class from another class using
Classname.main( ) . At the time of calling the main( ) method, we should pass a
string type array to it.
24) Is String a class or data type ?
Ans). String is a class in java.lang package. But in Java, all classes are also
considered as data types. So we can take String as a data type also.
Ans). Yes, a class is also called ‘ user-defined’ data type. This is because a use can
dreate a class.
Ans). = = operator compares the references of the sting objects. It does not
compare the contents of the objects. equals ( ) method compares the contents.
While comparing the strings, equals( ) method should be used as it yields the
correct result.
Ans). Sring constant pool is a separate block of memory where the string objects are
held by JVM. If a sting object is created directly, using assignment operator as:
String s1 = “Hello”,then it is stored in string constant pool.
Ans). In the first statement, assignment operator is used to assign the string literal
to the String variable s. In this case, JVM first of all checks whether the same object
is already available in the string constant pol. If it is available, then it creates
another reference to it. If the same object is not available, then it creates another
object with the content “Hello “and stores it into the string constant pool.
In the second statement, new operator is used to create the string object; in this
case, JVM always creates a new object without looking in the string constant pool.
Ans). String class objects are immutable and hence their contents cannot be
modified. StringBuffer class objects are mutable, so they can be modified. Moreover
the methods that directly manipulate data of the object are not available in String
class. Such methods are available in StringBuffer class.
31) Are there any other classes whose objects are immutalbe ?
Ans). Yes, classes like Character, Byte, Integer, Float, Double, Long..called ‘wrapper
classes’ are created as ‘immutable’.Classes like Class, BigInteger, Big Decimal are
also immutable.
32) What is the difference between StringBuffer and StringBuilder
classes?
Ans). A class is a model for creating objects and does not exist physically. An object
is any thing that exists physically.Both the classes and objects contain variables and
methods.
Ans). Hiding the unnecessary data from the user and expose only needed data is of
interest to the user.
A good example for abstraction is a car. Any car will have some parts like engine,
radiator, mechanical and electrical equipment etc. The user of the ca r (driver)
should know how to drive the car and does not require any knowledge of these
parts. For example driver is never bothered about how the engine is designed and
the internal parts of the engine. This is why, the car manufacturers hide these parts
from the driver in a separate panel, generally at the front.
Example in java:
?
1 Class Bank{
2 Private int accno;
Private String name;
3 Private float balance;
4 Private float profit;
5 Private float loan;
6 Public void desplay_to _clerk(){
System.out.println(“Accno= “+accno);
7 System.out.println(“Name=” +name);
8 System.out.println(“Balance=”+balance);
9 }
1 }
0
11
1
2
Ans). It creates new classes from existing classes, so that the new classes will
acquire all the features of the existing classes is called inheritance. (or) Acquiring
the all properties from base class to child class .
Ans). The word ‘Polymorphism’ came from two Greek words ‘poly’ meaning ‘many’
and ‘morphs’ meaning ‘forms’ . Thus, polymorphism represents the ability to
assume several different forms. In programming, we can use a single variable to
refer to objects of different types and thus, using that variable we can call the
methods of the different objects. Thus a method call can perform different tasks
depending on the type of the object.
Ans). Object oriented programming languages follow all the features of Object
Oriented Programming System(OOPS). Smalltalk, Simula-67,C++, Java are
examples for OOPS languages.
Object based programming languages follow all the features of OOPS except Inheritance. For
example, JavaScript and VBScript will come under object based programming languages.
Ans). Hash code is unique identification number alloted to the objects by the JVM.
This hash code number is also called reference number which is created based on
the location of the object in memory, and is unique for all objects, except for String
objects.
Ans). No, if we declare a class as private, then it is not available to java compiler
and hence a compile time error occurs, but inner classes can be declared as private.
Ans). A Constructor is called concurrently when the object creation is going on. JVM
first allocates memory for the object and then executes the constructor to initialize
the instance variables. By the time, object creation is completed; the constructor
execution is also completed.
Constructors Methods
A constructor is used to initialize A method is used for any general
the instance variables of a class. purpose processing or
calculations.
A constructor’s name and class A method’s name and class
name should be same. name can be same or different.
A constructor is called at the A method can be called after
time of creating object. creating the object.
A constructor is called only once A method can be called several
per object. times on the object.
Ans). Writing two or more constructors with the same name but with difference in
the parameters is called constructor overloading. Such constructors are useful to
perform different tasks.
Ans). Instance methods are the methods which act on the instance variables of the
class. To call the instance methods , we should use the
form; objectname.methodname( ).
Ex:
?
1double x = obj.sum( );
48) What are static methods?
Ans). Static methods are the methods which do not act upon the instance variables
of a class. Static methods are declared as ‘static’.
Ans). After executing static methods, JVM creates the objects. So the instance
variables of the objects are not available to static methods.
Ans). Premitive data types, objects, even object references – every thing is passed
to methods using ‘pass by value’ or ‘call by value’ concept. This means their bit by
bit copy is passes to the methods.
Ans). A factory method is a method that creates and returns an object to the class
to which it belongs. A single factory method replaces several constructors in the
class by accepting different options from the user, while creating the object.
Ans). It is an inner class whose name is not written in the outer class and for which
only one object is created.
Ans). Deriving new classes from existing classes such that the new classes acquire
all the features of existing classes is called inheritance.
Ans). Because, the sub class object contains a copy of super class object.
Ans). In inheritance a programmer reuses the super class code without rewriting it,
in creation of sub classes So, developing the classes becomes very easy. Hence, the
programmer’s productivity is increased.
Ans). Multiple inheritance is not available in Java for the following reasons:
Ans). There are two types of inheritances single and multiple. All other types are
mere combinations of these two.However, Java supports only single inheritance.
Ans). Coercion is the automatic conversion between different data types done by
the compiler.
Ans). Conversion is an explicit change in the data type specified by the operator.
Ans). Method signature represents the method name along with method parmeters.
65) What is method overloading?
Ans). Writing two or more methods in the same class in such a way that each
mehtod has same name but with different method signatures – is called method
overloading.
Ans). Writing two or more methods in super and sub classes such that the methods
have same name and same signature is called method overriding.
Ans). No, private methods are not available in the sub classes, so they cannot be
overriden.
Ans). NO. Both methods are different.A final method is not the same as a private
method. The only similarity is that they cannot be overridden, But final methods are
visible to subclasses, private methods are not.
72) What is difference between primitive data types and advanced data
types ?
Ans). Primitive data types represent single values. Advanced data types represent a
group of values. Also methods are not available to handle the primitive data types.
In case of advanced data types, methods are available to perform various
operations.
Ans). Automatic casting done by the Java compiler internally is called implicit
casting . Implicit casting is done to converty a lower data type into a higher data
type.
Ans). The cating done by the programmer is called explicit cating. Explicit casting is
compulsory while converting from a higher data type to a lower data type.
Ans). Converting lower data type into a higher data type is called widening and
converting a higher data type into a lower type is called narrowing. Widening is safe
and hence even if the programmer does not use cast operator, the Java compiler
does not flag any error. Narrowing is unsafe and hence the programmer should
explicitly use cast operator in narrowing.
81) How can you force your programmers to implement only the
features of your class ?
Ans). No, abstract class needs sub classes. final key word represents sub classes
which can not
be created. So, both are quite contradictory and cannot be used for the same class.
Ans). An interface is a specification of method prototypes, All the methods of the interface are
public and abstract.
84) Why the methods of interface are public and abstract by default ?
Ans). Interface methods are public since they should be available to third party
vendors to provide implementation. They are abstract because their implementation
is left for third party vendors.
Ans). No, we can’t implementing an interface means writing body for the methods.
This can not be done again in an interface, since none of the methods of the
interface can have body.
Ans). event is a sub package of java.awt package. But, when a package is imported,
its sub packages are not automatically imported into a program. So, for every
package or sub package, a separate import statement should be written. Hence if
the programmer wants the classes and interfaces of both the java.awt and
java.awt.event packages, then he should both the preceding statements in his
program.
Ans). We can call garbage collector of JVM to delete any unused variables and
unreferenced objects from memory using gc( ) method. This gc( ) method appears
in both Runtime and System classes of java.lang package. For example, we can call
it as:
System.gc( );
Runtime.getRuntime( ).gc( );
1. import pack.Addition;
2. import pack.*;
Ans) . In statement 1, only the Addition class of the package pack is imported into
the program and in statement 2, all the classes and interfaces of the package pack
are available to the program.
If a programmer wants to import only one class of a package say BufferedReader of
java.io package, we can write import java.io.BufferedReader;
Ans) . The CLASSPATH is an environment variable that tells the Java compiler where
to look for class files to import. CLASSPATH is generally set to a directory or a
JAR(Java Archive)file. Set the Classpath after installing java.
Ans) A Java Archive file (JAR) is a file that contains compressed version of several
.class files, audio files, image files or directories. JAR file is useful to bundle up
several files related to a project and use them easily.
Ans). Default members are available within the same package, but not outside of
the package. So their scope is package scope.
Ans). The code compiles but JVM cannot run it, as it cannot see the main( ) method
with String args[ ].
Ans). The exceptions that are checked at compilation-time by the Java compiler are
called ‘checked exceptions’. The exceptions that are checked by the JVM are called
‘unchecked exceptions’.
Ans). Throwable is a class that represents all errors and exceptions which may occur
in Java.
Ans). throws clause is used when the programmer does not want to handle the
exception and throw it out of a method. throw clause is used when the programmer
wants to throw an exception explicitly and wants to handle it using catch block.
Hence, throws and throw are contracictory.
Ans). Yes, we can re-throw an exception from catch block to another class where it
can be handled.
104). Which of the wrapper classes contains only one constructor ? (or)
Which of the wrapper classes does not contain a constructor with String
as parameter ?
Ans). Character.
Ans). Ideally a string with an integer value should be passed to parseInt ( ) method.
So, on parsing “Hello”, an exception called “NumberFormatException’ occurs since
the parseInt( ) method cannot convert the given string “Hello” into an integer value.
Ans). Both are useful to retreive elements from a collection. Iterator can retrieve the
elements
only in forward direction. But Listener can retrieve the elements in forward and
backward direction also. So ListIterator is preferred to Iterator.
Ans). Both are useful to retreive elements from a collection. Iterator has methods
whose names are easy to follow and Enumeration methods are difficult to
remember. Also Iterator has an option to remove elements from the collection which
is not available in Enumeration. So, Iterator is preferred to Enumeration.
2. Insertion and deletion of elements only from the top of the Stack is possible.
Insertion and deletion of elements from any where is possible in case of a
LinkedList.
ArrayList Vector
ArrayList increases its size every Vector increases its size every
time by 50 percent (half). time by doubling it.
Ans). 0.75.
Ans).
Set List
A Set represents a collection of A List represents ordered collection of
elements. Order of the elements may elements.List preserves the order of
change in the Set. elements in which they are entered.
Set will not allow duplicate values to List will allow duplicate values.
be stored.
Accessing elements by their index Accessing elements by index is
(position number) is not possible in possible in lists.
case of Sets.
Sets will not allow null elements. Lists allow null elements to be stored.
Ans). Both are used to display messages on the monitor. System.out is used to
display normal messages
As:
System.out.println(“This is nayanimuralidhar”);
System.err.println(“This is an error”);
Ans). Streams are mainly useful to move data from one place to another place. This
concept can be used to receive data from an input device and send data to an
output device.
121). What is the default buffer size used by any buffered class ?
Ans). Serialization is the process of storing object contents into a file. The class
whose objects are stored in the file should implement ‘serializable’ interface of
java.io.package.
Once the objects are stored into a file, they can be later retrieved and used as and
when needed.This is called de-serialization.
Ans). main thread. A thread represents execution of statements. The way the
statements are executed is of two types: 1). Single tasking 2). Multi tasking.