0 ratings 0% found this document useful (0 votes) 27 views 58 pages Question Bank JAVA
The document is a question bank for Unit 1 covering various concepts of Java, including the Java Virtual Machine (JVM), class file format, sandbox model, bytecode, characteristics of Java, differences between Java and C++, access specifiers, security promises, and static blocks. It explains the architecture of JVM, the role of bytecode, and the security model designed to protect users from untrusted code. Additionally, it discusses Java's features, including its platform independence and object-oriented nature.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Question Bank JAVA For Later Question Bank - Unit 1
Q1 What do you mean by JAVA VIRTUAL MACHINE? Draw and explain
the architecture of JVM.
Sol 4) JVM(Java Virtual Machine) acts as a run-time engine to run Java
applications. JVM is the one that actually calls the main method present in
ajava code. JVM is a part of JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This
means a programmer can develop Java code on one system and can
expect it to run on any other Java-enabled system without any adjustment.
This is all possible because of JVM. This makes Java Platform
independent
When we compile a java file, .class files(contains byte-code) with the same
class names present in java file are generated by the Java compiler.
This .class file goes into various steps when we run it. These steps
together describe the whole JVM
The architecture of JVM contains class loader , memory area, execution
engine, etc.
Class Loader
mory
VM Langu: PC rrr
sos
JVM Language
Classes
Execution Native Method Native Method
Engine Interface ui
1) Classloader
Classloader is a subsystem of JVM which is used to load class files.
Whenever we run the java program, it is loaded first by the classloader.
There are three built-in classloaders in Java:+ Bootstrap ClassLoader
+ Extension ClassLoader
+ System/Application ClassLoader
Avery popular exception of ClassNotFoundException is caused by Java
class loader.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime
constant pool, field and method data, the code for methods.
3) Heap
It is the runtime data area in which objects are allocated.
4) Stack
Java Stack stores frames. It holds local variables and partial results, and
plays a part in method invocation and return. Each thread has a private
JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is
destroyed when its method invocation completes.
5) Program Counter Register
PC (program counter) register contains the address of the Java virtual
machine instruction currently being executed
6) Native Method Stack
It contains all the native methods used in the application
7) Execution Engine
It contains:
+ Avirtual processor
+ Interpreter: Read bytecode stream then execute the
instructions.
+ Just-In-Time(JIT) compiler: It is used to improve
the performance. JIT compiles parts of the byte code that have
similar
functionality at the same time, and hence reduces the amount of time
needed for compilation.
8) Java Native InterfaceJava Native Interface (JNI) is a framework which provides an interface to
communicate with another application written in another language like C,
Ct,
Assembly etc. Java uses JNI framework to send output to the Console or
interact with OS libraries.
Q2 Explain Java class file format.
Sol 2) A Java class file is a file containing Java bytecode and having a
.class extension that can be executed by JVM. A Java class file is created
by a Java compiler from java files as a result of successful compilation. As
we know
that a single Java programming language source file (or we can say java
file) may contain one class or more than one class. So if a java file has
more than one class then each class will compile into a separate class file.
Java applications are called WORA (Write Once Run Anywhere). This
means a programmer can develop Java code on one system and can
expect it to run on any other Java-enabled system without any adjustment.
This is all possible because of JVM. This makes Java Platform independent
For example:
class Sample
{
class Student
{
class Test
public static void main(String[] args)
System. out.printin(‘Class File Structure’);
3
j
After compilation there will be 3 class files in corresponding folder named
as:
Sample.classStudent.class
Test.class
Q3 What is java sandbox model?
Sol 3)
The original security model! provided by the Java platform is known as
the sandbox model, which existed in order to provide a very restricted
environment in which to run untrusted code obtained from the open
network.
The essence of the sandbox model is that local code is trusted to have
full access to vital system resources (such as the file system) while
downloaded remote code (an applet) is not trusted and can access only
the limited resources provided inside the sandbox.
Ina Java programming language, the sandbox is the program area and
it has some set of rules that programmers need to fallow when creating
Java code (like an applet) that is sent as part of a page
Since a Java applet is sent automatically as part of the page and can be
executed as soon as it arrives, the applet can easily do harm, either
accidentally or intentionally.
The sandbox restrictions provide strict limitations on which system
resources the applet can request or access. The sandbox can be
conceived as a small area within your computer where an applet’s code
can play freely — but it’s not allowed to play anywhere else. Sandboxing
is frequently used to test unverified programs that may contain a virus or
other malicious code, without allowing the software to harm the host
device.
The Java sandbox relies on a three-tiered defense. If any of these three
elements fails the security model is completely compromised and
vulnerable to attack:
Byte Code verifier
Applet class loader
Security manager
Q4 What is byte code?
Sol 4) Bytecode is nothing but the intermediate representation of Java
source code which is produced by the Java compiler by compiling that
source code. This byte code is a machine independent code. It is not a
completely compiled code but it is an intermediate code somewhere in the
middle which is later interpreted and executed by JVM. Bytecode is amachine code for JVM. But the machine code is platform specific whereas
bytecode is platform independent that is the main difference between them.
It is stored in a class file which is created after compiling the source code.
Q5 Define the characteristics of Java.
[GGSIPU PREVIOUS YEAR ]
Sol 5) Characteristics of java: There are many features of java. They are
also known as java buzzwords. The Java Features given below are simple
and easy to understand
Simple
Object-Oriented
Platform independent
Secured
Robust
Portable
Dynamic
SP NOAR ODN =
Interpreted
9, Multithreaded
10. Distributed
Simple:
Java is Easy to write and more readable and eye-catching.
Java has a concise, cohesive set of features that makes it easy to learn
and use.
Most of the concepts are drawn from C++ thus making Java learning
simpler.
Object-oriented:
Object-oriented means we organize our software as a combination of
different types of objects that incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies
software development and maintenance by providing some rules.Object Oriented Programming Language must have the following
characteristics
(1) Encapsulation
(2) Polymorphism
(3) Inheritance
(4) Abstraction
Platform-independent:
Java Language is platform-independent due to its hardware and software
environment. Java code can be run on multiple platforms e.g. windows,
Linux, Mac/QOs etc. Java code is compiled by the compiler and converted
into byte code. This byte code is a platform independent code because it
can be run on multiple platforms i.e. Write Once and Run Anywhere
(WORA).
Secure
+ Java programs cannot harm other systems thus making it secure.
+ Java provides a secure means of creating Internet applications.
+ Java provides a secure way to access web applications.
Java is secured because:
+ No explicit pointer
» Programs run inside virtual machine sandbox.
Robust:
Java was created as a strongly typed language. Data type issues and
problems are resolved at compile-time, and implicit casts of a variable from
one type to another are not allowed. Memory management has been
simplified in java in two ways. First, Java does not support direct pointer
manipulation or arithmetic. This makes it possible for a java program to
overwrite memory or corrupt data
Java encourages error-free programming by being strictly typed and
performing run-time checks.
Portable
The feature of java ‘write once-run anywhere’ makes java portable. Many
types of computers and operating systems are used for programs. By
porting an interpreter for the Java Virtual Machine to any computer
hardware/operating system, one is assured that all code compiled for it will
run on that system. This forms the basis for Java's portability.Dynamic
Because itis interpreted, Java is an extremely dynamic language. At
runtime, the java environment can extend itself by linking in classes that
may be located on remote servers on a network(for example, the internet).
At runtime, the java interpreter performs name resolution while linking in
the necessary classes.
Interpreted:
Java supports cross-platform code through the use of Java bytecode.
Bytecode can be interpreted on any platform by JVM.
Multi-threaded: A thread is like a separate program, executing
concurrently. We can write Java programs that deal with many tasks at
once by defining multiple threads. The main advantage of multi-threading is
that it shares the same memory. Threads are important for multimedia,
Web applications etc
Distributed: Java facilitates the building of distributed application by a
collection of classes for use in networked applications. By using java's URL
(Uniform Resource Locator) class, an application can easily access a
remote server. Classes also are provided for establishing socket-level
connections.
QS Differentiate between Java and C++ Object Oriented Language.
[GGSIPU PREVIOUS YEAR ]
Sol 6)
Java C++Java was developed by
James Gosling at Sun
Microsystems.
C++ was developed by
Bjarne Stroustrup at Bell Labs in
1979 as an extension of the C
language.
Platform independent,
Java bytecode works on any
joperating system.
Platform dependent,
should be compiled for different
platforms.
lt can run in any OS
hence it is portable.
Ctt is
platform-dependent. Hence it is not
portable.
Java is both Compiled and
Interpreted Language.
C++ is a Compiled
Language.
Memory Management is
System Controlled.
Memory Management in
C++ is Manual.
It doesn't have Virtual
Keyword.
It has Virtual Keyword.
lt supports only single
inheritance. Multiple inheritances are|
lachieved partially using interfaces.
It supports both single
and multiple Inheritance.It supports only method
joverloading and doesn't allow
loperator overloading.
It supports both method
and operator overloading.
It has limited support
for pointers.
It strongly supports
pointers.
Java provides built-in
[support for multithreading.
Java is only an
jobject-oriented programming
language.
C++ doesn't have
built-in support for threads, depends
on third-party threading libraries.
C++ is both a procedural
and an object-oriented
programming language.
Java uses the (System
class): System.in for input and
\System.out for output.
Java doesn’t support goto Keyword,
global
scope, Structures and Unions
C++ uses cin for input and cout for
an output operation.
C++ supports goto keyword,
global scope, Structures
and Unions
C++ also supports namespace
scope.Java supports only the C++ supports both Pass by
Pass by Value and call by value. Value, pass by reference, and , call
technique. by value and call by reference.
(Automatic object It supports manual object
management with garbage management using new and delete.
|collection.
Q7 What are access specifiers and explain access scope of a
protected method?
[GGSIPU PREVIOUS YEAR ]
Sol 7) Access Specifiers In Java: Java Access Specifiers (also known as
Visibility Specifiers) regulate access to classes, fields and methods in Java.
These Specifiers determine whether a field or method in a class can be
used or invoked by another method in another class or subclass. Access
Specifiers can be used to restrict access
Types Of Access Specifiers:
In java we have four Access Specifiers and they are listed below.
1. Public
2. Private
3. Protected
4. Default(no specifier)
‘cones Modifiers Default private protected pubic
ee ee
‘Acceamile inside the dass ~ eye
‘Accessible within the subcamy you mo yun
inside the mame package
‘Acoousible outside the packages = 00m mye
‘Acoeasible within the subelns nono yu
‘uteide the package
Public Specifiers: Public Specifiers achieve the highest level of
accessibility. Classes, methods, and fields declared as public can be
accessed from any class in the Java program, whether these classes are in
the same package or in another package.Example:
public class Demo { // public class
public x, y, size; // public instance variables
}
Private specifiers: Private Specifiers achieves the lowest level of
accessibility. private methods and fields can only be accessed within the
same class to which the methods and fields belong. private methods and
fields are not visible within subclasses and are not inherited by subclasses.
Example:
public class Demo { //public class
private double x, y; // private (encapsulated) instance variables
public set(int x, int y) {// setting values of private fields
this.x = x;
this.y = y;
}
public get() { // setting values of private fields
return Point(x, y);
}
}
Protected specifiers: Methods and fields declared as protected can only be
accessed by the subclasses in other packages or any class within the
package of the protected members' class. The protected access specifier
cannot be applied to class and interfaces.
Default(no specifier): When you don't set access specifier for the element, it
will follow the default accessibility level. There is no default specifier
keyword. Classes, variables, and methods can be default accessed. Using
the default specifier we can access class, method, or field which belongs to
the same package, but not from outside this package.
Q8 Write a short note on Security Promises of Java.
Sol 8) Java's security model is focused on protecting users from hostile
programs downloaded from untrusted sources across a network. To
accomplish this goal, Java provides a customizable 'sandbox' in which Javaprograms run. A Java program must play only inside its sandbox. It can do
anything within the boundaries of its sandbox, but it can't take any action
outside those boundaries. The sandbox for untrusted Java applets, for
example, prohibits many activities, including:
* Reading or writing to the local disk
* Making a network connection to any host, except the host from which
the applet came
* Creating anew process
* Loading a new dynamic library and directly calling a native method
By making it impossible for downloaded code to perform certain actions,
Java's security model protects the user from the threat of hostile code.
The language defines all primitives with a specific size and all operations.
are defined to be in a specific order of execution. Thus, the code executed
in different JVMs will not differ from the specified order of execution.
The language provides access-control functionality on variables and
methods in the object by defining namespace management for type and
procedure names. This secures the program by restricting access to its
critical objects from untrusted code. For example, access is restricted by
qualifying the type members as public, protected, private, package, etc.
The Java language does not allow defining or dereferencing pointers,
which means that programmers cannot forge a pointer to the memory or
create code defining offset points to memory. All references to methods and
instance variables in the class file are done via symbolic names. The
elimination of pointers helps to prevent malicious programs like computer
viruses and misuse of pointers such as accessing private methods directly
by using a pointer starting from the object's pointer, or running off the end
of an array.
The Java object encapsulation supports ‘programming by contract,’ which
allows the reuse of code that has already been tested.
The Java language is a strongly typed language. During compile time, the
Java compiler does extensive type checking for type mismatches. This
mechanism guarantees that the runtime data type variables are compatible
and consistent with the compile time information.
The language allows declaring classes or methods as final. Any classes or
methods that are declared as final cannot be overridden. This helps to
protect the code from malicious attacks such as creating a subclass and
substituting it for the original class and override methods.The Java Garbage Collection mechanism contributes to secure Java
programs by providing a transparent storage allocation and recovering
unused memory instead of deallocating the memory using manual
intervention. This ensures program integrity during execution and prevents.
programmatic access to accidental and incorrect freeing of memory
resulting ina JVM crash
Q9 If we want to execute any statement before the call of the main()
method then how will it be done?
Sol 9) It will be executed in a static block.
Java supports a special block, called a static block that can be used for
static initialization of a class. This code inside the static block is executed
only once: the first time the class is loaded into memory.
Static block is executed when the class which contains the static block is
loaded into memory and static method is executed when it is called.
Q10 How Garbage Collection in Java works? Explain sandbox model
in detail and JVM as an Emulator. Comment on it.
[GGSIPU PREVIOUS YEAR ]
Sol 10) In Java, garbage means unreferenced objects. Garbage Collection
is the process of reclaiming the runtime unused memory automatically. In
other words, it is a way to destroy unused objects. To do so, we were using
the free() function in C language and delete() in C++. But, in Java it is
performed automatically. So, Java provides better memory management.
Advantage of Garbage Collection
It makes Java memory efficient because the garbage collector removes the
unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.
ge() method
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The ge() is found in System and Runtime classes.
public static void ge()f}.
Sandbox model in java.Asecurity measure in the Java development environment. The sandbox is
a set of rules that are used when creating an applet that prevents certain
functions when the applet is sent as part of a Web page. When a browser
requests a Web page with applets, they are sent automatically and can be
executed as soon as the page arrives in the browser. If the applet is
allowed unlimited access to memory and operating system resources, it
can do harm in the hands of someone with malicious intent. The sandbox
environment in which there are strict limitations on what system resources
the applet can request or access. Sandboxes are used when executable
code comes from an unknown or untrusted source and allow the user to
run untrusted code safely.
The Java sandbox relies on a three-tiered defense. If any one of these
three elements fails, the security model is completely compromised and
vulnerable to attack:
+ Byte code verifier-This is one way that Java automatically checks
untrusted outside code before it is allowed to run. When a Java
source program is compiled, it compiles down to platform-
independent Java byte code, which is verified before it can run. This
helps to establish a base set of security guarantees.
+ Applet class loader - All Java objects belong to classes, and the
applet class loader determines when and how an applet can add
classes to a running Java environment. The applet class loader
ensures that important elements of the Java run-time environment
are not replaced by code that an applet tries to install.
+ Security manager-The security manager is consulted by code in the
Java library whenever a dangerous operation is about to be carried
out. The security manager has the option to veto the operation by
generating a security exception.
Java typically interpret instead of compile. The main advantage of
compilation is that you end up with raw machine language code that can be
efficiently executed on your machine. However, it can only be executed on
‘one type of machine architecture . A primary advantage of a compiling to an
intermediate language like Java bytecode and then interpreting is that you
can achieve platform independence: you can interpret the same class file
‘on differently types of machine architectures. However, interpreting the
bytecode is typically slower than executing pre-compiled machine language
code. A second advantage of using the Java bytecode is that it acts as a
buffer between your computer and the program. This enables you to
download an untrusted program from the Internet and execute it on your
machine with some assurances. Since you are running the Java interpreter
(and not raw machine language code), you are protected by a layer ofsecurity which guards against malicious programs. It is the combination of
Java and the Java bytecode that yield a platform-independent and secure
environment, while still embracing a full set of modern programming
abstractions
Q11 What are different sandbox models in java ?
Sol 11) Java Built-in Security Model
With the JDK 1.0 sandbox security model, all Java applications (excluding
Java applets) executed locally can have full access to the resources
available to the JVM. Application code downloaded from remote resources,
such as Java applets, will have access only to the restricted resources
provided within its sandbox
Java 2 Security Model
Java 2 security architecture is as follows:
+ Policy-driven restricted access control to JVM resources.
» Rules-based class loading and verification of byte code.
* System for signing code and assigning levels of capability.
+ Policy-driven access to Java applets downloaded by a Web browser.
All code-regardless of whether it is run locally or downloaded remotely-can
be subjected to a security policy configured by a JVM user or administrator.
All code is configured to use a particular domain (equivalent to a sandbox)
and a security policy that dictates whether the code can be run ona
particular domain or not.
Q12 (a) Why is java called a strongly typed language?
Sol 12 a) Java is a strongly typed programming language because every
variable must be declared with a data type. A variable cannot start off life
without knowing the range of values it can hold, and once it is declared, the
data type of the variable cannot change.
Example:
The following declaration is allowed because the variable 'hasDataType' is
declared to be a boolean data type:
boolean hasDataType;
For the rest of its life, hasDataType can only ever have a value of true or
false(b) Can the main() method in java return any data 7?
Sol 12 b) The main method consists of public static as modifiers, void
return type and String arguments. If anything is changed, JVM doesn't
consider it as the entry point method and prompts an error at run time.
Therefore, you cannot change the return type of main method from void, at
the same time you cannot return any value from a method with void type.
Q13 Discuss the limitations of JVM.
[GGSIPU PREVIOUS YEAR ]
Sol 13) Java Virtual Machine has notable advantages, it comes with many
disadvantages also.
41. Platform specific features: Java cannot be used without Java Runtime
Environment being installed on your system. So in order to start coding in
Java, firstly you need to install the latest version of Java Virtual Machine
Because of JVM running on several Operating Systems, there is a
possibility that JVM does not have a feature that is specific to that particular
operating system. Therefore, there can be any feature that does not look
the same way as it did on some other operating system.
2. Speed: In a Java Virtual Machine, the code is first converted into
bytecode and then the bytecode is converted into the machine code for the
system to finally run it.
Therefore, this is the reason why the Java Virtual Machine tends to work
slower and hence making a Java code run slower when compared to its
equivalent C or C++ code. The compilation to bytecode that helps the code
to run on any platform eventually turns out to be a disadvantage when
performance is concerned.
3. Java bytecode is system neutral and optimization of the same according
to any specific hardware set is not possible. The reason behind this is that
for a code to get optimize system specific features are the necessity and
since the bytecode is system neutral it is not possible to optimize it.
4. A Java code is completely dependent on the Java Virtual Machine which
makes it platform dependent and itself is platform dependent. Thus, before
proceeding towards Java development one should have the basic idea of
what a Java Virtual Machine is.Q14 Explain the concepts of class area and heap in JVM.
Sol 14)
Heap
In Java, a heap is a chunk of memory which is shared among all threads. In
a heap, all class instances and the array is allocated. It is created when
JVM starts-up. An automatic storage management system reclaims heap. It
may be of fixed and variable size. It does not need to be contiguous.
The heap is divided into two parts (or generations):
* Young Generation (or Young Space or Nursery)
+ Old Generation (or Old Space or Tenured)
Class Area
JVM has a method area common across all the threads. It contains per-
class elements like constant pool, fields, method local data, method code,
constructor codes etc. which are used in class and initialization of
objects/interfaces.
This method area gets created during JVM start-up. It is generally part of
Heap area. It could be of fixed size or vary. Its memory may not be
contiguous. JVM implementation can give control to programmer over
Method area creation, its sizing etc. If method area memory is not
sufficient to satisfy an allocation request then JVM _ throws
OutOfMemoryError.
Q15 Is JVM an Interpreter or Emulator or both? Discuss.
[GGSIPU PREVIOUS YEAR ]
Sol 15) The Java processor can be implemented as software. It is implemented as
a program that reads the bytecodes and performs the operations they specify. This is
another type of interpreter. Some interpreters run source code written in a high level
language like Basic; others (like the Java interpreter) run bytecodes.
This second type of interpreter is sometimes called an emulator because it emulates
hardware, but in fact is software. A Java bytecode interpreter can be created for any
computer system. Once you have a Java compiler and a Java interpreter you can
run any Java program no matter what type of computer you have.
The ‘Java interpreter’ in the picture is an executable program that is running on an
ordinary computer system, such as a desktop Intel system. Each type of computer
system has its own Java interpreter that can run on that system.When the Java interpreter is running on a computer system, that system acts just
like a hardware Java bytecode processor. It is a Java Virtual Machine.
Any computer system can execute a Java bytecode program by using a Java
interpreter. The Java interpreter has to be specifically written for that particular
computer system, but once that is done, the computer system can become a Java
virtual machine. That is, it looks like a computer with a hardware Java processor chip
and can run Java bytecodes.
When a Java program is translated into bytecodes, the bytecodes are the same no
matter what computer system is used.
A Java source program (such as Hello.java) can be written and compiled on one
computer (say a Windows computer) to produce bytecode (say Hello.class). Now
that bytecode can run on any computer that has a Java interpreter.
Therefore JVM is both.
Question Bank - Unit 2
Q1 (a) What is method overriding in java ?
Sol 1 (a) If a subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
In other words, If a subclass provides the specific implementation of the
method that has been declared by one of its parent classes, it is known as
method overriding.Rules of method overriding in java:
* The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
* There must be an IS-A relationship (inheritance).
Uses:
* Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
* Method overriding is used for runtime polymorphism
Example:
class Vehicle{
//defining a method
void run(){System.out. printIn("Vehicle is running’); }
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.printin( ‘Bike is running safely'); }
public static void main(String args[]) {
Bike2 obj = new Bike2(); //creating object
obj.run();//calling method
}
}
Output : Bike is running safely
Q1 (b) Differentiate between abstract class and interface.
[GGSIPU PREVIOUS YEAR]
Sol 1 (b)
Abstract class Interface
Abstract classes can have abstract | Interfaces can have only abstract
and non-abstract methods. methods. Since Java 8, it can have
default and static methods also.
Abstract class doesn’t support Interface supports multiple
multiple inheritance. inheritance.
Abstract classes can have final, Interface has only static and final
non-final, static and non-static variables.
variables.Abstract class can provide the
implementation of interface.
Interfaces can't provide the
implementation of abstract classes.
The abstract keyword is used to
declare abstract class.
An abstract class can extend
another Java class and implement
multiple Java interfaces.
The interface keyword is used to
declare the interface.
An interface can extend another Java
interface only.
An abstract class can be extended
using the keyword ‘extends’.
An interface can be implemented
using the keyword ‘implements’.
A Java abstract class can have
class members like private,
protected, etc.
Abstract class achieves partial
abstraction.
Members of a Java interface are public
by default.
Interface achieves fully abstraction
Example:
public abstract class Shape{
public abstract void draw();
Example:
public interface Drawable{
void draw();
Q2 (a) Explain various uses of the final keyword with example.
[GGSIPU PREVIOUS YEAR]
Sol 2 (a) The final keyword in java is used to restrict the user. The java final
keyword can be used in many contexts. Final can be:
© variable
* method
° Class
Java final variable
If you make any variable as final, you cannot change the value of the final
variable(|t will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because the final variable once assigned a
value can never be changed.
class Bike {
final int speedlimit=90;//final variable
void run(){speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}//end of class
Output: Compile Time Error
Java final method
If you make any method final, you cannot override it. A final method can be
inherited but cannot be overridden.
Example of final method
class Bike{
final void run(){
System.out.printin(‘running’);
+
class Honda extends Bike{
void run(){
System.out.printin(‘running safely with 100kmph');
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output: Compile Time Error
Java final class
If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}
class Hondal extends Bike{
void run(){System.out.printin(‘running safely with 100kmph’');}
public static void main(String args[]) {
Hondal honda= new Hondal();
honda.run();
+
t
Output: Compile Time ErrorQ2 (b) Can we initialize the final static variable inside the constructor?
Explain.
Sol 2(b) No, we can not initialize the final static variable inside the
constructor. Static final variables cannot be assigned value in constructor, they
must be assigned a value with their declaration. Non-static final variables can
be assigned a value either in the constructor or with the declaration.
public class A
4
private static final int x;
public A()
{
}
}
Final means the variable can only be assigned once (in the constructor). Static
means it's a class instance.
Aconstructor will be called each time an instance of the class is created.
Thus, the above code means that the value of x will be re-initialized each time
an instance is created. But because the variable is declared final (and static),
you can only do this
class A {
private static final int x;
static {
x=5;
}
}
But, if you remove static, you are allowed to do this:
class A {
private final int x;
public AQ) {
x=5;
}
a
Q3 (a) What is type conversion? Explain implicit and explicit conversion
with example
Sol 3 (a)
e Java provides various data types such as boolean, char, int, unsigned
int, signed int, float, double, long, where every datatype acquires
different space while storing in memory.
* We can convert the value of one data type (int, float, double, etc) to
another. This process is known as type conversion.* When you assign a value of one data type to another, the two types
might not be compatible with each other.
¢ Ifthe data types are compatible, then Java will perform the conversion
automatically known as Automatic Type Conversion (implicit) , and if not
then they need to be cast or converted explicitly.
For example, assigning an int value to a long variable.
Widening or Automatic Type Conversion (implicit):
Widening conversion takes place when two data types are automatically
converted. This happens when:
The two data types are compatible.
When we assign a value of a smaller data type to a bigger data type.
For Example, in java, the numeric data types are compatible with each
other but no automatic conversion is supported from numeric type to
char or boolean. Also, char and boolean are not compatible with each
other.
Byte -> Short -> Int -> Long -> Float -> Double
Example:
class Main{
public static void main(String[] args)
4
t
int i= 100;
/ Automatic type conversion
// Integer to long type
long I= i;
// Automatic type conversion
// long to float type
float f= 1;
// Print and display commands
System.out printin(Int value ' + i);
System.out printIn('Long value + 1);
System.out printIn(Float value’ +f);
Output
Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit ConversionIf we want to assign a value of a larger data type to a smaller data type we
perform explicit type casting or narrowing.
* This is useful for incompatible data types where automatic conversion
cannot be done.
* Here, the target type specifies the desired type to convert the specified
value to.
Double -> Float -> Long -> Int -> Short -> Byte
public class Main{
public static void main(String[] args)
{
// Double datatype
double d = 100.04;
// Explicit type casting by forcefully getting
// data from long data type to integer type
long | = (long)d;
// Explicit type casting
int i = (int)l;
// Print statements
System.out.printin(‘Double value ' + d);
System.out.printin(‘Long value ‘ + 1);
System.out.printin(‘Int value ' + i);
}
}
Output
Double value 100.04
Long value 100
Int value 100
Q3 (b) Explain uses of String, StringBuffer and String Tokenizer with
example.
Sol 3 (b)
String:
In Java, string is basically an object that represents a sequence of char values. An
array of characters works the same as Java string.
The Java String class provides a lot of methods to perform operations on strings
such as compare(), concat(), equals(), split(), length(), replace(), compareTo(),
intern(), substring() etc
For example:
char[] ch=f'a’, 'p'. 'p’, ‘I’, ‘e}:
String s=new String(ch);
is same as
String s="apple";
In Java, String objects are immutable. Immutable simply means
unmodifiable or unchangeable. The java.lang. String class provides many useful
methods to perform operations on sequence of char values. Some of them are:S.n_ | Method
Description
1 | char charAt(int index)
Itretums char value for the
particular index
2 |intlengthy)
Itretums string length
3. | static String format(String format, Object...
args)
It returns a formatted string.
4 | static String format(Locale |, String format,
Object... args)
It returns a formatted string with a
given locale.
5 | String substring(int beginindex)
Itreturs a substring for a given
begin index.
String substring(int beginindex, int
endindex)
Itreturns substring for given begin
index and end index.
7 — | boolean contains(CharSequence s)
Itretums true or false after
matching the sequence of char
values.
8 | static String join(CharSequence delimiter,
CharSequence... elements)
Itretuns a joined string.
String Buffer Class: If we do a lot of changes with String objects, we will
end up with a lot of memory leaks. Java StringBuffer class is used to
create mutable (modifiable) String objects. The StringBuffer class in Java
is the same as String class except it is mutable i.e. it can be changed.
Important methods of StringBuffer class
1. Public synchronized StringBuffer append(String s): Is used to
append the specified string with this string. The append() method is
overloaded like append (char), append (boolean), append (int), append
(float), append(double) etc.
2. Public synchronized StringBuffer insert(int offset, String s): Is
used to insert the specified string with this string at the specified position.
The insert() method is overloaded like insert(int, char), insert(int,
boolean), insert(int, int), insert(int, float), insert (int, double) etc.
3. Public synchronized StringBuffer replace(int startindex, int
endindex, String str): Is used to replace the string from specified
startIndex and endindex.
4. Public synchronized StringBuffer delete(int startindex, int
endindex): Is used to delete the string from specified startindex and
endindex.
class A {
public static void main(String args[]){StringBuffer sb=new StringBuffer('Hello');
sb.append(‘Java'); //now original string is changed
System.out.printin(sb) ;//prints Hello Java
t
String is slow and consumes more memory when we concatenate too
many strings because every time it creates a new instance, whereas,
StringBuffer is fast and consumes less memory when we concatenate the
strings
String Tokenizer in Java: The java.util.StringTokenizer class allows you
to break a String into tokens. It is a simple way to break a String.
The six useful methods of the StringTokenizer class are as follows:
Method Description
boolean hasMoreTokens() | It checks if there are more tokens available.
String nextToken() It returns the next token from the
StringTokenizer object.
String nextToken(String It returns the next token based on the delimiter.
delim)
boolean It is the same as hasMoreTokens() method
hasMoreElements()
Object nextElement() It is the same as nextToken() but its return type
is Object.
int countTokens() It returns the total no. of tokens
Example:
import java.util. StringTokenize
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer(‘how are you ','');
while (st.hasMoreTokens()) {
System.out.printin(st.nextToken());
}
}
Output
how
are
you
Q4 (a) What are Wrapper Classes? What is the purpose of using them?
Sol 4 (a)
Awrapper class is defined as a class in which a primitive value is wrapped up.
These primitive wrapper classes are used to represent primitive data typevalues as objects. The Java platform provides wrapper classes for each of the
primitive data types. For example, Integer wrapper class holds primitive ‘int’
data type value. Similarly, Float wrapper class contains ‘float’ primitive values,
Character wrapper class holds a ‘char’ type value, and Boolean wrapper class
represents ‘boolean’ value.
int i = 26; // Primitive data type ‘int’
//integer Wrapper class instantiation
Integer i_Obj= new Integer(i); // Unwrapping primitive data ‘int’ from
wrapper object
int j=i_Obj.intValue();
Q4 (b) Explain concept of inner class and anonymous inner class with
example.
Sol 4 (b)
Java Inner Class contains
1. Java Inner classes
2. Advantage of Inner class
3. Difference between nested class and inner class
Java inner class or non-static nested class is a class i.e, declared
inside the class or interface.
We use inner classes to logically group classes and interfaces in one
place so that it can be more readable and maintainable.
Additionally, it can access all the members of the outer class including
private data members and methods.
Syntax of Inner class
class Java Outer_class
/icode
class Java Inner_class{
iicode
}
}
Advantage of java inner classes
There are basically three advantages of inner classes in java:
(1) Inner classes represent a special type of relationship, that is it can
access all the members (data members and methods) of outer class
including private.
(2) Inner classes are used to develop more readable and maintainable
code because it logically groups classes and interfaces in one place
only.
(3) Code Optimization: It requires less code to write.Difference between nested class and inner class
Nested classes that are declared static are called static nested classes. A
nested class is a member of its enclosing class. Non-static nested classes
(inner classes) have access to other members of the enclosing class, even if
they are declared private.
Java Anonymous inner class
Aclass that has no name is known as an anonymous inner class in java. It should be
used if you have to override the method of class or interface. Java Anonymous inner
class can be created by two ways:
1. Class (may be abstract or concrete).
2. Interface
Java anonymous inner class example using class
abstract class Person{
abstract void eat();
class TestAnonymousinner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out. printin(“nice fruits”); }
oa
p.eat();
}
}
Q5) What is an applet? Explain the life cycle of Applet and its security
concerns.
[GGSIPU PREVIOUS YEAR]
Sol 5) Features of applet are:
* Itis a small program and is used to run a program on client Browser.
* Applet is portable and can be executed by a supported browser.
* Applet applications are executed in Restricted Environment.
* Applets are created using the extension java.applet.Applet
* Applet application has 5 methods which will be automatically invoked on
occurrence of specific events.
Following are the methods:
1. init() method
2. start() method
3. paint() method
4. stop() method
5. destroy() method
These methods are known as life cycle methods. These methods are defined
in java.applet.Applet class except paint() method. The paint() method is
defined in java.awt. Component class, an indirect superclass of Applet.The life cycle methods are called callback methods as they are called
implicitly by the browser for the smooth execution of the applet. Browsers
should provide an environment known as a container for the execution of the
applet. Following are the responsibilities of the browser.
1. It should call the callback methods at appropriate times for the smooth
execution of the applet
2. It is responsible for maintaining the life cycle of the applet.
3. It should have the capability to communicate between applets, applet to
JavaScript and HTML, applet to browser etc.
Q6) (a) Describe the various types of exceptions and illustrate how they
are handled.
[GGSIPU PREVIOUS YEAR]
Sol 6) (a) A Java exception is an object that describes the exception that
occurs in a program. When an exceptional event occurs in Java an exception
is said to be thrown. The code that is responsible for doing something about
the exception is called an exception handler.
* Checked Exception: The exception that can be predicted by the
programmer. Example: File that needs to be opened is not found. These
types of exceptions must be checked at compile time.
* Unchecked Exception: Unchecked exceptions are the class that
extends Runtime Exception. Unchecked exceptions are ignored at
compile time. Example: ArithmeticException, NullPointerException,
Array Index out of Bound exception. Unchecked exceptions are
checked at runtime.
* Error: Errors are typically ignored in code because you can rarely do
anything about an error. Example: If stack overflow occurs, an error will
arise. This type of error is not possible to handle in code.
Exception handling is done using five keywords,
1. Try 2. Catch 3. Throw 4. Throws 5. Finally
Exception handling is done by transferring the execution of a program to an
appropriate exception handler when exception occurs.
* Using try and catch: Try is used to guard a block of code in which an
exception may occur. This block of code is called a guarded region. A
catch statement involves declaring the type of exception you are trying
to catch. If an exception occurs in guarded code, the catch block that
follows the try is checked, if the type of exception that occurred is listed
in the catch block then the exception is handed over to the catch block
which then handles it.
* Example using Try and catch: