20

JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who
Page 2: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 2

CHAPTER – 1JAVA

1. List the features of Java language. (or) Mention the features of JAVA.

The key considerations were summed up by the Java team in the following list ofbuzzwords:

Simple Secure Portable Object oriented Robust Multithreaded Architecture neutral Interpreted High performance Distributed Dynamic

2. Define bytecode.

The key that allows Java to solve both the security and the portability problems is thatthe output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is ahighly optimized set of instructions designed to be executed by the Java run-time system,which is called the Java Virtual Machine (JVM).

3. What is Java virtual machine? (or) Define Java Virtual Machine. (or) What is theneed for Java virtual machine?

The key that allows Java to solve both the security and the portability problems is thatthe output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is ahighly optimized set of instructions designed to be executed by the Java run-time system,which is called the Java Virtual Machine (JVM).

4. What is difference between JDK, JRE and JVM?

Java Development Kit (JDK): The software for programmers who want to write Javaprograms

Java Runtime Environment (JRE): The software for consumers who want to run Javaprograms

Java Virtual Machine (JVM): Bytecode is a highly optimized set of instructionsdesigned to be executed by the Java run-time system, which is called the Java VirtualMachine (JVM).

Page 3: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 3

5. Mention some of the separators used in Java programming.

Symbol Name Purpose( ) Parentheses Used to contain lists of parameters in method

definition and invocation. Also used for definingprecedence in expressions, containing expressions incontrol statements, and surrounding cast types.

{ } Braces Used to contain the values of automaticallyinitialized arrays. Also used to define a block ofcode, for classes, methods, and local scopes.

[ ] Brackets Used to declare array types. Also used whendereferencing array values.

; Semicolon Terminates statements., Comma Separates consecutive identifiers in a variable

declaration. Also used to chain statements togetherinside a for statement.

. Period Used to separate package names from subpackagesand classes. Also used to separate a variable ormethod from a reference variable.

6. How dynamic initialization of variables is achieved in java?

Java allows variables to be initialized dynamically, using any expression valid at thetime the variable is declared.

For example, here is a short program that computes the length of the hypotenuse of aright triangle given the lengths of its two opposing sides:

// Demonstrate dynamic initialization.class DynInit {

public static void main(String args[]) {double a = 3.0, b = 4.0;// c is dynamically initializeddouble c = Math.sqrt(a * a + b * b);System.out.println("Hypotenuse is " + c);

}}Here, three local variables - a, b, and c - are declared. The first two, a and b, are

initialized by constants. However, c is initialized dynamically to the length of the hypotenuse(using the Pythagorean theorem). The program uses another of Java’s built-in methods, sqrt( ),which is a member of the Math class, to compute the square root of its argument. The keypoint here is that the initialization expression may use any element valid at the time of theinitialization, including calls to methods, other variables, or literals.

Page 4: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 4

7. Define Objects and classes in java. (or) Define class. (or) Define the term class. (or)Define Objects and Classes. (or) What do you mean by instance variables? (or)Define objects and object variable.

A class defines a new data type. Once defined, this new type can be used to createobjects of that type. Thus, a class is a template for an object, and an object is an instance of aclass.

A class is declared by use of the class keyword. The general form of a class definitionis shown here:

class classname {type instance-variable1;type instance-variable2;// ...type instance-variableN;type methodname1(parameter-list) {

// body of method}type methodname2(parameter-list) {

// body of method}// ...type methodnameN(parameter-list) {

// body of method}

}

The new operator dynamically allocates memory for an object. It has this generalform:

class-var = new classname();

Here, class-var is a variable of the class type being created. The classname is the nameof the class that is being instantiated.

8. Why does Java not support destructors and how does the finalize method help ingarbage collection?

Sometimes an object will need to perform some action when it is destroyed. Forexample, if an object is holding some non-Java resource such as a file handle or windowcharacter font, then you might want to make sure these resources are freed before an object isdestroyed. To handle such situations, Java provides a mechanism called finalization. By usingfinalization, you can define specific actions that will occur when an object is just about to bereclaimed by the garbage collector.

Page 5: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 5

9. Mention the purpose of finalize method. (or) What is the purpose of finalization? (or)What is finalize method? (or) Define finalize method.

To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class. Inside thefinalize( ) method you will specify those actions that must be performed before an object isdestroyed. The garbage collector runs periodically, checking for objects that are no longerreferenced by any running state or indirectly through other referenced objects. Right before anasset is freed, the Java run time calls the finalize( ) method on the object.

The finalize( ) method has this general form:

protected void finalize( ){

// finalization code here}

Here, the keyword protected is a specifier that prevents access to finalize( ) by codedefined outside its class.

10. Define constructor. (or) What is a Constructor? Give an example. (or) What are thefunctions of a constructor?

A constructor initializes an object immediately upon creation. It has the same name asthe class in which it resides and is syntactically similar to a method. Once defined, theconstructor is automatically called immediately after the object is created, before the newoperator completes.

class Box {double width;double height;double depth;// This is the constructor for Box.Box() {

System.out.println("Constructing Box");width = 10;height = 10;depth = 10;

}// compute and return volumedouble volume() {

return width * height * depth;}

}

11. What is the difference between a constructor and a method?

A constructor initializes an object immediately upon creation. It has the same name asthe class in which it resides and is syntactically similar to a method. Once defined, theconstructor is automatically called immediately after the object is created, before the newoperator completes.

Page 6: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 6

A method is an ordinary member function of a class. It has its own name, a return type(which may be void), and is invoked using the dot operator.

12. What is a default constructor?

A default constructor is a constructor with no parameters. For example, here is adefault constructor for the Employee class:

Box() {width = height = depth = -1;

}

If you write a class with no constructors whatsoever, then a default constructor isprovide for you. This default constructor sets all the instance fields to their default values. So,all numeric data contained in the instance fields would be 0, all boolean values would be false,and all object variables would be set to null.

13. What is meant by parameter passing constructors? Give example.

A parameterized constructor is a constructor that can take arguments.

For example, the following version of Box defines a parameterized constructor whichsets the dimensions of a box as specified by those parameters.

// This is the constructor for Box.Box(double w, double h, double d) {

width = w;height = h;depth = d;

}. . .Box mybox1 = new Box(10, 20, 15);

14. Distinguish between method overriding and method overloading in Java. (or) Whatis method overriding in Java? (or) What is Overriding and how it is different fromOverloading? (or) Differentiate method overloading and method overriding.

Method Overloading Method OverridingTwo or more methods within the same classthat share the same name, as long as theirparameter declarations are different.

In a class hierarchy, when a method in asubclass has the same name and typesignature as a method in its superclass, thenthe method in the subclass is said to overridethe method in the superclass.

Parameter must be different and name mustbe same.

Both name and parameter must be same.

Compile time polymorphism. Runtime polymorphism.Increase readability of code. Increase reusability of code.

Page 7: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 7

15. What is the use of this keyword?

Sometimes a method will need to refer to the object that invoked it. To allow this, Javadefines the this keyword. this can be used inside any method to refer to the current object.That is, this is always a reference to the object on which the method was invoked.

For example, here is a version of Box( ), which uses width, height, and depth forparameter names and then uses this to access the instance variables by the same name:

// Use this to resolve name-space collisions.Box(double width, double height, double depth) {

this.width = width;this.height = height;this.depth = depth;

}

16. What is the purpose of ‘final’ keyword? (or) What is the use of final keyword? (or)How to define a constant variable in Java?

A variable can be declared as final. Doing so prevents its contents from beingmodified. This means that you must initialize a final variable when it is declared. Forexample:

final int FILE_OPEN = 2;

Subsequent parts of your program can now use FILE_OPEN, etc., as if they wereconstants, without fear that a value has been changed. It is a common coding convention tochoose all uppercase identifiers for final variables. Variables declared as final do not occupymemory on a per-instance basis. Thus, a final variable is essentially a constant.

17. Write a declaration to convert the value ‘‘Programmer’’ in the string variable‘convert’ to ‘‘Programming’’.

convert = convert.substring(0, 8) + "ing";

18. What is the difference between the String and StringBuffer classes? (or) What is astring buffer class and how does it differs from string class?

String StringBufferString class is immutable. StringBuffer class is mutable.String is slow and consumes more memorywhen you concat too many strings becauseevery time it creates new instance.

StringBuffer is fast and consumes lessmemory when you concat strings.

String class overrides the equals() method ofObject class. So you can compare thecontents of two strings by equals() method.

StringBuffer class doesn't override theequals() method of Object class.

Page 8: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 8

19. List any four methods available in string handling.

The String class contains several methods that you can use. You can test two stringsfor equality by using equals( ). You can obtain the length of a string by calling the length( )method. You can obtain the character at a specified index within a string by calling charAt( ).The general forms of these three methods are shown here:

boolean equals(String object)int length( )char charAt(int index)

20. List out the type of Arrays.

One-dimensional array Multidimensional arrays

21. How to create one dimensional array? (or) How will you declare an array?

A one-dimensional array is, essentially, a list of like-typed variables. To create anarray, you first must create an array variable of the desired type. The general form of a one-dimensional array declaration is

type var-name[]; (or) type[] var-name;

Here, type declares the base type of the array. The base type determines the data typeof each element that comprises the array. Thus, the base type for the array determines whattype of data the array will hold.

For example, the following declares an array named month_days with the type “arrayof int”:

int month_days[];

22. What is meant by Anonymous Array?

Anonymous arrays in Java is an Array without any name, just like Anonymous innerclasses and policy of using Anonymous array is just create, initialize and use it, since itdoesn't have any name you can not reuse it.

Anonymous array follows same syntax like normal array in Java e.g. new [] { }; , onlydifference is that after creating Anonymous array we don't store it on any reference variable.here is few examples of creating anonymous array in java:

anonymous int array : new int[] {1, 2, 3, 4};anonymous String array : new String[] {"one", "two", "three"};anonymous char array : new char[] {'a', 'b', 'c');

23. What is static in java?

There will be times when you will want to define a class member that will be usedindependently of any object of that class. Normally a class member must be accessed only in

Page 9: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 9

conjunction with an object of its class. However, it is possible to create a member that can beused by itself, without reference to a specific instance. To create such a member, precede itsdeclaration with the keyword static. When a member is declared static, it can be accessedbefore any objects of its class are created, and without reference to any object. You candeclare both methods and variables to be static.

24. Why main method is static?

The most common example of a static member is main( ). main( ) is declared as staticbecause it must be called before any objects exist.

25. What is the difference between static and nonstatic variables?

If you define a field as static, then there is only one such field per class. In contrast,each object has its own copy of all instance fields. For example, let’s suppose we want toassign a unique identification number to each employee. We add an instance field id and astatic field nextId to the Employee class:

class Employee{

...private int id;private static int nextId = 1;

}

Every employee object now has its own id field, but there is only one nextId field thatis shared among all instances of the class.

26. Enumerate two situations in which static methods are used. (or) What are thecharacteristics of static methods?

Methods declared as static have several restrictions:

They can only call other static methods. They must only access static data. They cannot refer to this or super in any way.

27. What is static variable?

Instance variables declared as static are, essentially, global variables. When objects ofits class are declared, no copy of a static variable is made. Instead, all instances of the classshare the same static variable.

28. Define static inner classes.

A static nested class is one which has the static modifier applied. Because it is static, itmust access the members of its enclosing class through an object. That is, it cannot refer tomembers of its enclosing class directly. Because of this restriction, static nested classes areseldom used.

Page 10: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 10

29. Define non-static inner classes.

An inner class is a non-static nested class. It has access to all of the variables andmethods of its outer class and may refer to them directly in the same way that other non-staticmembers of the outer class do. Thus, an inner class is fully within the scope of its enclosingclass.30. What is an anonymous inner class?

When using local inner classes, you can often go a step further. If you want to makeonly a single object of this class, you don’t even need to give the class a name. Such a class iscalled an anonymous inner class.

31. State the difference between inner class and anonymous class?

An inner class is a class that is defined inside another class. There are three reasons:

Inner class methods can access the data from the scope in which they are defined -including data that would otherwise be private.

Inner classes can be hidden from other classes in the same package. Anonymous inner classes are handy when you want to define callbacks without

writing a lot of code.

32. Define Inheritance.

Using inheritance, you can create a general class that defines traits common to a set ofrelated items. This class can then be inherited by other, more specific classes, each addingthose things that are unique to it. In the terminology of Java, a class that is inherited is called asuperclass. The class that does the inheriting is called a subclass. Therefore, a subclass is aspecialized version of a superclass. It inherits all of the instance variables and methodsdefined by the superclass and adds its own, unique elements.

The general form of a class declaration that inherits a superclass is shown here:

class subclass-name extends superclass-name {// body of class

}

33. What is the use of ‘super’ keyword?

super has two general forms. The first calls the superclass’ constructor. The second isused to access a member of the superclass that has been hidden by a member of a subclass.

Using super to Call Superclass Constructors: A subclass can call a constructor methoddefined by its superclass by use of the following form of super:

super(parameter-list);

Here, parameter-list specifies any parameters needed by the constructor in thesuperclass. super( ) must always be the first statement executed inside a subclass’ constructor.

Page 11: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 11

A Second Use for super: The second form of super acts somewhat like this, except thatit always refers to the superclass of the subclass in which it is used. This usage has thefollowing general form:

super.member

Here, member can be either a method or an instance variable.

This second form of super is most applicable to situations in which member names ofa subclass hide members by the same name in the superclass.

34. What is an abstract class? (or) What is an abstract class? Give its syntax.

You can require that certain methods be overridden by subclasses by specifying theabstract type modifier. These methods are sometimes referred to as subclasser responsibilitybecause they have no implementation specified in the superclass. Thus, a subclass mustoverride them-it cannot simply use the version defined in the superclass. To declare anabstract method, use this general form:

abstract type name(parameter-list);

As you can see, no method body is present.

35. What are the conditions to be satisfied while declaring abstract classes? (or) Give theproperties of abstract classes and methods and write a suitable example. (or) What isthe significance of an abstract class?

Any class that contains one or more abstract methods must also be declared abstract.To declare a class abstract, you simply use the abstract keyword in front of the class keywordat the beginning of the class declaration. There can be no objects of an abstract class. That is,an abstract class cannot be directly instantiated with the new operator. Such objects would beuseless, because an abstract class is not fully defined. Also, you cannot declare abstractconstructors, or abstract static methods. Any subclass of an abstract class must eitherimplement all of the abstract methods in the superclass, or be itself declared abstract.

36. Can an abstract class in Java be instantiated? Give reason.

There can be no objects of an abstract class. That is, an abstract class cannot bedirectly instantiated with the new operator. Such objects would be useless, because an abstractclass is not fully defined.

37. What is dynamic binding?

Java resolves calls to methods dynamically, at run time. This is called late binding.However, since final methods cannot be overridden, a call to one can be resolved at compiletime. This is called early binding.

38. Distinguish between static and dynamic binding. (or) What is dynamic binding? (or)Differentiate: Static and Dynamic Binding. (or) Write the difference between staticand dynamic binding in Java.

Page 12: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 12

Java resolves calls to methods dynamically, at run time. This is called late binding.However, since final methods cannot be overridden, a call to one can be resolved at compiletime. This is called early binding.

39. What is the use of final keyword? (or) What is the purpose of ‘final’ keyword? (or)Mention the purpose of the keyword ‘final’.

The keyword final has three uses. First, it can be used to create the equivalent of anamed constant. This use was described in the preceding chapter. The other two uses of finalapply to inheritance.

Using final to Prevent Overriding: While method overriding is one of Java’s mostpowerful features, there will be times when you will want to prevent it from occurring. Todisallow a method from being overridden, specify final as a modifier at the start of itsdeclaration. Methods declared as final cannot be overridden. The following fragmentillustrates final:

class A {final void meth() {

System.out.println("This is a final method.");}

}class B extends A {

void meth() { // ERROR! Can't override.System.out.println("Illegal!");

}}

Using final to Prevent Inheritance: Sometimes you will want to prevent a class frombeing inherited. To do this, precede the class declaration with final. Declaring a class as finalimplicitly declares all of its methods as final, too. As you might expect, it is illegal to declarea class as both abstract and final since an abstract class is incomplete by itself and relies uponits subclasses to provide complete implementations.

Here is an example of a final class:

final class A {// ...

}

// The following class is illegal.class B extends A { // ERROR! Can't subclass A

// ...}

As the comments imply, it is illegal for B to inherit A since A is declared as final.

Page 13: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 13

40. Can an abstract class be final? Why?

It is illegal to declare a class as both abstract and final since an abstract class isincomplete by itself and relies upon its subclasses to provide complete implementations.

41. Mention the necessity for import statements.

Java includes the import statement to bring certain classes, or entire packages, intovisibility. Once imported, a class can be referred to directly, using only its name. The importstatement is a convenience to the programmer and is not technically needed to write acomplete Java program. If you are going to refer to a few dozen classes in your application,however, the import statement will save a lot of typing.

42. How does one import a single package?

You can import a specific class or the whole package. You place import statements atthe top of your source files (but below any package statements). For example, you can importall classes in the java.util package with the statement:

import java.util.*;

Then you can use

Date today = new Date();

without a package prefix. You can also import a specific class inside a package:

import java.util.Date;

The java.util.* syntax is less tedious. It has no negative effect on code size. However,if you import classes explicitly, the reader of your code knows exactly which classes you use.

43. What are different types of access modifiers (Access specifiers)?

The four access modifiers in Java that control visibility:

1. Visible to the class only (private).2. Visible to the world (public).3. Visible to the package and all subclasses (protected).4. Visible to the package-the (unfortunate) default. No modifiers are needed.

Private No modifier Protected PublicSame class Yes Yes Yes YesSame package subclass No Yes Yes YesSame package no-subclass No Yes Yes YesDifferent package subclass No No Yes YesDifferent package non-subclass

No No No Yes

Table: Class Member Access

Page 14: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 14

44. What is the scope of method which is declared as protected.

When a method is declared as protected, code contained in its defining class, allclasses in the package in which the class that defines the method belongs to, and all subclassesof that class (regardless of package) can call the method.

45. Can Java directly support multiple inheritance?

If a child class inherits the property from multiple classes is known as multipleinheritance.

Java does not allow to extend multiple classes but to overcome this problem it allowsto implement multiple Interfaces.

46. Why is multiple inheritance using classes a disadvantage in Java?

Multiple inheritance is the ability of a single class to inherit from multiple classes.Java does not have this capability. The designers of Java considered multiple inheritance to betoo complex, and not in line with the goal of keeping Java simple.

One specific problem that Java avoids by not having multiple inheritances is called thediamond problem.

47. In java what is the use of Interfaces? (or) What is Interface? (or) What is interfaceand mention its use. (or) Define Interface and write the syntax of the Interface. (or)Write down the syntax for defining interface.

Through the use of the interface keyword, Java allows you to fully abstract theinterface from its implementation. Using interface, you can specify a set of methods whichcan be implemented by one or more classes. The interface, itself, does not actually define anyimplementation. Although they are similar to abstract classes, interface have an additionalcapability: A class can implement more than one interface.

An interface is defined much like a class. This is the general form of an interface:

access interface name {return-type method-name1(parameter-list);return-type method-name2(parameter-list);type final-varname1 = value;type final-varname2 = value;// ...return-type method-nameN(parameter-list);type final-varnameN = value;

}

Page 15: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 15

48. Write down the syntax for implementing interface.

Once an interface has been defined, one or more classes can implement that interface.To implement an interface, include the implements clause in a class definition, and then createthe methods defined by the interface. The general form of a class that includes the implementsclause looks like this:

access class classname [extends superclass][implements interface [,interface...]] {

// class-body}

Here, access is either public or not used. If a class implements more than one interface,the interfaces are separated with a comma. The methods that implement an interface must bedeclared public. Also, the type signature of the implementing method must match exactly thetype signature specified in the interface definition.

49. How interface can be extended?

One interface can inherit another by use of the keyword extends. The syntax is thesame as for inheriting classes. When a class implements an interface that inherits anotherinterface, it must provide implementations for all methods defined within the interfaceinheritance chain.

50. What is an exception?

An exception is an abnormal condition that arises in a code sequence at run time. Inother words, an exception is a run-time error. In computer languages that do not supportexception handling, errors must be checked and handled manually-typically through the use oferror codes, and so on. This approach is as cumbersome as it is troublesome. Java’s exceptionhandling avoids these problems and, in the process, brings run-time error management into theobject-oriented world.

51. What happens if an exception is not caught?

Any exception that is not caught by your program will ultimately be processed by thedefault handler. The default handler displays a string describing the exception, prints a stacktrace from the point at which the exception occurred, and terminates the program.

52. What is the difference between throw and throws in Java?

throw throwsJava throw keyword is used to explicitlythrow an exception.

Java throws keyword is used to declare anexception.

Checked exception cannot be propagatedusing throw only.

Checked exception can be propagated withthrows.

throw is followed by an instance. throws is followed by class.throw is used within the method. throws is used with the method signature.You cannot throw multiple exceptions. You can declare multiple exceptions.

Page 16: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 16

53. What are Stack Trace Elements?

A stack trace is a listing of all pending method calls at a particular point in theexecution of a program. You have almost certainly seen stack trace listings - they aredisplayed whenever a Java program terminates with an uncaught exception.

The StackTraceElement class has methods to obtain the file name and line number, aswell as the class and method name, of the executing line of code. The toString method yields aformatted string containing all of this information.

Page 17: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 17

54. Give any two methods available in Stack trace Element.

String getFileName() - gets the name of the source file containing the execution pointof this element, or null if the information is not available.

int getLineNumber() - gets the line number of the source file containing the executionpoint of this element, or –1 if the information is not available.

String getClassName() - gets the fully qualified name of the class containing theexecution point of this element.

String getMethodName() - gets the name of the method containing the execution pointof this element. The name of a constructor is <init>. The name of a static initializer is<clinit>. You can’t distinguish between overloaded methods with the same name.

boolean isNativeMethod() - returns true if the execution point of this element is insidea native method.

String toString() - returns a formatted string containing the class and method name andthe file name and line number, if available.

55. What are threads? (or) What do you mean by Threads in Java? (or) What ismultithreading? (or) What is thread? (or) What is the need for threads? (or) Definemultithreaded programming.

A multithreaded program contains two or more parts that can run concurrently. Eachpart of such a program is called a thread, and each thread defines a separate path of execution.Thus, multithreading is a specialized form of multitasking.

56. What are the different states in thread? (or) What is Thread State?

A thread can exist in a number of different states. You can obtain the current state of athread by calling the getState( ) method defined by Thread. It is shown here:

Thread.State getState( )

It returns a value of type Thread.State that indicates the state of the thread at the timeat which the call was made. State is an enumeration defined by Thread. Here are the valuesthat can be returned by getState( ):

Page 18: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 18

Fig. Thread States

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

When the thread tries to acquire an intrinsic object lock (but not a Lock in thejava.util.concurrent library) that is currently held by another thread, it becomesblocked.

When the thread waits for another thread to notify the scheduler of a condition, itenters the waiting state.

Several methods have a timeout parameter. Calling them causes the thread to enterthe timed waiting state. This state persists either until the timeout expired or theappropriate notification has been received.

58. What all constructors are present in the Thread class? (or) Name any four threadconstructor.

public Thread();public (Runnable);public Thread(ThreadGroup, Runnable);public Thread(String);

Page 19: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 19

public Thread(ThreadGroup, String);public Thread(Runnable, String);public Thread(ThreadGroup, Runnable, String);public Thread(ThreadGroup, Runnable, String, long);

59. What are the two ways for creating a Thread?

By implementing the runnable interface:class Newthread implements Runnable

By Extending the Thread classclass Newthread extends Thread

60. Why do we need run() and start() methods both? Can we achieve it with only runmethod.

We need run() & start() method both because JVM needs to create a separate threadwhich can not be differentiated from a normal method call. So this job is done by start methodnative implementation which has to be explicitly called. Another advantage of having thesetwo methods is we can have any object run as a thread if it implements Runnable interface.This is to avoid Java’s multiple inheritance problems which will make it difficult to inheritanother class with Thread.

61. What happens if a start method is not invoked and the run method is directlyinvoked?

If a thread has been instantiated but not started it is said to be in new state. Unless untila start() method is invoked on the instance of the thread, it will not said to be alive. If you donot call a start() method on the newly created thread instance thread is not considered to bealive. If the start() method is not invoked and the run() method is directly called on the Threadinstance, the code inside the run() method will not run in a separate new thread but it will startrunning in the existing thread.

62. What do you mean Synchronization? (or) Write notes on synchronization. (or) Whatis synchronization?

When two or more threads need access to a shared resource, they need some way toensure that the resource will be used by only one thread at a time. The process by which this isachieved is called synchronization.

63. Compare final, finally and finalize.

final finally finalizefinal is used to applyrestrictions on class, methodand variable. Final class can'tbe inherited, final methodcan't be overridden and finalvariable value can't bechanged.

finally is used to placeimportant code, it will beexecuted whether exceptionis handled or not.

finalize is used to performclean up processing justbefore object is garbagecollected.

final is a keyword. finally is a block. finalize is a method.

Page 20: JAVA - reccsec.weebly.com...Java Development Kit (JDK): The software for programmers who want to write Java programs Java Runtime Environment (JRE): The software for consumers who

B.BHUVANESWARAN / AP (SS) / CSE / REC - 20