Latest :

Java Interview Questions : For Beginners With Sample Examples

           

  1. What is instance actually mean in line “An Object is instance of class.”.?

Instance means an example (or an occurrence). So an object is an example of a class. We can understand it as ‘Gandhi’ is an example of the class ‘Human’, similarly ‘Lincoln’ is an example of the class ‘Human’ and ‘Mother Teressa’ is an example of ‘Human’. So these sentences can be termed as ‘Gandhi’ is an object of the class ‘Human’ and ‘Lincoln’ is an object of the class ‘Human’

  1. what are java flavours.?

We have 3 standard editions

  1. J2SE (Standard Edition) : generally for Stand-Alone applications
  2. J2EE (Enterprise Edition) : generally for Web Applications
  3. J2ME (Macro Edition) : generally for Mobile and Device Applications

 

  1. What is java Statement.?

A statement is a set of tokens that form a meaningful operation. Each of the following lines is a statement.

  1. int a;
  2. out.println(“himani”);
  3. if(a==b) c=c+d;
  4. for(a=1; a<=n; a++) System.out.print(“hi”);
  5. break;

 

  1. What is javaBlock.?

A set of statements enclosed inside a pair of curly braces is known as a Block. In the following two example, //some stuff is inside a block.

Eg1:

if(a==b)

{

            //some stuff

}

Eg2:

while(a<b)

{

            //some stuff

}

 

 

  1. What are Features of java?

Object oriented

Multi-Threaded

Simple

Robust

Portable

Dynamic

Platform independent

Architecture neutral

Secured

Compiled and Interpreted

Distributed

  1. what are local variables and instance variables.?

Local variables are created in a method and they can be used in that method only. These are used for temporary purpose in that particular method.

Instance variables are created outside the methods (inside the class) and these variables are created each time a new object of the class is created. If we create 10 objects of the class, then we will have 10 copies of the instance variables.

            class Rect

            {

                        int l,b;  // instance variables

                       

                        void area()

                        {

                                    int a; // local variable

                                    a=l*b;

                        }

                       

                        void peri()

                        {

                                    int p;  // local variable

                                    p=2*(l+b);

                        }

            }

 

  1. In the package Statement “import java.lang.*;”..??? what does here means..?

The statement “import java.lang.*” indicates to make all the classes (*) available in the package “java.lang” to the current java program file. Here * indicates all the facilities (classes, interfaces, enums, abstract classes)

If we want to avail only a particular facility (say one class Exception), then we write the statement as “import java.lang.Exception;”

 

  1. what is Operator? What are different types of Operators.?

Operator is a symbol used to perform an operation(calculation). We have different types of operators like

  • Arithmetic
  • Relational
  • Logical
  • Bitwise
  • Ternary
  • Unary
  • Assignment
  • Etc

 

 

  1. What are different Operators..?

+ – * / % are arithmetic operators

< <= > >= == != are relational operatoars

&& || ! are logical operators

++ — + – ~ are unary operators

?: is ternary (conditional) operators

= += -= *= /= %= &= |= ^= <<= >>= >>>= are assignment operators

 

  1. what is member Operator.?

Dot (.) is member reference operator. Generally this is used to access an element of an object with its reference variable as in

rect1.length

rect2.breadth;

Thread1.start();  // accessing a method using an object reference

similarly it is used to access static elements of a class using an object reference or class name as in

            Thread.sleep(1000); // accessing static method using class name

            Thread.MAX_PRIORITY // accessing static variable using class name

 

  1. What is package.?

A package is a folder/directory that holds a set of related classes, abstract classes, interfaces and enums

 

  1. Of all these packages which is included in our program by default..?

The “java.lang” package is included by default in every program

 

  1. What is String.?

The class String is used to hold a set of characters as a single unit. Anything within a pair of double quotes will be treated as a String object. We can create String objects using String constructors too. When we want to store name of a person, address of a person, etc then we can use String type.

 

  1. what are datatypes used in java.?

The 8 data types (primitive) used in java are…

  1. char
  2. float
  3. double
  4. byte
  5. short
  6. int
  7. long
  8. boolean

 

  1. what is difference between float & double…????

both are used for working with fractional parted values but double is more accurate and can hold bigger values. The default type for storing real numbers is double but not float. Java treats 3.5 as double type value rather than float type value. To treat it as float, we should use type casting like (float)3.5

 

 

  1. how many are required to represent human languages..?

question not clear

 

  1. what is instanceof Operator.?

We have an operator “instanceof” and we can use this to know whether an object belongs to the specified class or its child class. This operator returns a boolean (true or false) as the result.

            class Fruit

            {

            }

            class Vegetable

            {

            }

            class Mango extends Fruit

            {

            }

            class RedMango extends Mango

            {

            }

            class Check

            {

                        public static void main(String arg[])

                        {

                                    Fruit f=new Fruit();

                                    Vegetable v=new Vegetable();

                                    Mango m=new Mango();

                                    RedMango r=new RedMango();

                                    if(f instanceof Fruit) System.out.println(“A”);//true

                                    if(m instanceof Fruit) System.out.println(“C”);//true

                                    if(r instanceof Fruit) System.out.println(“D”);//true

                                    if(f instanceof Mango) System.out.println(“F”);//false

                                    if(m instanceof Mango) System.out.println(“H”);//true

                                    if(r instanceof Mango) System.out.println(“I”);//true                                  

                                    //if(v instanceof Fruit) System.out.println(“B”);error

                                    //if(f instanceof Vegetable) System.out.println(“E”);error

                                    //if(v instanceof Mango) System.out.println(“G”);error

                        }

            }

  1. what is new Operator.?

The new operator is used to create a new memory block dynamically. Generally the memory block would be an object.

 

  1. What is Cast Operator.?

Converting one type of data into another (compatible) type is known as casting. Suppose we want to take a double value into an int variable we will use cast. Here the target type is placed in a set of parenthesis and these parenthesis acts as cast operators with the type mentioned inside.

Eg:

            double d=2.4;

            int a=d; //without cast, not valid

            int b=(int)d;//casted, valid

 

  1. what is Object Casting.?

We can understand it as converting object of one type to another type. But in java we do not convert type of an object. we always cast with references. Suppose a parent class refrence is referring a child class object, and we want a child class reference to refer that object. in that case we cannot directly assign the parent class reference to child class reference, instead we should typecast the parent class reference to target type (child class) while assigning.

Eg:

            class Fruit

            {

            }

            class Mango extends Fruit

            {

            }

            class Check

            {

                        public static void main(String arg[])

                        {

                                    Fruit f=new Mango();

                                    Mango m;

                                    //m=f; not allowed

                                    m=(Mango)f; //valid with casting

                        }

            }

 

  1. What are Control Statements..???

The statements that are used to control the flow of program are known as control statements. The if-else, switch, while, do, for are known as control statements. These would decide whether a statement/block should be executed or not and if executed how many times the statements/block should be executed.

 

  1. what are java Control Statements & different categories..?

the control statements are basically two types

  1. selection statements: if-else, switch
  2. iterative statements: do, while, for

 

  1. what is Switch..?

switch is a selection statement generally used to select one out of multiple possibilities. It is good when we need to check an expression for equality with different constants and perform a corresponding operation.

 

  1. Out of do while and while which is efficient..????

Both are equally efficient. It is just upto the programmer which one to use.

 

  1. what is procedure Oriented. & Object Oriented approach?

The approach where functionality is given higher preference over data is procedure orientedness where as the approach where data is given higher preference over functionality is object oriented. Infact, data is held in the object. so ‘object oriented’ means “data concentrated” (concentrating on data)

  1. what is use of continue.?

The continue statement is used to continue the loop from next iteration by skipping the remaining statements of the current iteration.

 

  1. what is use of return..?

the return statement is used to pass the control back to the calling method from a called method.

 

  1. what is use of exit.?

The exit( ) method is used to terminate the program.

Eg:

            System.exit(0);

 

  1. what is Stream.?

A stream is an entity that holds a sequence of data items. The data items can be bytes, chars, objects, etc. When we want to transfer data from one location to another location, we pass (transfer) the data through a Stream.

Eg:

FileOutputStream : data passing from program to a data file

FileInputStream : data passing from a data file to program

 

  1. What is System.in ,System.out, System.err..?

The in, out and err are static variables (reference variables) defined in the class System like the following.

public final class java.lang.System

{

  public static final java.io.InputStream in;

  public static final java.io.PrintStream out;

  public static final java.io.PrintStream err;

  //some more stuff;

}

As these are static variables, they can be accessed using its class name.

System.in is reference to an object of type InputStream wehre as System.out and System.err are references to objects of PrintStream class.

System.in refers the standard input device (keyboard) of the system

System.out refers the standard output device (monitor) of the system.

System.err refers the standard error device (which is also monitor by default) of the system.

 

  1. What is Binary operator.?

An operator that works on two operands is known as binary operator. Most of the operators we use are binary operators only. When we write an expression like a+b, the operator + works on two operands (a and b) so + is a binary operator here. Similarly in a==b, a<b, a*b, a=b and x&&y the operators ==, <, *, = and && are binary operators.

 

  1. what is Case.?

A case is a part in a switch construction. In case the switch expression matches with a case label then the code in that case will be executed.

 

  1. what is Command line arguments..?

When executing a java program, we can specify some data to it so that the data will be used in the program. Generally, to execute a class named “Hello”, we write the following on the command prompt.

java Hello

if we want to provide some data to the program from command prompt, we can write something like the following on command prompt

            java Hello one two three

here the three words “one”, “two” and “three” are the arguments supplied at command line so that these will be received by the main() method in the class Hello. This is why we use a String array as formal argument in main. These command line arguments (data) will be received by formal argument at main( )

 

  1. what are String class methods.?

The String class has many methods like length(), charAt(), charCodeAt(), indexOf(), lastIndexOf(), toUpperCase(), toLowerCase(), etc.

 

  1. what are access specifiers? Explain me

we have 4 access specifiers “public”, “protected”, “normal/default” and “private”

public elements can be accessed from anywhere

protected elements can be accessed from any where in the current package and from child classes in other packages

normal/default elements can be accessed from anywhere in the current package but not from other packages

private elements can be accessed from within current class only.

 

  1. what is Constructor.?

Constructor is a special method in a class that is automatically invoked whenever a new object is created. Name of the constructor and name of its class should be same.

 

  1. what is polymorphism.?

Having multiple forms for a single interface is known as polymorphism. Method overloading is an example of polymorphism.

 

  1. What is Method signature..???

The type of arguments and the type of return type represent signature of a method.

Eg:

int multiply(int x,int y);

the above method signature indicates that the method named multiply receives 2 integers and returns an integer.

  1. What is method Overloading..??

Having multiple methods with same name but with different type of arguments is referred as method overloading. The following two methods are overloaded, in this, the method names (sum) are same but arguments are different.

int sum(int a,int b);

double sum(double a,double b);

 

  1. what is Static method.?

A method that can be invoked without any concern with an object is known as static method. Invoking a static method with any object of the class will have same effect. Static method can be invoked using its class name also.

            class Rect

            {

                        int l,b; 

                        static void areaFormula() // static method

                        {

                                    System.out.println(“l*b”);

                        }

                        void area() //non-static method

                        {

                                    System.out.println(l*b);

                        }

            }

  1. what is this Operator..?

the “this” is an operator as well as a keyword created by the system to refer the current object. generally it is used in two ways

  1. as a reference to current object
  2. as a method call to invoke one constructor from another constructor of the same class

eg:

      class Rect

      {

                  int l,b; 

                  Rect()

                  {

                              this(10,20); // this as a constructor call

                  }

                  Rect(int l,int b)

                  {

                              this.l = l; // this as a reference

                              this.b = b; // ‘this’ is useful to differentiate between instance variables and local variable when they have same names

                  }

      }

 

  1. In java what is a terminator…?

The class java.lang.Terminator is used by the JVM to receive terminate signals from Operating System.

 

  1. how is final used.?

The keyword final is used to define a final value/meaning to an entity. The entity can be a variable, method or a class.

 

When used on a variable, value of that variable cannot be changed in course of the program.

Eg:     

            final int a=10;

 

When used on a method, the method cannot be overloaded.

Eg:     

            final void sum()

            {

            }

 

When used on a class, that class cannot be inherited.

Eg:

            final class Hello

            {

            }          

  1. what is inheritance.?

The mechanism of acquiring (getting) features from existing classes into new classes is known as inheritance.

 

  1. what is Super.?

The keyword “super” is used in two ways

  1. as a reference to parent part of the object
  2. as a call to parent class constructor

when there are two elements (variables or methods) with same name (one in parent and another in child class) and we want to access the parent class element from child class, then we should qualify the parent element with super

eg:       super.length

to call any specific constructor of the parent class from a child class constructor then we can use super

eg:      

Child()

            {

                        super(10,20);

                        //child stuff

}

 

  1. Why do we use interfaces…????

Interfaces are useful to specify some abstraction so that the actual implementations can be done at a later stage in different ways.

 

  1. what is Garbage Collection.?

It is the mechanism of collecting unusable memory blocks (objects without references) so that they can be used for newer memory allocations.

 

  1. what is recursion..?

calling (invoking) a method by itself (directly or indirectly) is known as recursion.

 

  1. difference between recursion and Iteration..?

recursion is done at method level and iteration is done at block (loop) level

with recursion, the system maintains a stack automatically where the data is stored at each level (when we come back in recursion, the previous values can be used) and in iteration this facility is not available.

A loop is not required for recursion and a loop (do, while or for) is required for iteration.

 

 

  1. what is abstract class.?

A class that has one or more abstract methods is abstract class.

When we do not need any objects to be created for a class, then we can make the class as abstract.

An incomplete class is an abstract class.

  1. what is abstract method…????

a method that does not have any body is an abstract method. The keyword ‘abstract’ is used before the method declaration.

Eg:

abstract class Fruit

            {

                        abstract void color();

            }

 

  1. what is Object class.?

The class “Object” is the root class for almost all of the classes in Java. When we create a class without any parent, the system automatically makes “Object” as the parent class for our class. So the methods in that class are available to all classes. This class is available in the package “java.lang”

 

  1. Which is super class of all the classes including our classes also….????

The class “Object” is the super class for all the classes including our classes.

 

  1. what is inheritance..?

getting features from existing classes into new classes is known as inheritance. The keyword “extends” is used while inheriting.

 

  1. In how many ways we can Create Object in java…????

All objects in java are created dynamically only with the keyword “new”. In languages like C++, objects can be created both statically and dynamically.

 

  1. What is Inner Class…????

A class created inside another class is known as inner class.

Eg:

            class Fruit

            {

                        void color()

                        {

                                    System.out.println(“yellow”);

                                    Seed s=new Seed();

                                    s.size();

                        }

                       

                        class Seed

                        {

                                    void size()

                                    {

                                                System.out.println(“small”);

                                    }

                        }                      

            }

  1. what is java compiler?

A java compiler converts java source code (high level language) into byte code (low level language).

 

  1. What is the difference between an Abstract class and Interface?

An abstract class can have both abstract methods as well as concrete methods. But an interface can have only abstract methods.

Methods in an abstract class can be public, protected, private or normal. But methods in an interface are always public only.

An abstract class can have instance variables as well as static variable. But an interface can have only static variables.

Variables in an abstract class can be normal or final. But in an interface, variables are always final only.

  1. What are checked and unchecked exceptions?

The exceptions for which the compiler checks whether they (exceptions) are properly handled (in our code) are known as checked exceptions.

Eg: Exception, InterruptedException, IOException.

The exceptions for which the compiler does not check whether they are handled or not are known as unchecked exceptions.

Eg: RuntimeException, ArithmeticException, ArrayIndexOutOfBoundsException.

 

  1. What is a user defined exception?

An exception class created by us (programmer) are known as user defined exceptions.

The exceptions that are available by default with JDK are known as standard exceptions.

 

  1. What is the difference between C++ & Java?

Java has better facilities compared with C++. Thought C++ is a base language on which java developed, some of the features of C++ are not taken into java for security and simplicity.

Java does not support operator overloading, multiple inheritance, pointers, etc which are available in C++.

Java has better GUI facilities, memory management facilities (garbage collection), built in multi-threading facilities, network and internet programming facilities, etc.

 

 

  1. What are statements in JAVA ?

A collection of tokens that form a meaningful operation are known as statements.

 

  1. Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA?

An empty interface is known as ‘null interface’. It does not contain any variables or methods.

Eg:

interface Cloneable

{

}

We have some null interfaces in java like Cloneable, Serializable, etc.

Note: Runnable, Externalizable, etc  are not null interfaces, they have some content in them.     

 

In the following example we just are putting 4 Rect objects into a file and then getting those 4 objects back from the file to print the data on screen.

            import java.io.*;

            class Rect implements Serializable

            {

                        int l,b; 

                        Rect(int x,int y)

                        {

                                    l=x;

                                    b=y;

                        }

                        public String toString()

                        {

                                    return ” “+l+” “+b;

                        }

            }

            class Check

            {

                        public static void main(String arg[])  throws Exception

                        {

                                    FileOutputStream fos=new FileOutputStream(“rectobj.txt”);

                                    ObjectOutputStream oos=new ObjectOutputStream(fos);

                                    for(int i=1;i<=4;i++)

                                    {

                                                Rect r=new Rect(i+i,i*i);

                                                oos.writeObject(r);

                                    }

                                    oos.close(); fos.close();

 

                                    FileInputStream fis=new FileInputStream(“rectobj.txt”);

                                    ObjectInputStream ois=new ObjectInputStream(fis);

                                    for(int i=1;i<=4;i++)

                                    {

                                                Rect r=(Rect)ois.readObject();

                                                System.out.println(r);

                                    }

                                    ois.close(); fis.close();

                        }

            }

In this example, if Rect has not implemented Serializable then the program will not run successfully. If we observe, the Serializable interface does not contain any specific methods defined in it. This is why we have not overridden any additional methods in Rect. Rect has only methods concerned to itself. But we have implemented Serializable because the Object-Streams works with Serializable objects only.

  1. Is synchronised a modifier?identifier??what is it??

The keyword “synchronized” is a modifier. None of the keywords can be used as identifiers.

 

  1. What is singleton class?where is it used?

A class for which we can create only one object is known as singleton class. Generally this kind of classes are used while connecting to a database or such resources where only one object (connection object) is required.

 

  1. What is a compilation unit?

A ‘java compilation unit’ is a technical term that describes the format of a java source file.

Some of the rules are mentioned below,

  • The package statement should be the first statement, if it exists,
  • The import statements, if exist, should follow the package statement,
  • It can have only one public container (class, interface, enum, etc),
  • Comments can be anywhere, etc

 

  1. Is string a wrapper class?

No, String is not a wrapper class.

We have wrapper classes for the 8 primitive types (i.e. Integer for int, Boolean for boolean, Character for char, Float for float, Double for double, Byte for byte, Short for short, Long for long).

But, there is no primitive type like string.

String does not hold a simple data, it holds an array of characters (set of data items). So String cannot be a wrapper class.

  1. Why java does not have multiple inheritance?

When multiple inheritance is involved, features of a class may be available in a child class redundantly. It would create many problems in the program. So multiple inheritance is not supported in java.

In the following example, features of A are available in D through B as well as through C. To control this, multiple inheritance is not supported.

Eg:

            class A{}

            class B extends A{}

            class C extends A{}

            class D extends B,C{}

 

  1. Why java is not a 100 % oops?

Some people expect a language to perform all operations through objects only so that the language will be qualified as 100% OOPS language. But java supports primitive types, which are not objects, and hence they say java is not a 100% OOPS language.

 

  1. What is a transient variable?

A transient variable is one that is not serialized when writing object of the class into a file.

Let us take an example here…suppose we have a class like the following

            class Rect implements Serializable

            {

                        int lenght;

                        int breadth;

                        int borderThickness;

            }

When we store the object of it in a file, all the three elements will be stored in the file. If we want only length and breadth to be stored and don’t want the borderThickness to be stored in the file, then we can make the borderThickness as transient. The variables that are temporary or not important are created as transient. The flowing declaration shows the transient in action.

            class Rect implements Serializable

            {

                        int lenght;

                        int breadth;

                        transient int borderThickness;

            }

 

 

  1. Is null a keyword?

NO, null is not a keyword. It is a reserved word in java along with true and false.

 

 

  1. What is the preferred size of a component?

The minimum size (width and height) required to display a content is known as preferred size of the component. Generally components are displayed with their preferred size in FlowLayout. In GridLayout, BorderLayout they are displayed bigger/smaller than their preferred (normal) size.

 

 

  1. What method is used to specify a container’s layout?

The setLayout( ) is used for setting the layout.

 

 

  1. Which containers use a FlowLayout as their default layout?

Panel, Applet, etc use FlowLayout as their default layout.

 

 

  1. What state does a thread enter when it terminates its processing?

Dead (stopped) state.

 

  1. Which characters may be used as the second character in a variable name.

A lower case alphabet, an upper case alphabet, a digit, the underscore or a dollar symbol can be used as second character in a variable name.

 

 

  1. What modifiers may be used with an inner class that is a member of an outer class?

Almost all modifiers can be used with an inner class like final, static, abstract, public, protected, private, etc.

 

 

  1. What is the difference between the >> and >>> operators?

The >> shifts the bits of the given value to right and adds a 0 at left end for positive numbers and adds a 1 at left end for negative numbers.

The >>> shifts the bits of the given value to right and adds a 0 at left end for both positive as well as negative numbers.

 

 

  1. How many bits are used to represent Unicode, ASCII, UTF-, and UTF-characters?

Unicode: 16 bits

ASCII: 8 bits

UTF-8: 8 bits

UTF-16: 16 bits

 

  1. Which java.util classes and interfaces support event handling?

The interface java.util.EventListener, the abstract class java.util.EventListenerProxy, the class EventObject and the exception class java.util.TooManyListenersException from java.util package support event handling.

 

  1. Is sizeof a keyword?

NO, sizeof is not a keyword in java. It is a keyword in C and C++ languages.

 

  1. What are wrapped classes?

A class that encapsulates a primitive type of data is known as wrapper class. We have 8 wrapper classes for the 8 primitive types.

 

  1. Does garbage collection guarantee that a program will not run out of memory?

NO, garbage collection cannot give such guarantee. If all the objects in a program have a reference, and we want new objects to be created and there is no more space for new memory allocation, then garbage collector cannot help. In that case the program terminates with “OutOfMemoryError”.

 

  1. What restrictions are placed on the location of a package statement within a source code file?

It should be the first statement is a source code file (other than comments).

 

  1. Can an object’s finalize() method be invoked while it is reachable?

YES, we can invoke the finalize() method. But it is strongly recommended to leave that work to the system so that it would invoke when it is appropriate.

 

  1. Can a for statement loop indefinitely?

YES, for statement can loop indefinitely.

 

  1. What are order of precedence and associativity, and how are they used?

Order of precedence tells which operation should be evaluated in an expression. (the operation with higher precedence is executed first)

Eg:

            In an expression like 2+3*4-5, the * has higher precedence over + and – so the multiplication (3*4) takes place first.

Out of the + and – operators, both have same precedence. When there are two operators with same precedence, their associativity decides which operation takes place first. As the associativity of + and – are from left to right, the leftone (+) is evaluated first.

            In case of a=b=c=4; there are 3 assignment operators (=) and associativity of = symbol is right to left. The rightside one (c=4) is operated first.

 

 

  1. To what value is a variable of the String type automatically initialized?

String variable (which is a reference variable) is automatically initialized with “null”

 

  1. When a thread is created and started, what is its initial state?

“Running” state.

 

  1. Can an anonymous class be declared as implementing an interface and extending a class?

NO, an anonymous class cannot implement an interface and extend a class at a time.

An anonymous class can implement an interface or extend a class, but cannot do both.

 

  1. What is the range of the short type?

Range of short type is from -32768 to +32767

 

  1. What is the range of the char type?

Range of char type is from 0 to 65535

 

  1. What is the immediate superclass of Menu?

The parent class of java.awt.Menu is java.awt.MenuItem

 

  1. What is the purpose of finalization?

In exception handling mechanism, the “finally” block is used to execute a code irrespective of an exception is raised or not. The code in the “finally” block is executed even when the control returns from the try or catch block.

In garbage collection mechanism, the “finalize()” method is invoked automatically when an object is garbage collected.

 

  1. What invokes a thread’s run() method?

The thread’s run() methods is invoked by start() method.

 

  1. What is the difference between the Boolean & operator and the && operator?

&& (logical AND operator) works on boolean values only.

Eg:      true && true  à results in true

            true && false  à results in false

& (bitwise AND operator) can work on boolean as well as integer type numbers.

Eg:      true & true  à results in true

            true & false  à results in false

            10 & 20  à results in 0

10 & 15  à results in 10

10 & 10 à results in 10

10 & 7  à results in 2

  1. Which Container method is used to cause a container to be laid out and redisplayed?

The validate() method

 

  1. What is the purpose of the Runtime class?

It is used to perform some runtime activities like invoking garbage collector, terminating the program, halting the program, executing a process, finalizing objects, etc.

 

  1. How many times may an object’s finalize() method be invoked by the garbage collector?

Only once

 

  1. What is the purpose of the finally clause of a try-catch-finally statement?

In exception handling mechanism, the “finally” block is used to execute a code irrespective of an exception is raised or not. The code in the “finally” block is executed even when the control returns from the try or catch block.

 

 

  1. What is the argument type of a program’s main() method?

The main() should have a reference to array of Strings.

Eg: public static void main(String[] arg)

 

  1. Which Java operator is right (right to left) associative?

! (logical NOT)

~ (bitwise NOT)

= (assignment)

++ and — (increment and decrement)

? : (conditional)

+ (positive sign)

– (negative sign)

 

  1. What is the Local class?

A class defined inside a method is known as local class.

A class defined inside another class is known as nested/inner class.

 

  1. Can a double value be cast to a byte?

Yes, we can cast explicitly.

 

  1. What is the difference between a break statement and a continue statement?

The break takes the control out of a looping construct (so that the next iterations will not take place).

the continue takes the control to next iteration by skipping the remaining statement of the current iteration. (so next iteration takes place)

the break statement can be applied to come out of a switch construct also but continue can be applied on loops (do, while and for) only.

 

  1. What must a class do to implement an interface?

The class should implement (override) all methods of the interface.

 

 

  1. What method is invoked to cause an object to begin executing as a separate thread?

The start() method is used for this purpose.

 

 

  1. How are commas used in the intialization and incrementation parts of a for statement?

Commas can be used to write multiple statements as part of the initialization part of a for loop. Upto the first semicolon all the statements are treated as initialization part only.

Similarly, in the incrementation part also we can write multiple statements separated by commas.

Eg:

            int a,b,c;

            for(a=1, b=10, c=5; a<=b; a++, b–,c*=2)

                        System.out.println(a+” “+b+” “+c);

 

  1. What is the purpose of the wait(), notify(), and notifyAll() methods?

The wait() methods makes a thread wait (sleep) upto another thread notifies it.

The notify() method informs the thread that is waiting for a common resource.

The notifyAll() method informs all the threads waiting for the common resource.

 

  1. What is an abstract method?

A method without a definition body is known as an abstract method.

 

  1. How are Java source code files named?

They are saved with an extention “.java”. the primary name would be name of the public class in the file. If public class is not there, we can give any primary name to the file. But it is strongly recommended to write a separate file for each class. So it is a good practice to give name of the class to the file also.

 

  1. What is the relationship between the Canvas class and the Graphics class?

When we write a GUI application, we use paint method something like the following…

            public void paint(Graphics g)

            {

                        g.setColor(Color.RED);

            }

The Graphics object is actually passed by the Canvas object.

 

  1. What are the high-level thread states?

“Ready”, “Running”, “Sleeping” and “Dead” states.

 

  1. What value does read() return when it has reached the end of a file?

The value -1 is returned by read() when it reaches end of file.

 

  1. Can a Byte object be cast to a double value?

YES, we can cast Byte object to a double value.

Even without casting also, this conversion takes place implicitly.

 

  1. What is the difference between a static and a non-static inner class?

A non-static inner class can access all elements of the outer class as a non-static method has.

Similarly, a static inner class cannot access non-static elements of the outer class. A static inner class can access only the static elements of the outer class as a static method does.

  1. What is the difference between the String and StringBuffer classes?

Content in a String object cannot be modified where as content in a StringBuffer object can be modified.

 

  1. If a variable is declared as private, where may the variable be accessed?

Only within the class.

 

  1. How are the elements of a BorderLayout organized?

They can be organized in 5 places, it means at NORTH (top), EAST (right), SOUTH (bottom), WEST (left) and CENTER (middle).

 

 

  1. What is the % operator?

This is used to get remainder after a division.

Eg:      25%5 à 0

            25%7 à 4

            25%9 à 7

 

  1. When can an object reference be cast to an interface reference?

If the interface is a parent to the class of the object, then we can cast reference of the object to reference of the interface.

Eg:

            interface Mother {}

            class Daughter implements Mother{}

            Mother m;

            Daughter d;

            m=d;

 

  1. What is the difference between a Window and a Frame?

Window is the parent class of Frame. The Frame can have a Menubar where as a Window cannot have a Menubar. So we generally prefer Frame over Window in our programs. If we don’t want any menus, then there is not much difference between Window and Frame.

The Window (java.awt.Window) provides most of the functionalities for Frame (java.awt.Frame). the Frame is created like the following.

            class Frame extends Window implements MenuContainer

{

}

The title bar, borders, close button, restore button, minimize button, resizable options, moveable options, etc all come from Window only to Frame.

  1. Which class is extended by all other classes?

The “Object” class is extended by all other classes.

 

 

  1. Can an object be garbage collected while it is still reachable?

NO, it cannot be garbage collected.

Only the objects without references can be garbage collected.

 

  1. Is the ternary operator written x : y ? z or x ? y : z ?

The expression x ? y : z is proper way.

 

 

  1. How is rounding performed under integer division?

In integer division, the rounding is not at all required. (but speaking in terms of rounding, we can say lower bound is taken)

 

 

  1. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

Reader/Writer work with char type data primarily.

InputStream/OutputStream work with byte type data primarily.

 

 

  1. What classes of exceptions may be caught by a catch clause?

Only “Throwable” and its subclasses.

 

  1. If a class is declared without any access modifiers, where may the class be accessed?

It can be accessed from anywhere in the current package but not from other packages.

Without an access specifier a class become “normal/default”. The “public” classes can be accessed from outside packages.

 

 

  1. Does a class inherit the constructors of its superclass?

NO, constructors are not inherited.

 

 

  1. What is the purpose of the System class?

Like “Object”, the “System” class also very much useful as it provides facilities for standard input, output operations, terminating the program, invoking garbage collector, etc. But “System” cannot be inherited into other classes as it is a ‘final’ class.

 

 

  1. How are the elements of a CardLayout organized?

They are arranged one over another like a stack (at a place) and we generally make any one out of them visible based on the user selections.

 

  1. Is &&= a valid Java operator?

NO, it is not a valid java operator.

 

 

  1. Name the eight primitive Java types?

The 8 primitive data types in java are byte, short, int, long, float, double, char and boolean.

 

 

  1. What is the relationship between clipping and repainting?

Clipping is used for repainting part of a window.

Rendering (displaying) the window content is generally referred as painting the window. A window is kept painted whenever an operation (like some other window covers and uncovers the window, the window is minimized and then restored, etc) is performed on the window. This is known as repainting and this is done using repaint() method.

If we need to repaint only part of the window then we (or the system) sets the bounds for the repaintable area. This is known as clipping.

 

  1. Is “abc” a primitive value?

NO, it is not a primitive value. It is a String.

 

 

  1. What is the relationship between an event-listener interface and an event-adapter class?

A listener interface provides only abstract methods and its corresponding adapter class provides dummy implementations to methods of the interface.

 

 

  1. What restrictions are placed on the values of each case of a switch statement?

The values (labels) of a case can be integer constants only. (Obviously, char type is also allowed)

From java 1.7 onwards, String constants can also be used as case labels.

Variables and fractional parted values are not allowed.

No two case labels in a switch construction should be same.(duplicate case labels are not allowed)

 

  1. What modifiers may be used with an interface declaration?

An interface can be ‘public’ or ‘normal’ (in terms of access specification) when created normally. When created innerly (inside a class), all access specifiers are accepted.

Eg:

            class Check

            {

                        interface c1{ }  //valid

                        public interface c2{ } //valid

                        protected interface c3{ }  //valid

                        private interface c4{ }  //valid

            }

            interface A{ }  // valid

            public interface B{ } // valid (name of the file should be B.java

            //protected interface C{ } //not valid

            //private interface D{ } //not valid

 

An interface is ‘abstract’ by default, and if we want we can explicitly mention it. An openly (outerly) created interface should be not ‘static’ but an inner interface (created inside a class) can be ‘static’.

Eg:

            class Check

            {

                        abstract interface c1{}  //valid

                        static interface c2{} //valid

            }

           

            abstract interface A{}  // valid

            //static interface B{} // not valid

 

  1. Is a class a subclass of itself?

NO, a class cannot be a subclass of itself.

 

 

  1. What is the Collection interface?

Collection interface provides basic abstractions for all classes, abstract classes and interface of the collection hierarchy. The data structures like ArrayList, LinkedList, Stack, HashSet, Vector, List, Set, Queue, Deque, AbstractList, AbstractQueue, etc all come under “Collection” interface only.

 

  1. What is the purpose of the File class?

The File class provides the facilities to get properties of a file. The properties can be getting

  • name of the file,
  • path of the file,
  • is the file readable,
  • is the file writable,
  • is the file hidden,
  • is that a file or directory,
  • is the file existing,
  • size of the file,
  • Get the files and directories in it (if it were a directory),
  • when the file was modified last, etc.

Some of the above properties can be set with File object.

 

  1. Can an exception be rethrown?

YES, an exception can be re-thrown.

The keyword ‘throw’ can be used for this purpose if we want to rethrow an exception exclusively.

If catch block(s) cannot handle an exception, then the exception is implicitly rethrown by the system.

 

 

  1. Which Math method is used to calculate the absolute value of a number?

Math.abs( )

This methods takes a value as argument and returns the absolute value of that argument. It has 4 overloaded versions like…

  public static int abs(int);

  public static long abs(long);

  public static float abs(float);

  public static double abs(double);

 

  1. When does the compiler supply a default constructor for a class?

If we do not provide (supply) any constructor in a class then the system supplies the default constructor.

 

 

  1. When is the finally clause of a try-catch-finally statement executed?

It is always executed (whether an exception is raised or not) when the control comes to a try-catch block.

This block is executed when any one of the following things happen…..

  • After executing the try block successfully
  • After executing the catch block
  • Before returing to calling method from the try block
  • Before returning to calling method from the catch block

 

 

  1. Which class is the immediate superclass of the Container class?

Component (java.awt.Component) is the immediate super class of Container (java.awt.Container)

 

 

 

  1. If a method is declared as protected, where may the method be accessed?
  • from any class of current package.
  • From subclasses of other packages.

 

 

  1. Which non-Unicode letter characters may be used as the first character of an identifier?

All characters that we use are under UniCode only.

The non-alphabetic character that can be used as first character of an identifier are underscore ( _ ) and dollar ( $ ).

 

 

  1. What restrictions are placed on method overloading?

When methods are overloaded, their names should be same and arguments should be different.

 The difference in arguments can be in terms of number, type or order.

 

 

  1. What is casting?

The conversion of a data item from one type to other type is known as casting.

Eg:

            int a = 3.5; //invalid

            int b = (int)3.5; //valid – in this example, (int) is used for casting

 

 

  1. What is the return type of a program’s main() method?

Return type of main is always “void”

 

  1. What class of exceptions are generated by the Java run-time system?

It throws the RuntimeExceptions (RuntimeException and their subclasses) and Errors (Error and their subclasses) which we generally call as unchecked exceptions.

The compiler would check the checked exceptions only but not check the unchecked exceptions. That is why we do not get any compilation error even though we have any possibility of unchecked exception to rise in our code.

  1. What is the difference between a field variable and a local variable?

A field variable (instance variable) is created as part of the object. if we create N objects of a class, then we would have N copies of field variables (one for each object). these are destroyed when the object is destroyed (generally when the object is garbage collected or when the program ends).

A local variable is created inside a method and the variable is destroyed when the method ends. If the control comes to the method again, the local variable is created afresh. If a recursion takes place, multiple copies of the local variable is created.

 

  1. Under what conditions is an object’s finalize() method invoked by the garbage collector?

The finalize() method is invoked when the garbage collector deallocates (destroys) an object. an object is deallocated only if it is not referred by any reference. We cannot give any guarantee that ‘all objects without reference’ will be deallocated because the garbage collector is not activated everytime an object looses its references.

Generally the garbage collector is invoked in the following situations…

  • periodically
  • when there is memory requirement but not sufficient free memory.

 

  1. How are this() and super() used with constructors?

The this() is used to call one constructor from another constructor of the same class.

The super() is used to call a parent class constructor from a child class constructor.

 

  1. How is it possible for two String objects with identical values not to be equal under the == operator?

Because, == compares the hashcodes but not the actual content.

Let us assume the following two statements

String s1=”himani”;

String s2=”himani”;

With the first statement, a String object with the data “himani” is created and that object will be referred by s1. (hashcode of the created String object is stored in s1).

With the second statement, another String object with the data “himani” is created and that object will be referred by s2. (hashcode of the created String object is stored in s2).

The expression s1==s2 would compare the hashcodes stores in s1 and s2. As the hashcodes of both the objects are different, the expression would result in false.

If we want to compare the actual data, then we better to use s1.equals(s2)

 

  1. Why are the methods of the Math class static?

The operations performed by the methods in Math class are done on the arguments we pass to them. There is no need to store some value in advance and work on them at a later stage. So there is no need of created an object, generally. To call a method without an object, that method should be static. This is why all methods in Math class are static.

 

  1. What Checkbox method allows you to tell if a Checkbox is checked?

The getState() method can be used to know whether a Checkbox (java.awt.Checkbox) is selected or not. If the Checkbox is selected it returns true otherwise it returns false.

If we want to know the status of JCheckBox (javax.swing.JCheckBox), then we can use isSelected() method. This also gives true if the JCheckBox is selected otherwise it returns false.

 

  1. What state is a thread in when it is executing?

It is in “Running” state.

 

 

  1. What classes of exceptions may be thrown by a throw statement?

The objects of Throwable and its subclasses are only thrown by the throw statement.

Note: Exception, Error, RuntimeException, IOException, InterruptedException, ArithmeticException, ArrayIndexOutOfBoundsException, etc all are subclasses of Throwable only.

  1. Are true and false keywords?

NO, true and false are not keywords.

The words true, false and null are reserved words in java. The reserved words are almost equal to keywords practically.

 

  1. What happens when you add a double value to a String?

The double value is also converted as a String and String concatenation takes place.

Suppose we write like “Devaki”+17.01, then the system considers it as “Devaki”+”17.01” and a new String “Devaki17.01” is created.

 

 

  1. What is your platform’s default character encoding?

To know exact encoding of our platform we can use a statement like the following…it just prints the character encoding of our system.

Eg:      System.out.println( java.nio.charset.Charset.defaultCharset() );

On windows, it would be “windows-1252” or “windows-1250” or “CP1250” or “CP1252”

On Linux, it would be UTF-8

On Mac, it would be MacRoman

Note: Other character encoding are also possible.

 

  1. Which package is always imported by default?

The java.lang package is always imported by default.

 

  1. What interface must an object implement before it can be written to a stream as an object?

“Serializable” interface should be implemented by an object (its class) before it can be written to a Stream as object.

 

  1. How are this and super used?

The keyword ‘this’ is used in two ways…

  • To call one constructor from another constructor of the same class
  • As a reference to the current object

The keyword ‘super’ is used in two ways…

  • To call a parent class constructor from a constructor
  • As a reference to the parent part of the current object.

 

  1. What is the purpose of garbage collection?

The garbage collector deallocates (clears) the unwanted objects from memory so that, the cleared (collected) memory can be used for further memory requirements.

 

  1. What restrictions are placed on method overriding?

The signatures of both the methods (of the parent class and of the child class) should be same. It means, the arguments, return type along with method name.

 

  1. What happens if an exception is not caught?

The program (in fact, the current thread) will be abnormally terminated.

 

  1. Which arithmetic operations can result in the throwing of an ArithmeticException?

The division operation may result in ArithmeticException

Eg:      23/0

 

 

 

  1. What are three ways in which a thread can enter the waiting state?

The sleep(), join() and wait() methods can make a thread into waiting state.

 

 

 

  1. Can an abstract class be final?

NO, an abstract class cannot be final.

A class can be either abstract or final but cannot be both.

 

  1. What happens if a try-catch-finally statement doesnot have a catch clause to handle an exception that is

In that case, if an exception is raised in the try block, the finally block is executed and then the program is terminated.

If the try-catch-finally is in a method and that method is called from some other block, then the exception is rethrown to that block (parent block)

 

  1. What is the difference between a public and a nonpublic class?

A public class is accessible from other packages but a non-public class is not accessible from other packages.

 

  1. To what value is a variable of the boolean type automatically initialized?

The boolean value is initialized with “false” by default.

 

  1. Can try statements be nested?

YES, try statements can be nested.

 

  1. What is the difference between the prefix and postfix forms of the ++ operator?

The prefix notation increases the value of the variable and then the incremented value would be used in the expression.

Eg:

            int a = 5;

            int b =  ++a + ++a;

                        // with first ++a, a value is incremented by 1 and a becomes 6 and the incremented value will be used there

                        // it means the expression would become b = 6 + ++a;

                        // with the second ++a, a value is again incremented by 1 and a becomes 7 and the incremented value will be used there

                        // it means the expression would become b = 6 + 7

                        // the sum of 6 and 7 is stored in b so b becomes 13 (a became 7)

            System.out.println(a+” “+b);  // 7  13           

The postfix notation uses the existing (original) value of the variable and then increases the value.

Eg:

            int a = 5;

            int b =  a++ + a++;

                        // with first a++, existing value of a (i.e. 5) is taken as value of expression and then a is incremented by 1 to become 6

                        // it means the expression would become b = 5 + a++;

                        // with the second a++, existing value of a (i.e. 6) is taken as value of expression and then a is incremented by 1 to become 7

                        // it means the expression would become b = 5 + 6

                        // the sum of 5 and 6 is stored in b so b becomes 11 (a became 7)

            System.out.println(a+” “+b); // 7  11

 

 

  1. What is the purpose of a statement block?

A statement block is used to group a set of statements as a single unit.

Eg:

            if(condition)

{

                        //statement1;

                        //statement2;

                        //statement3;

}

Here, the 3 statements are grouped as a single unit.

 

 

  1. What is a Java package and how is it used?

A java package is a directory/folder that holds a set of related classes, abstract classes, interfaces and enums.

We can use a package into a program using “import” statements.

 

 

  1. What modifiers may be used with a top-level class?

Only “public” and “normal” modifiers can be used with a top-level classes.

An inner class can be “public”, “protected”, “normal” or “private”

 

 

  1. What are the Object and Class classes used for?

“Object” class is used to provide basic features to all the classes in java. The features includes the methods like the following (as Object is parent class for all other classes, the following features are available in all the classes)….

finalize( )         : invoked when an object is garbage collected

getClass( )       : returns the Class object that gives class details of the object

toString( )       : generally used when we want the String equivalent of the object’s data (by default, the hashcode is given)

equals( )          : generally used to compare data of the object with data of argumented object for equality

clone( )                        : generally used to create a duplicate (clone) of the object

notify( )           : to inform other waiting thread(s) that activitiy of a thread is completed

            wait( )              : to make a thread wait until another thread notifies

 

“Class” class is used to know details of a class with the methods like…. isInterface(), isPrimitive(), getName(), getSuperClass(), getPackage(), getMethods(), getMethod(), getConstructors(), getConstructor(), getFields(), getField(), etc.

Eg:

            class Rect

            {

                        int l,b;

                        Rect(int x,int y)

                        {

                                    l=x;

                                    b=y;

                        }

                        public String toString()

                        {

                                    return l+” “+b;

                        }          

                        static

                        {

                                    System.out.println(“static block”);

                        }

            }

            class Check

            {

                        public static void main(String[] args) throws Exception

                        {

                                    Class.forName(“Rect”);  // the Rect class is loaded with the forName() method of the Class class.              

                                                                                                            // when a class is loaded, its static method will be executed automatically

                                    System.out.println(“going to create Rect object”);  

                                    Rect r = new Rect(10,20);

                                    System.out.println(r); // r.toString() is invoked implicitly

                                    Class c = r.getClass();

                                    System.out.println(c.getName()); //name of the class (Rect) is printed

                        }

            }          

  1. How does a try statement determine which catch clause should be used to handle an exception?

With the raised exception in the try block, the system checks the first available catch block for a match. If that is matched then that particular catch block will be executed. If that is not matched then only the system looks for the next catch block for match. This looking goes on upto the first matched catch block. Once a catch block is matched the remaining catch blocks are not checked.

 

 

  1. Can an unreachable object become reachable again?

NO, once an object has become unreachable, we cannot reach it again.

 

  1. When is an object subject to garbage collection?

As far as garbage collection is concerned, ‘object’ is a memory block created based on a class.

 

  1. What method must be implemented by all threads?

The run() method should be implemented by all threads.

 

 

 

  1. What are synchronized methods and synchronized statements?

A synchronized method of an object cannot be invoked by a thread when another thread is using that method. It means a synchronized method can be used by only one thread at a time. To make a method synchronized we just use the keyword ‘synchronized’ before the method declaration.

Eg:

            synchronized void print()

{

}

A synchronized statement is used to specify that some code (of a method) should be used by one thread only at a time.

            void someMethod()

{

                        synchronized(obj)

{

}

}

  1. What are the two basic ways in which classes that can be run as threads may be defined? .
  • By extending Thread
  • By implementing Runnable

 

 

 

  1. What is the difference between an if statement and a switch statement?

‘if’ can be used to work with variables, constants, integers, real numbers, equality comparisions, range comparisions, etc and there is no limitation it them.

‘switch’ is good for equality comparison of an expression with different integer constants only. (from java1.7 onwards, String is also allowed). It means there are some limitations in switch statement.

A simple if-else statement is used to select one out of two possibilities and a simple if statement is used to decide whether a particular block of statements should be executed  or not. A nested if-else constructor can be used to select one out of multiple possibilities.

Generally a switch statement is used to select one out of multiple possibilities. If break is not used between cases, we can select multiple possibilities also with switch.

 

 

  1. What happens when you add a double value to a String?

The double value is also converted to String, and a String concatenation operation would result.

 

  1. What do you mean by platform independence?

Here, platform is used to refer the ‘Operating System’. So ‘platform independence’ means, ‘irrespective of operating system’.

We generally say that java is platform independent language because a java compiled file (byte code) can be executed on a machine with any platform (operating system).

 

 

  1. What is the difference between a JDK and a JVM?

JDK refers the environment/package with the support of what we write and compile the program.

JVM is a layer on Operating System that makes all java related activites done on our machine.

 

  1. What is difference between Path and Classpath?

Path is specified to let the system know where the java executables like ‘java’, ‘javac’, ‘javap’, etc are existing.

Classpath is specified to let the system know where the other packages (and in turn classes) required for our program are existing.

 

  1. Can a class be declared as protected?

An inner class can be declared as protected.

But a top level class is not declared as protected.

 

  1. What is the purpose of declaring a variable as final?

When a variable is declared as ‘final’, value of that variable cannot be changed in course of the program. Just its initial value can be used when required.

 

 

 

  1. How is final different from finally and finalize()?

‘final’ is used to give a final meaning/value to a variable, method or a class. Its meaning/value cannot be changed in course of the program.

‘finally’ is used at try-catch mechanism to execute a block of code irrespective of an exception is raised or not.

‘finalize()’ is used to execute a block of code when a object is garbage collected.

 

 

  1. Can a class be defined inside an Interface?

YES, we can define a class inside an Interface.

Eg:

            interface Hello

            {

                        class One

                        {

                                    void one(){System.out.println(“hi”);}

                        }

            }

            class Check

            {

                        public static void main(String[] args) throws Exception

                        {

                                    Hello h;

                                    Hello.One ho;

                                    ho = new Hello.One();

                                    ho.one();

                        }

            }          

  1. What is an exception?

An exception is an object created by the system when a runtime error occur.

  1. What is error?

We have different types of errors like compilation error (or syntactical error), logical error, throwable error, etc. The mistake made by the programmer that violates the rules of the language is known as compilation or syntactical error. The mistake made by the programmer that results in wrong outputs is known as the logical error. The mistakes occur due to ‘out of memory’, ‘assertion not satisfied’, ‘improper class format’, etc are known as throwable errors.

  1. Which is superclass of Exception?

‘Throwable’ is the super class of Exception.

 

  1. What are the advantages of using exception handling?

It allows the programmer to concentrate on the actual logic first so that the problems can be handled somewhere else.

It allows the program not to be terminated abnormally when a runtime error occur.

It allows the programming team (development team) to record the problems in a sophisticated way.

It allows the program to run smoothly from user point of view.

 

 

  1. Can class be declared as Private.?

An inner class can be declared as private. A top-level (outer class) is not declared as private.

 

  1. What is the argument type of a program’s main() method?

“String[]” is the argument type of main() method. It is the formal argument used to receive the command line arguments.

 

  1. . If a method is declared as protected, where may the method be accessed?
  • Anywhere from the current package
  • From subclasses of other packages.

 

 

  1. What is the return type of a program’s main() method?

“void” is the return type of program’s main() method.

 

  1. . What class of exceptions are generated by the Java run-time system?

The unchecked exceptions ( Error, RuntimeException and their child classes) are thrown by the runtime system.

Infact, all exceptions are thrown by the runtime system only but unchecked exceptions come into action only at runtime where as checked exceptions are validated at compilation stage also.

  1. How are this() and super() used with constructors?

this() is used to call constructor of same class and super() is used to call constructor of parent class.

 

 

 

  1. . Describe what happens when an object is created in Java..???

First memory is allocated and then constructor is invoked.

  1. What is The Mother of All Classes..????

“Object” is the mother of all classes.

  1. What does the this reference refer to…..??????

The “this” reference refers the current object in a method.

 

  1. What is the difference between a static variable and an instance variable…????

The “static” variable is created only once and it can be accessed by any object. we can have only one copy of static variable. so modifying it through any object will be effective for other objects also. The static variable can be accessed using its class name also. So the static variable can be used without any object also.

An instance variable is created whenever a new object is created. If we create N objects then we can have N number of copies of the instance variable. Modifying instance variable of one object will have no effect on other objects. Memory is not at all allocated for the instance variables if objects are not allocated.

 

  1. When a Java program is running, what happens if the expression evaluated for a switch statement does not match any of the case values associated with the statement…..????

Then, the “default” part is executed.

 

  1. What is the difference between a conditional operator and a conditional statement………?????

The ?: is known as conditional operator. It is used in the following way…

Syntax:            expression ? truepart : falsepart;

A statement that works depending on a condition is known as conditional statement. Generally the if statement is known as conditional statement. Similarly the statement formed using the conditional operator is also known as conditional statement.

  1. Does break have to be used in each section of statements that follow a case..????

NO, it is not required. If we want the control to come out of the switch construction after executing a case block, then a break is required. If we don’t want to come out of the switch and continue executing the next case also then we can skip the break statement at end of a case.

 

  1. Why do you sometimes use single-quotation marks after a case statement and sometimes leave them off…..?????

When we want to compare the switch expression with different character constants then each such character constant is placed inside the single quotation marks.

Eg:

            case ‘A’: //some stuff

case ‘B’: //some other stuff

case ‘5’: //some more stuff

when we are comparing integer constants with the switch expression then the numbers are not placed in quotations.

Eg:

case 34: //some stuff

case 5: //some other stuff

 

  1. What is java EmptyStatement..????

A statement that does not perform any activity is known as empty statement. Just a semicolon will serve the purpose.

Eg1:

            for(a=1; a<=b; a++)

                        Somestuff;

 

Eg2:

            for( ; a<=b; a++)

                        ;

In the above two examples we can find some differences. The initialization part of the for loop in the first example has a=1 and the initialization part of the for loop in the second example has an empty statement. Similarly the body of first for loop has some stuff where as body of for loop in second example has empty statement.

 

  1. What’s the difference between the Integer object and the int variable type?

An integer variable is created like

            int a=5;

an Integer object is created like

            Integer a = new Integer(5);

Practically there is not much difference between int variable and Integer object. an Integer object is created based on the class Integer. The Integer class holds an int value and wraps it as a class. This is why Integer (and Character, Double, etc are ) is known as wrapper class.

Where ever an int value can be used we can use an Integer object also.

But at some locations (like collections), int values are not allowed to be stored. In that case we should use Integer objects only.

The system automatically converts int value as Integer object (which is known as Boxing) and an Integer object as an int value (which is known as UnBoxing).

x

Check Also

Java Program To Calculate Discount Of Product | Programs

Java program to calculate discount of a product. With the help of the following program, ...