0% found this document useful (0 votes)
113 views24 pages

Java Fundamentals: An Example or Single Occurrence of Something

The document discusses Java fundamentals including classes, objects, arrays, packages, and abstract data types (ADTs). It provides answers to 16 multiple choice questions covering these topics as well as definitions and explanations. Key topics covered include the difference between classes and objects, array declarations and usage, package declarations, and the definition of an abstract data type.

Uploaded by

arjoghosh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
113 views24 pages

Java Fundamentals: An Example or Single Occurrence of Something

The document discusses Java fundamentals including classes, objects, arrays, packages, and abstract data types (ADTs). It provides answers to 16 multiple choice questions covering these topics as well as definitions and explanations. Key topics covered include the difference between classes and objects, array declarations and usage, package declarations, and the definition of an abstract data type.

Uploaded by

arjoghosh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 24

JAVA FUNDAMENTALS

1. State whether the following statement is true or false.


Class is an instance of an object
Answer: FALSE
/*
An object is an instance of a class.
Instance: an example or single occurrence of something
*/

2. int values [] = {1,2,3,4,5,6,7,8};
for (int i=0;i<X;++i)
System.out.println(values[i]);
Referring to the above, what value for X will print all members
of array values?
Answer: 8
(Because of ++i)
3. What is the correct ordering for the import, class and package
declarations found in a single file?
Answer: package, import, class
4. What will be the result of compiling the following code?
public class Test {
public static void main (String args[])
{
int age;
age=age+1;
System.out.println(The age is+age);
}
}


Answer: Doesnt compile.

/*

C:\Users\Dell\SkyDrive\Documents\Test.java:4: error: variable
age might not have been initialized
age=age+1;
^
1 error

Tool completed with exit code 1

*/

5. What is the legal range of a byte integral type?
Answer:

-128 to 127

6. Which of the following returns true?
Answer:
john==john & join.equals(join)
/*
if("join"=="join")
{
System.out.println("TRUE");
}
if("john".equals("john"))
{
System.out.println("TRUE");
}
OUTPUT :
TRUE
TRUE

*/
7. Which of the following do not lead to runtime error?
Answer: NONE
8. Which code declares class A to belong to the
mypackage.financial package?
Answer: package mypackage.financial;
9. A package is a collection of
Answer: classes + interfaces
10. Which of the following statements is valid array
declaration?
Answer: float average[]
11. What is the output of this code fragment?
int x=3; int y=10;
System.out.println(y%x);
Answer: 1
12. Which three form part of correct array declarations?
Answer:
public int a []
static int []a
public final int []a
13. Which causes a compiler error?
Answer: int [][] scores = {2,7,6},{9,3,45};
/*
C:\Users\Dell\SkyDrive\Documents\Test.java:12: error:
<identifier> expected
int [][] scores = {2,7,6},{9,3,45};
^
C:\Users\Dell\SkyDrive\Documents\Test.java:12: error: not a
statement
int [][] scores = {2,7,6},{9,3,45};
^
C:\Users\Dell\SkyDrive\Documents\Test.java:12: error: ';'
expected
int [][] scores = {2,7,6},{9,3,45};
^
C:\Users\Dell\SkyDrive\Documents\Test.java:14: error: class,
interface, or enum expected
}
^
4 errors
Tool completed with exit code 1
*/
14. Which two cause a compiler error?
Answer:
float []f= new float(3);
float f2[]=new float[];
/*
C:\Users\Dell\SkyDrive\Documents\Test.java:4: error: '['
expected
float []f= new float(3);
^
C:\Users\Dell\SkyDrive\Documents\Test.java:4: error: ']'
expected
float []f= new float(3);
^
C:\Users\Dell\SkyDrive\Documents\Test.java:5: error: array
dimension missing
float f2[]=new float[];
^
3 errors

Tool completed with exit code 1
*/
15. What will be the output of the following Java code:
a) byte x = 64, y;
y=(byte)(x<<2);
System.out.println(y);

b) String s;
System.out.println(S= + s);
c) String S = new String();
System.out.println(S=+S);
d) Class Number
{
int x;
void store (Number num)
{
num.x++;
}
}
Class MainNumber
{
public static void main (String
args[]) {
Number n = new Number();
n.x=10;
n.store(n);
System.out.println(n.x);
}
}
Answer:
a) 0
b) /*
C:\Users\Dell\SkyDrive\Documents\Test.java:5: error:
variable s might not have been initialized
System.out.println("S=" + s);
^
1 error

Tool completed with exit code 1
*/
c) S=
d)11

16. Define ADT
Answer:
In computer science, an abstract data type (ADT) is a mathematical model for a certain class of data
structures that have similar behavior; or for certain data types of one or more programming
languages that have similar semantics. An abstract data type is defined indirectly, only by the
operations that may be performed on it and by mathematical constraints on the effects (and
possibly cost) of those operations.
"Abstract data type" -- often abbreviated ADT -- is basically an old-fashioned term for "class". If you
know what a Java class is -- especially if you understand it as some data plus some operations on
that data -- then you understand what an ADT is.
1. public abstract class MyAbstractClass
2. {
3. //code
4. public abstract void method();
5. }


When used with a class, it does NOT allow any instantiations of it. It means you will not be
able to create any object for the above class "MyAbstractClass". This is used when you are
not sure about the implementation of the class and the class only gets its real meaning when
its extended by some other class.

Absract methods are not given any body. They are only declared.
Note: I have used a semicolon after the method signature.

The body for the method is defined by any class that extends its class.

Here's an example:
1. public abstract class Animal
2. {
3. abstract void walk();
4. }
5.
6. public class Dog extends Animal
7. {
8. void walk()
9. {
10. //Implementation is done here
11. }
12. }


You really don't know what an Animal object looks like. Does it have four legs or four horns.
There is no definite meaning for it. So you NEED to subclass it to give it a proper shape such
as a Dog.
Different Animals have different styles of walking, so we just declare an abstract method for
walk() and leave it to the sub-classes to implement a specific style for its class.

Now, there are many rules associated with the "abstract" keyword which you can learn once
you understand this concept.
17. Java doesnt support destructor. Discuss.
Answer:
The purpose of a Destructor is usually to clear off unused variables and clean up the memory. Java
has in built memory handling mechanisms (Garbage collection) that clear off unused memory
automatically. Hence there is no requirement for destructor methods.

Tip: In spite of automatic garbage collection by java, it is a good practice to nullify all unused objects
in the finally block of the code.
18. Explain public static void main(String args[]) in brief.
Answer:
In Java, the execution starts from main() method. But for compilation, main() is not required.
Java's main() method syntax is quiet different from C/C++.
Following is the main() method signature
public static void main(String args[])
Every word in the above statement has got a meaning to the JVM.
1. public: It is a keyword and denotes that any other class (JVM) can call the main() method
without any restrictions.
2. static: It is a keyword and denotes that any other class (JVM) can call the main() method
without the help of an object.
3. void: It is a keyword and denotes that the main() method does not return a value.
4. main(): It is the name of the method.
5. String args[]: The parameter is a String array by name args. The string array is used to
access command-line arguments.
The Java program under execution takes some context area (execution area) in the RAM.
JVM is in another context area. To call the main(), the JVM requires an object. When the
JVM has not entered into the program, how it can create an object or get an object. To
overcome this, allow the JVM to access the main() without object just by declaring static.
Once the JVM enters, it can create hundreds of objects later.
Whether you pass right now command-line arguments or not, you must have the string
array as parameter as it is the part of syntax.
19. What is JVM? Explain function of JVM in brief. What do you
mean by JVM? What do you mean by Java is a platform independent
language?
Answer:
Java Virtual Machine (JVM)
Quite possibly, the most important part of the JRE is the Java Virtual Machine (JVM). The
JVM acts like a virtual processor, enabling Java applications to be run on the local system. Its
main purpose is to interpret (read translate) the received byte-code and make it appear as
native code. The older Java architecture used this process of interpretation to execute Java
byte-code. Even though the process of interpretation brought the WORA principle to diverse
machines, it had a drawback it consumed a lot of time and clocked the system processor
intensively to load an application.

Figure 2: A JVM interpreter translates the byte-code line-by-line to make it appear as if a native
application is being executed.
The idea of Java is to compile the source code into an intermediate language that will be interpreted.


The source code The intermediate file The interpretor
The intermediate language is the byte code. The interpretor is the Java Virtual Machine
(JVM). The byte code file is universal and the JVM is platform specific:





So a JVM should be coded for each platform. And that's the case. So you just have to
generate a unique byte code file (a .class file).
The first implementations of the language used an interpreted virtual machine to achieve
portability, and many implementations still do. These implementations produce programs that
run more slowly than the fully-compiled programs created by the typical C++ compiler, so
the language suffered a reputation for producing slow programs. Since Java 1.2, Java VM
produces programs that run much faster, using multiple techniques.
The first of these is to simply compile directly into native code like a more traditional
compiler, skipping bytecode entirely. This achieves great performance, but at the expense of
portability. This is not really used any more.
Another technique, the just-in-time (JIT) compiler, compiles the Java bytecode into native
code at the time the program is run, and keep the compiled code to be used again and again.
More sophisticated VMs even use dynamic recompilation, in which the VM can analyze the
behavior of the running program and selectively recompile and optimize critical parts of the
program. Both of these techniques allow the program to take advantage of the speed of native
code without losing portability.
Portability is a technically difficult goal to achieve, and Java's success at that goal is a matter
of some controversy. Although it is indeed possible to write programs for the Java platform
that behave consistently across many host platforms, the large number of available platforms
with small errors or inconsistencies led some to parody Sun's "Write once, run anywhere"
slogan as "Write once, debug everywhere".
One of the major features of java includes that why java is called platform independent
language.
Before understanding this feature we need to know about -

Javac compiler that converts source code to byte code.
JVM- interpreter that converts byte code to machine language code.
As we know java is both compiler & interpreter based language. Once the java code also
known as source code is compiled, it gets converted to native code known as BYTE CODE
which is portable & can be easily executed on all operating systems. Byte code generated is
basically represented in hexa decimal format. This format is same on every platform be it
Solaris work station or Macintosh, windows or Linux. After compilation, the interpreter reads
the generated byte code & translates it according to the host machine. . Byte code is
interpreted by Java Virtual Machine which is available with all the operating systems we
install. so to port Java programs to a new platform all that is required is to port the interpreter
and some of the library routines.
Source code -> javac ->Universal byte code
Universal byte ->jvm/java -> execute them on a particular machine.
Another reason the makes Java a Platform independent language is the elimination of
undefined or architecture dependent constructs.
Therefore java is called platform independent language.
20. What is byte code? What does the JVM do? Why Java is called
compiler-interpreter language?
Answer:
Java bytecode is the instruction set of the Java virtual machine. Each bytecode is composed by one,
or in some cases two, bytes that represent the instruction (opcode), along with zero or more bytes
for passing parameters.
Java is compiled to an intermediate "byte code" at compilation time. This is in contrast to a
language like C that is compiled to machine language at compilation time. The Java byte
code cannot be directly executed on hardware the way that compiled C code can. Instead the
byte code must be interpreted by the JVM (Java Virtual Machine) at runtime in order to be
executed. The primary drawback of a language like C is that when it is compiled, that binary
file will only work on one particular architecture (e.g. x86).
Interpreted languages like PHP are effectively system independent and rely on a system and
architecture specific interpreter. This leads to much greater portability (the same PHP scripts
work on Windows machines and Linux machines, etc.). However, this interpretation leads to
a significant performance decrease. High-level languages like PHP require more time to
interpret than machine-specific instructions that can be executed by the hardware.
Java seeks to find a compromise between a purely compiled language (with no portability)
and a purely interpreted language (that is significantly slower). It accomplishes this by
compiling the code into a form that is closer to machine language (actually, Java byte code is
a machine language, simply for the Java Virtual Machine), but can still be easily transported
between architectures. Because Java still requires a software layer for execution (the JVM) it
is an interpreted language. However, the interpreter (the JVM) operates on an intermediate
form known as byte code rather than on the raw source files. This byte code is generated at
compile time by the Java compiler. Therefore, Java is also a compiled language. By operating
this way, Java gets some of the benefits of compiled languages, while also getting some of
the benefits of interpreted languages. However, it also inherits some limitations from both of
these languages.
As Bozho points out, there are some strategies for increasing the performance of Java code
(and other byte code languages like .Net) through the use of Just in Time (JIT) compilation.
The actual process varies from implementation to implementation based on the requirements,
but the end-result is that the original code is compiled into byte code at compile time, but
then it is run through a compiler at runtime before it is executed. By doing this, the code can
be executed at near-native speeds. Some platforms (I believe .Net does this) saves the result
of the JIT compilation, replacing the byte code. By doing this, all future executions of the
program will execute as though the program was natively compiled from the beginning.
21. What might be the difference in functionality between a machine
with only JDK installed and another machine with only JRE installed?
Answer:
The Java platform is the name given to the computing platform from Oracle that helps users
to run and develop Java applications. The platform does not just enable a user to run and
develop a Java application, but also features a wide variety of tools that can help developers
work efficiently with the Java programming language.
The platform consists of two essential softwares:
the Java Runtime Environment (JRE), which is needed to run Java applications and
applets; and,
the Java Development Kit (JDK), which is needed to develop those Java
applications and applets. If you have installed the JDK, you should know that it comes
equipped with a JRE as well. So, for all the purposes of this book, you would only
require the JDK.
22. Explain the use of finally, final and finalize keywords in Java.
Discuss differences between final and finally.
Answer:
final:
final is a keyword. The variable decleared as final should be
initialized only once and cannot be changed. Java classes
declared as final cannot be extended. Methods declared as final
cannot be overridden.

finally:
finally is a block. The finally block always executes when the
try block exits. This ensures that the finally block is executed
even if an unexpected exception occurs. But finally is useful for
more than just exception handling - it allows the programmer to
avoid having cleanup code accidentally bypassed by a return,
continue, or break. Putting cleanup code in a finally block is
always a good practice, even when no exceptions are anticipated.

finalize:
finalize is a method. Before an object is garbage collected, the
runtime system calls its finalize() method. You can write system
resources release code in finalize() method before getting garbage
collected.
23. Write down a program to implement Command Line arguments.
Answer:
In this example, we are receiving only one argument and printing it. To run this java program, you
must pass at least one argument from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }

1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo

24. Discuss the garbage collection procedure in Java.
Answer:
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically.
Advantage of Garbage Collection:
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
It is automatically done by the garbage collector so we don't need to make extra efforts.

How can an object be unreferenced?
There are many ways:
By nulling the reference
By assigning a reference to another
By annonymous object etc.
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
2) By assigning a reference to another:
1. Employee e1=new Employee();
2. Employee e2=new Employee();
3.
4. e1=e2;//now the first object referred by e1 is available for garbage collection
3) By annonymous object:
1. new Employee();

finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This method can
be used to perform cleanup processing. This method is defined in System class as:
1. protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to
perform cleanup processing (destroying remaining objects).

gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.
1. public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage
Collector(GC). This thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection:
1. public class TestGarbage1{
2.
3. public void finalize(){System.out.println("object is garbage collected");}
4.
5. public static void main(String args[]){
6. TestGarbage1 s1=new TestGarbage1();
7. TestGarbage1 s2=new TestGarbage1();
8. s1=null;
9. s2=null;
10. System.gc();
11. }
12. }
25. Explain the following methods of the java.lang.String class work.
i) equals
ii) startsWith
iii) substring
Answer:
Equals
Description:
This method compares this string to the specified object. The result is true if and only if the
argument is not null and is a String object that represents the same sequence of characters as
this object.
Syntax:
Here is the syntax of this method:
public boolean equals(Object anObject)
Parameters:
Here is the detail of parameters:
anObject -- the object to compare this String against.
Return Value :
This method returns true if the String are equal; false otherwise.
Example:
public class Test {

public static void main(String args[]) {
String Str1 = new String("This is really not immutable!!");
String Str2 = Str1;
String Str3 = new String("This is really not immutable!!");
boolean retVal;

retVal = Str1.equals( Str2 );
System.out.println("Returned Value = " + retVal );

retVal = Str1.equals( Str3 );
System.out.println("Returned Value = " + retVal );
}
}
This produces the following result:
Returned Value = true
Returned Value = true

startsWith
Description:
This method has two variants and tests if a string starts with the specified prefix beginning a
specified index or by default at the beginning.
Syntax:
Here is the syntax of this method:
public boolean startsWith(String prefix, int toffset)

or

public boolean startsWith(String prefix)
Parameters:
Here is the detail of parameters:
prefix -- the prefix to be matched.
toffset -- where to begin looking in the string.
Return Value:
It returns true if the character sequence represented by the argument is a prefix of the
character sequence represented by this string; false otherwise.
Example:
import java.io.*;

public class Test{
public static void main(String args[]){
String Str = new String("Welcome to Tutorialspoint.com");

System.out.print("Return Value :" );
System.out.println(Str.startsWith("Welcome") );

System.out.print("Return Value :" );
System.out.println(Str.startsWith("Tutorials") );

System.out.print("Return Value :" );
System.out.println(Str.startsWith("Tutorials", 11) );
}
}
This produces the following result:
Return Value :true
Return Value :false
Return Value :true

substring
Description:
This method has two variants and returns a new string that is a substring of this string. The
substring begins with the character at the specified index and extends to the end of this string
or up to endIndex - 1 if second argument is given.
Syntax:
Here is the syntax of this method:
public String substring(int beginIndex)

or

public String substring(int beginIndex, int endIndex)
Parameters:
Here is the detail of parameters:
beginIndex -- the begin index, inclusive.
endIndex -- the end index, exclusive.
Return Value:
The specified substring.
Example:
import java.io.*;

public class Test{
public static void main(String args[]){
String Str = new String("Welcome to Tutorialspoint.com");

System.out.print("Return Value :" );
System.out.println(Str.substring(10) );

System.out.print("Return Value :" );
System.out.println(Str.substring(10, 15) );
}
}
This produces the following result:
Return Value : Tutorialspoint.com
Return Value : Tuto

26. Why do we need the import statement in Java program?
Answer:
An import statement is a way of making more of the functionality of Java available to your program.
Java can do a lot of things, and not every program needs to do everything. So, to cut things down to
size, so to speak, Java has its classes divided into "packages." Your own classes are part of packages,
too.

No import Needed

The simple Hello.java program we've used as an example so far doesn't have any import statements:

public class Hello{
public static void main(String arg[]){
System.out.println("Hello.");
}
}

Everything in the program is already available to the compiler. The compiler can access any class in
the java.lang package without needing an import statement. It can also access any classes in the
"local" package, which is any classes defined in files in the same directory as the program being
compiled that aren't part of another package (that is, they don't have a package statement at the
start of the file.)

import Required

Anything that isn't in the java.lang package or the local package needs to be imported. An
example is the Scanner class. If you look up the Scanner class in the Java API Specification, you'll
see that it is in the java.util package. Remember, to look it up you scroll to the class name in
the lower left frame then click on it to bring up its definition in the main frame of the browser. Class
names are in regular typeface, interfaces are in italics (some classes and interfaces have the same
name.)

Here's an example program that uses Scanner, with an import statement:

import java.util.Scanner;

public class ScannerTest{
public static void main(String arg[]){

// scanner gets its input from the console.
Scanner scanner = new Scanner(System.in);
String name = "";

// Get the user's name.
System.out.print("Your name, adventurer? >");
name = scanner.next();
System.out.println();

// Print their name in a a message.
System.out.println("Welcome, " + name + " to Javaland!");
}
}

We imported just the class Scanner from java.util in the import statement in this program. If we'd
been using multiple classes from java.util, we could have made all the classes in java.util available to
us by using this import statement:

import java.util.*;

The * is a "regular expression operator" that will match any combination of characters. Therefore,
this import statement will import everything in java.util. If you have tried entering and running the
example program above, you can change the import statement to this one.

If we need multiple classes from different packages, we use an import statement for each package
from which we need to import classes (or interfaces, or any other part of that package we need.) It's
not unusual to see a series of import statements near the start of a program file:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

Now, you may wonder why we have statements importing java.awt.* and
java.awt.event.*. It seems like if you import java.awt.* that ought to import everything
"under" java.awt, right? And the "dot" notation sure makes it look like java.awt.event is
under java.awt.

27. Why java is called a purely object oriented language? What is
byte code and how it helps the portability of Java Programming
language? Why java is a strongly typed language?
Answer:
Because you can't code anything in Java without declaring classes and objects. Even the small "Hello
World" declares a class: class HelloWorldApp { public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string. } }
There are lot of arguments around whether Java is purely object oriented or not. According to
me, Java is now a purely object oriented language as it has wrapper classes. So you can use
Integer, Float etc. instead of int, float etc. (there are a total of eight primitive types).
But since Java has those eight primitive types, the critics will say Java is not purely object-
oriented.
Java bytecode is the instruction set of the Java virtual machine.
Programming code that, once compiled, is run through a virtual machine instead of the computers
processor. By using this approach, source code can be run on any platform once it has been
compiled and run through the virtual machine.
Bytecode is the compiled format for Java programs. Once a Java program has
been converted to bytecode, it can be transferred across a network and
executed by Java Virtual Machine (JVM). Bytecode files generally have a .class
extension.
The key that allows Java to solve both the security and the portability problems
is that the output of a Java compiler is not executable code. Rather, it is
bytecode. Bytecode is a set of instructions designed to be executed by the Java
run-time system known as Java Virtual Machine (JVM). That is, in its standard
form, the JVM is an interpreter for bytecode.

Translating a Java program into bytecode helps makes it easier to run a program
in a wide variety of environments. The reason is straightforward: only the JVM
needs to be implemented for each platform. Once the run-time package exists
for a given system, any Java program can run on it. Although the details of JVM
will differ from platform to platform, all interpret the same Java bytecode.

A strongly typed programming languages is one that requires the type of a variable to be explicitly
stated. C is a strongly typed language. You must declare the type of data a variable will store for C to
interpret it: int myVariable;

myVariable = 25; Perl is a loosely typed language. There is no need to declare the variable type
before using it: $myVariable = 25;
$myVariable = "A String.";
28. WAP to implement a dynamic stack. Each stack is constructed
with an initial length. If this length is exceeded, i.e., if more room is
needed then the size of the stack is doubled.

Answer
First, here is the interface that defines an integer stack. Put this in a file called
IntStack.java. This interface will be used by both stack implementations.

// Define an integer stack interface.
interface IntStack {
void push(int item); // store an item
int pop(); // retrieve an item
}



Following is another implementation of IntStack that creates a dynamic stack by use
of the same interface definition. In this implementation, each stack is constructed
with an initial length. If this initial length is exceeded, then the stack is increased in
size. Each time more room is needed, the size of the stack is doubled.

// Implement a "growable" stack.
class DynStack implements IntStack {
private int stck[];
private int tos;
// allocate and initialize stack
DynStack(int size) {
stck = new int[size];
tos = -1;
}
// Push an item onto the stack
public void push(int item) {
// if stack is full, allocate a larger stack
if(tos==stck.length-1) {
int temp[] = new int[stck.length * 2]; // double size
for(int i=0; i<stck.length; i++) temp[i] = stck[i];
stck = temp;
stck[++tos] = item;
}
else
stck[++tos] = item;
}
// Pop an item from the stack
public int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class IFTest2 {
public static void main(String args[]) {
DynStack mystack1 = new DynStack(5);
DynStack mystack2 = new DynStack(8);
// these loops cause each stack to grow
for(int i=0; i<12; i++) mystack1.push(i);
for(int i=0; i<20; i++) mystack2.push(i);
System.out.println("Stack in mystack1:");
for(int i=0; i<12; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<20; i++)
System.out.println(mystack2.pop());
}
}

29. Discuss the role of the following methods in java:
(a) public void join () throws InterruptedException
(b) getDocumentBase()
(c) getCodeBase()
(d) String int length()
(e) Boolean equals (String str)
Answer
(a) The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.
Certain methods cannot be executed by the JVM alone. JVM takes the help of the
underlying operating system to do the job. Such methods are known as native
methods. For example, for all the file operations and thread operations, the JVM
should communicate with the operating system and with the operating system
cooperation, the task intended will be achieved. File management and thread
management etc. are managed entirely by the OS. Any language should communicate
and take the help of OS.
Any problem in the communication (known as communication gap) and any
programmer's task is not done successfully, the JVM informs through an exception
and especially as a checked exception. The name of the checked exception is included
in the method signature or constructor signature. Some checked exceptions with
constructor signatures are given hereunder.
One example of checked exception is InterruptedException very often used in thread
operations. Many thread methods throw InterruptedException. Observe the following
two method signatures of Thread class.
public static native void sleep(long) throws
java.lang.InterruptedException; // a method
public final void join() throws java.lang.InterruptedException; //
a method

Both the methods sleep() and join() throw a checked exception InterruptedException.
While using these methods, these methods must be placed in try-catch blocks; else
program does not compile.
(b+c) The getCodebase() method is also commonly used to establish a path to
other files or folders that are in the same location as the class being run.
URL getCodeBase()
Gets the base URL.
URL getDocumentBase()
Gets the URL of the document in which the applet is embedded.
(d) This method returns the length of this string. The length is equal to the number of 16-bit
Unicode characters in the string.
Here is the syntax of this method:
public int length()

(e) Description
The java.lang.Boolean.equals(Object obj) returns true if and only if the argument is not null
and is a Boolean object that represents the same boolean value as this object.
Declaration
Following is the declaration for java.lang.Boolean.equals() method
public boolean equals(Object obj)
Overrides
equals in class Object
Parameters
obj - the object to compare with
Return Value
This method returns true if the Boolean objects represent the same value, false otherwise.
30. Write short note on Templates.
Answer:
Templates are a feature of the C++ programming language that allow functions and classes
to operate with generic types. This allows a function or class to work on many different data
types without being rewritten for each one.
Templates are of great utility to programmers in C++, especially when combined with
multiple inheritance and operator overloading. The C++ Standard Library provides many
useful functions within a framework of connected templates.

You might also like