Java Final - Merged
Java Final - Merged
a)
E)
b)Static
Method Overloading Method Overriding
Static binding is being used for overloaded Dynamic binding is being used for overriding
methods. methods.
Argument list should be different while Argument list should be same in method
doing method overloading. overriding.
It can be applied to nested static class, variables, methods and block.
It is not required to initialize the static variable when it is declared.
This variable can be re-initialized.
It can access the static members of the class only.
It can be called only by other static methods.
Objects of static class can’t be created.
Static class can only contain static members.
It is used to initialize the static variables.
Final
It is a keyword.
It is used to apply restrictions on classes, methods and variables.
It can’t be inherited.
It can’t be overridden.
Final methods can’t be inherited by any class.
It is needed to initialize the final variable when it is being declared.
Its value, once declared, can’t be changed or re-initialized.
F)
2. Applicable Final keyword is used Finally block is always finalize() method is used
to with the classes, related to the try and with the objects.
methods and variables. catch block in exception
handling.
3. Functionality (1) Once declared, final (1) finally block runs the finalize method performs
variable becomes important code even if the cleaning activities
constant and cannot be exception occurs or not. with respect to the object
modified. (2) finally block cleans before its destruction.
(2) final method cannot up all the resources
be overridden by sub used in try block
class.
(3) final class cannot be
inherited.
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
Static variables are rarely used other than being declared as constants. Constants
are variables that are declared as public/private, final, and static. Constant
variables never change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the
program stops.
Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is
0; for Booleans, it is false; and for object references, it is null. Values can be
assigned during the declaration or within the constructor. Additionally, values
can be assigned in special static initializer blocks.
Static variables can be accessed by calling with the class name
ClassName.VariableName.
When declaring class variables as public static final, then variable names
(constants) are all in upper case. If the static variables are not public and final,
the naming syntax is the same as instance and local variables.
o Change the value in Method: Java supports only call by value. So,
if we pass a primitive value, it will not change the original value. But,
if we convert the primitive value in an object, it will change the
original value.
o Serialization: We need to convert the objects into streams to
perform the serialization. If we have a primitive value, we can convert
it in objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in
Multithreading.
o java.util package: The java.util package provides the utility classes
to deal with objects.
o Collection Framework: Java collection framework works with
objects only. All classes of the collection framework (ArrayList,
LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue,
ArrayDeque, etc.) deal with objects only.
Basis of Exception Error
Comparison
Type It can be classified into two categories i.e. All errors in Java are
checked and unchecked. unchecked.
Known or Only checked exceptions are known to the Errors will not be known to the
unknown compiler. compiler.
11)And can you explain when you are using Abstract classes?
=>In Java, we can create our own exceptions that are derived classes of
the Exception class. Creating our own Exception is known as custom
exception or user-defined exception. Basically, Java custom exceptions
are used to customize the exception according to user need.
While a developer can never actually force Java garbage collection, there
are ways to make the JVM prioritize memory management functions. In
review, five ways to try and force Java garbage collection are:
=> Wrapper classes in Java provides a way to wrap or represent the value of primitive
data types as an object. By creating an object to the wrapper class, a data field is created
and in this field we can store the value of a primitive data type.
It also include methods to unwrap the objects back into the primitive data types. It is
one of the classes provided in the java.lang package and all of the primitive wrapper
classes in Java are immutable.
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
=>
19. What is the difference between ‘throw’ and ‘throws’? And it’s
application?
=>
S. Key
No. Difference throw throws
=>In Java, it is possible to inherit attributes and methods from one class to
another. We group the "inheritance concept" into two categories:
29. What is the difference between a JDK (Java Development Kit) and a JVM
(Java Virtual Machine)? What is the base class of all classes? What is a package?
Which package is imported by default?
(25)What is JVM
It is:
=> The super base class of all the Java classes is the
java.lang.Object class. In Java, each Java descends from the
Object.
package demotest;
public class GuruThread1 implements Runnable
{
public static void main(String[] args) {
Thread guruThread1 = new Thread("Guru1");
Thread guruThread2 = new Thread("Guru2");
guruThread1.start();
guruThread2.start();
System.out.println("Thread names are
following:");
System.out.println(guruThread1.getName());
System.out.println(guruThread2.getName());
}
@Override
public void run() {
}
}
=>
Meaning A Java Application also known The Java applet works on the
as application program is a type client side, and runs on the
of program that independently browser and makes use of
executes on the computer. another application program so
that we can execute it.
Requirement of Its execution starts with the It does not require the use of any
main( ) method main( ) method only. The use of main() method. Java applet
the main( ) is mandatory. initializes through init( ) method.
Installation We need to install the Java Java applet does not need to be
application first and obviously pre-installed.
on the local computer.
Operation It performs read and write tasks It cannot run the applications on
on a variety of files located on a any local computer.
local computer.
File access It can easily access a file or data It cannot access the file or data
available on a computer system found on any local system or
or device. computer.
Security Java applications are pretty Java applets are less reliable. So,
trusted, and thus, come with no they need to be safe.
security concerns.
C) =>
1. import java.applet.Applet;
2. import java.awt.Graphics;
3. public class First extends Applet{
4.
5. public void paint(Graphics g){
6. g.drawString("welcome",150,150);
7. }
8.
9. }
2) Object is a real world entity such as pen, laptop, Class is a group of similar
mobile, bed, keyboard, mouse, chair etc. objects.
4) Object is created through new keyword mainly Class is declared using class
e.g. keyword e.g.
Student s1=new Student(); class Student{}
7) There are many ways to create object in java There is only one way to
such as new keyword, newInstance() method, define class in java using
clone() method, factory method and class keyword.
deserialization.
(Class is a detailed description, the definition, and the template of what an
object will be. But it is not the object itself. Also, what we call, a class is the
building block that leads to Object-Oriented Programming. It is a user-defined
data type, that holds its own data members and member functions, which can
be accessed and used by creating an instance of that class. It is the blueprint
of any object. Once we have written a class and defined it, we can use it to
create as many objects based on that class as we want. In Java, the class
contains fields, constructors, and methods. For example, consider
the Class of Accounts. There may be many accounts with different names
and types, but all of them will share some common properties, as all of them
will have some common attributes like balance, account holder name, etc.
So here, the Account is the class.
Object is an instance of a class. All data members and member functions of
the class can be accessed with the help of objects. When a class is defined,
no memory is allocated, but memory is allocated when it is instantiated (i.e. an
object is created). For Example, considering the objects for the
class Account are SBI Account, ICICI account, etc.) (Just for
understanding Rajarshi)
=>Any code as an example.
b) If your machine has JRE, then it can run all java applets and applications, jre provides
environment for them to run.
While if your machine has jdk than you can also develop java applications.. It provides
compiler and debugger for development purpose..
c) 1. Public
It is an Access modifier, which specifies from where and who can access the
method. Making the main() method public makes it globally available. It is
made public so that JVM can invoke it from outside the class as it is not
present in the current class.
2. Static
5. String[] args
d)
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
=>a) The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
System.out.println("Turning on Phone...");
}
}
class SmartPhone extends Phone{
public void music(){
System.out.println("Playing music...");
}
public void on(){
System.out.println("Turning on SmartPhone...");
}
}
public class CWH {
public static void main(String[] args) {
obj.showTime();
obj.on();
// obj.music(); Not Allowed
}
}
The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has
five core methods namely init(), start(), stop(), paint() and destroy().These methods are
invoked by the browser to execute.
Along with the browser, the applet also works on the client side, thus having less
processing time.
o init(): The init() method is the first method to run that initializes the applet. It
can be invoked only once at the time of initialization. The web browser creates
the initialized objects, i.e., the web browser (after checking the security settings)
runs the init() method within the applet.
o start(): The start() method contains the actual code of the applet and starts the
applet. It is invoked immediately after the init() method is invoked. Every time
the browser is loaded or refreshed, the start() method is invoked. It is also
invoked whenever the applet is maximized, restored, or moving from one tab
to another in the browser. It is in an inactive state until the init() method is
invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method
is invoked whenever the applet is stopped, minimized, or moving from one tab
to another in the browser, the stop() method is invoked. When we go back to
that page, the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the
webpage is closed. It removes the applet object from memory and is executed
only once. We cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to
draw shapes like circle, square, trapezium, etc., in the applet. It is executed after
the start() method and when the browser or applet windows are resized.
6. a) Differentiate between 'up casting' and 'down casting' with
suitable examples. b) What is thread? Explain thread creation
methods. c) How does synchronized keyword works? Why is thread
synchronization important for Multithreaded process? d)What are
packages and what are they used for? 3+4+4+4=15
=>a) https://www.geeksforgeeks.org/upcasting-vs-downcasting-in-
java/
b) In java, a thread is a lightweight process. Every java program executes by a thread called
the main thread. When a java program gets executed, the main thread created automatically.
All other threads called from the main thread.
The java programming language provides two methods to create threads, and they are listed
below.
Step-1: Create a class as a child of Thread class. That means, create a class that extends
Thread class.
Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.
Example
class SampleThread extends Thread{
Example
class SampleThread implements Runnable{
In java, when two or more threads try to access the same resource
simultaneously it causes the java runtime to execute one or more
threads slowly, or even suspend their execution. In order to overcome
this problem, we have thread synchronization.
Synchronization means coordination between multiple
processes/threads.
For example, when using a cell phone, you can figure out how to answer
incoming calls and respond to text messages.
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
The idea behind inheritance in Java is that you can create new classes
that are built upon existing classes. When you inherit from an existing class,
you can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.
=>given below:
2) String is slow and consumes more memory StringBuffer is fast and consumes
when we concatenate too many strings because less memory when we
every time it creates new instance. concatenate t strings.
3) String class overrides the equals() method of StringBuffer class doesn't
Object class. So you can compare the contents override the equals() method of
of two strings by equals() method. Object class.
5) String class uses String constant pool. StringBuffer uses Heap memory
d)The main purpose of using a class being declared as final is to prevent the
class from being subclassed. If a class is marked as final then no class can
inherit any feature from the final class.
e) Java inner class or nested class is a class that is declared inside the class or
interface.
We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
Additionally, it can access all the members of the outer class, including private data
members and methods.
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
1. Nested classes represent a particular type of relationship
that is it can access all the members (data members and
methods) of the outer class, including private.
2. Nested classes are used to develop more readable and
maintainable code because it logically group classes and
interfaces in one place only.
3. Code Optimization: It requires less code to write.
a) Garbage Collection in JAVA: Garbage collection in Java is the process by
which Java programs perform automatic memory management. Java
programs compile to bytecode that can be run on a Java Virtual
Machine, or JVM for short. When Java programs run on the JVM,
objects are created on the heap, which is a portion of memory
dedicated to the program. Eventually, some objects will no longer be
needed. The garbage collector finds these unused objects and deletes
them to free up memory. Java garbage collection is an automatic
process. Automatic garbage collection is the process of looking at heap
memory, identifying which objects are in use and which are not, and
deleting the unused objects. An in-use object, or a referenced object,
means that some part of your program still maintains a pointer to that
object. An unused or unreferenced object is no longer referenced by
any part of your program. So the memory used by an unreferenced
object can be reclaimed. The programmer does not need to mark objects
to be deleted explicitly. The garbage collection implementation lives in
the JVM.
c) Association:
=> Association in Java defines the connection between two classes that
are set up through their objects. Association manages one-to-one, one-
to-many, and many-to-many relationships. In Java, the multiplicity
between objects is defined by the Association. It shows how objects
communicate with each other and how they use the functionality and
services provided by that communicated object. Association
manages one-to-one, one-to-many, many-to-one and many-to-
many relationships. Let's take an example of each relationship to manage
by the Association.
Example
This shows that class Van HAS-A Speed. By having a separate class for Speed,
we do not have to put the entire code that belongs to speed inside the Van class,
which makes it possible to reuse the Speed class in multiple applications.
In the Object-Oriented feature, the users do not need to bother about which object
is doing the real work. To achieve this, the Van class hides the implementation
details from the users of the Van class. So, basically what happens is the users
would ask the Van class to do a certain action and the Van class will either do
the work by itself or ask another class to perform the action. This concept of
containing an object to do action is termed as Aggregation.
System.out.println("Zzz");
Encapsulation:(age ache)
Inheritance: (ager ta)
Wrapper Class. (age)
String Tokenizer Class. The string tokenizer class allows an
application to break a string into tokens. The tokenization
method is much simpler than the one used by
the StreamTokenizer class.
The StringTokenizer methods do not distinguish among
identifiers, numbers, and quoted strings, nor do they recognize
and skip comments
import java.util.*;
public class Sample {
public static void main(String[] args) {
// creating string tokenizer
StringTokenizer st = new StringTokenizer("Come to learn");
// checking next token
System.out.println("Next token is : " + st.nextToken());
}
}
Output
Next token is : Come
=>
Abstract class Interface
1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Part c
1. What are main differences of Structured Programming Language and Object oriented
programming language? Why Java is so important to the internet? 3+2 [8+5 Minutes]
Importance of Java to the Internet
Java has had a profound effect on the Internet because it allows objects to move freely in
Cyberspace. In a network there are two categories of objects that are transmitted between the
Server and the Personal computer.
Passive information
The Dynamic Self-executing programs cause serious problems in the areas of Security and
probability. But Java addresses those concerns and by doing so has opened the door to an
exciting new form of program called the Applet.
2 Which members are called static members? When do all static members get memory
location and by whom? 2+3[5+8 Minutes]
3 What is the order of execution of all static variables? What is the lifetime and scope of
static variable? 2+3[5+8 Minutes]
Ans : When you have all the three in one class, the static blocks are executed first, followed by
constructors and then the instance methods.
A static variable stays in the memory and retains its value until the program execution ends
irrespective of its scope. Scope is of four types: file, block, function and prototype
scope. Lifetime is of three types: static, auto and dynamic lifetime
4. How JVM execute the static variables before its main method even if it is defined after the
main method? Can we declare local variable or parameters as static? Explain. 3+2[8+5
Minutes]
Ans:- First, JVM executes the static block, then it executes static methods, and then it creates the
object needed by the program. Finally, it executes the instance methods. JVM executes a static
block on the highest priority basis. It means JVM first goes to static block even before it looks for
the main() method in the program.
Eg-
You can use Static only on local variables. This means the declaration context for a Static
variable must be a procedure or a block in a procedure, and it cannot be a source file, namespace,
class, structure, or module.
5. Show the JVM architecture of static variables. When a method is called as static method?
Can we nest static blocks? 2+3[8+5 Minutes]
Static methods are the methods in Java that can be called without creating an object of class.
They are referenced by the class name itself or reference to the Object of that class.
Both, nesting of instance and static blocks, does not make sense - and both is not allowed.
6. What is the order of execution of static variable, static block, static method and main
method? When user defined methods should declare as static methods? 3+2[8+5 Minutes]
Order of execution
When you have all the three in one class, the static blocks are executed first, followed
by constructors and then the instance methods.
You should consider making a method static in Java : 1) If a method doesn't modify the state of
the object, or not using any instance variables. 2) You want to call the method without creating
an instance of that class.
Overloading and overriding
7. Why Dynamic method dispatch is called run-time polymorphism? Why java does not
support operator overloading? 3+2[8+5 Minutes]
8. Why static method can’t be overloaded? Can we override constructor? Explain 3+2 [8+5
Minutes
Overloading: Overloading is also a feature of OOP languages like Java that is
related to compile-time (or static) polymorphism. This feature allows different
methods to have the same name, but different signatures, especially the number
of input parameters and type of input parameters. Note that in both C++ and
Java, methods cannot be overloaded according to the return type.
Can we overload static methods?
The answer is ‘Yes’. We can have two or more static methods with the same
name, but differences in input parameters. For example, consider the following
Java program.
Constructor looks like method but it is not. It does not have a return type and its name is same
as the class name.
But, a constructor cannot be overridden. If you try to write a super class’s constructor in the
sub class compiler treats it as a method and expects a return type and generates a compile time
error.
9. Can we overload the main method? Give reason to support your answer. What is the
difference between compile time and runtime polymorphism? 2+3[5+8 Minutes]
Yes, we can overload the main() method in Java. A Java class can have any number of
overloaded main() methods. But the very first thing JVM (Java Virtual Machine) seeks is the
original main() method, i.e., public static void main(String[] args) to execute. The class
will compile but won't run without the original main() method.
The main method is a special method in Java that acts as an entry point for running any Java
program. It always has the same syntax, i.e., public static void main (String[] args). One
can only change the name of the String array argument, for example, args as str.
As JVM starts its execution by invoking the main method of the class, so, it must have
an exact signature as mentioned above. The following methods are overloaded main method:
Inheritance
10. Why java class does not support multiple inheritances? Why subclass variable can’t
refer to super class object? 3+2 [8+5 Minutes]
Because an instance of the superclass isn't (necessarily) an instance of a subclass. For example, a
Parrot is an Animal , but not every Animal is a Parrot .
Blocks
11. Can we write a program without main method? Why static blocks are executed only
once where as instance blocks are executed for each object? 2+3[5+8 Minutes]
When we execute a particular class, JVM performs two actions at the runtime. They are as:
1. JVM loads the corresponding dot class file (byte code) into memory.
2. During the dot class file loading into memory, a static block is executed. After loading the dot
class file, JVM calls the main method to start execution. Therefore, the static block is executed
before the main method.
or in simple word’s we can also say that static block always gets executed first in Java
because it is stored in the memory at the time of class loading and before the object
creation.
First, JVM executes the static block, then it executes static methods, and then it creates the
object needed by the program. Finally, it executes the instance methods. JVM executes a
static block on the highest priority basis. It means JVM first goes to static block even before
it looks for the main() method in the program.
Final keyword
12. Explain why abstract class can’t be declared as Final. If a class is declared as final
whether all its members are final? Explain 3+2[8+5 Minutes
Abstract keyword
13. When we will use an Interface and an Abstract class? Does abstract class have
constructor? 3+2 [8+5 Minutes]
An abstract class is used if you want to provide a common, implemented functionality among all
the implementations of the component. Abstract classes will allow you to partially implement
your class, whereas interfaces would have no implementation for any members whatsoever.
As we all know abstract classes also do have a constructor. So if we do not define any
constructor inside the abstract class then JVM (Java Virtual Machine) will give a default
constructor to the abstract class.
Inner class
14. What are the advantages and disadvantages of using inner classes? If you compile a file
containing inner class how many .class files are created and can we access them accessible in
usual way? 3+2 [8+5 Minutes]
Advantage:- Note that inner classes can access outer class private members and at the same
time we can hide inner class from outer world. Keeping the small class within top-level classes
places the code closer to where it is used and makes the code more readable and maintainable
Disadvantage:- Inner classes have their disadvantages. From a maintenance point of
view, inexperienced Java developers may find the inner class difficult to understand. The use of
inner classes will also increase the total number of classes in your code.
Two files are created will be created. Though a separate inner class file is generated, the inner
class file is not accessible in the usual way.
15. Can you define a class without name? What are different types of anonymous classes
and do anonymous classes have constants? 2+3 [5+8 Minutes]
Yes, we can create a class without a name using the Anonymous class.
Anonymous class is an inner class which does not have a name and whose instance is created
at the time of the creation of class itself and these classes are somewhat different from normal
classes in its creation.
An anonymous class can have static members provided that they are constant variables.
16. Can anonymous class define method of its own? Can an anonymous can implement an
interface and also extend a class at the same time? 2+3 [5+8 Minutes]
A normal class can implement any number of interfaces but the anonymous inner class can
implement only one interface at a time. A regular class can extend a class and implement any
number of interfaces simultaneously. But anonymous Inner class can extend a class or can
implement an interface but not both at a time.
Interface
17. Can we compile and execute interface? Can interface have concrete members? Can we
declare interface method as private and protected? Why interface members are by default
public? 2+3 [5+8 Minutes]
Open a command prompt and navigate to the directory containing your Java program. Then
type in the command to compile the source and hit Enter . The interface is now ready to be
implemented by a Java program. The Java program declares that it will implement the interface
by using the implements keyword.
All the methods in an interface must be abstract, you cannot have a concrete method (the one
which has body) if you try to do so, it gives you a compile time error saying “interface abstract
methods cannot have body”.
In general, the protected fields can be accessed in the same class or, the class inheriting it. But,
we do not inherit an interface we will implement it. Therefore, cannot declare the fields of an
interface protected.
Default methods are defined with the default modifier, and static methods with the static
keyword. All abstract, default, and static methods in an interface are implicitly public , so you can
omit the public modifier. In addition, an interface can contain constant.
18. Can we create an empty interface? What is the marker interface, what are the
predefined marker interfaces? What is the use of an interface? 2+3 [5+8 Minutes]
An empty interface in Java is known as a marker interface i.e. it does not contain any methods
or fields by implementing these interfaces a class will exhibit a special behavior with respect to
the interface implemented. java. lang. Cloneable and java.
A marker interface is an interface that doesn't have any methods or constants inside it. It
provides run-time type information about objects, so the compiler and JVM have additional
information about the object. A marker interface is also called a tagging interface.
Interfaces are useful for the following: Capturing similarities among unrelated classes without
artificially forcing a class relationship. Declaring methods that one or more classes are expected
to implement. Revealing an object's programming interface without revealing its class.
Enum keyword
19. Explain the advantages of enum? Can we create a normal variables, methods, blocks
and constructors in enum? 2+3 [5+8 Minutes]
Enumerations in Java can be compared usign == operator. Safe comparison because enum
constants are static and final by default. We can use enum parameter in a switch case. This makes
constants driven computations better and faster.
It can have constructors, methods and instance variables. It is created using the enum keyword.
By default, each enumeration constant is public, static and final. Even though enumeration defines
a class type and has constructors, you do not need to instantiate an enum using the new variable.
20. Write the difference between default constructor in class and enum? Can we create
object of enum like normal class and can create enum from another enum? 2+3
[5+8Minutes]
Difference between Enums and Classes
The only difference is that enum constants are public , static and final (unchangeable - cannot be
overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can
implement interfaces).
An enum can, just like a class , have attributes and methods. The only difference is that enum
constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be
used to create objects, and it cannot extend other classes (but it can implement interfaces).
Package
21. Why package concept is useful in JAVA? What are the difference between
a. import pkg.*;
b. import pkg.C; 2+3[5+8 Minutes]
Make easy searching or locating of classes and interfaces. Implement data encapsulation (or
data-hiding). Provide controlled access: The access specifiers protected and default have access
control on package level.
22. How to access non packaged classes from packaged class? Explain static imports in
JAVA. 2+3[5+8 Minutes]
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
In Java, static import concept is introduced in 1.5 version. With the help of static
import, we can access the static members of a class directly without class name or any
object. For Example: we always use sqrt() method of Math class by using Math class
i.e. Math.sqrt(), but by using static import we can access sqrt() method directly.
According to SUN microSystem, it will improve the code readability and enhance coding.
But according to the programming experts, it will lead to confusion and not good for
programming. If there is no specific requirement then we should not go for static import.
Thread
23. Why multithreading is so important with respect to OS? What thread is called light
weight process? 3+2 [8+5 Minutes]
Multithreading in an interactive application may allow a program to continue running even if a
part of it is blocked or is performing a lengthy operation, thereby increasing responsiveness to the
user.
Threads are sometimes called lightweight processes because they have their own stack but can
access shared data. Because threads share the same address space as the process and other threads
within the process, the operational cost of communication between the threads is low, which is an
advantage.
24. What are the differences between multithreading and multiprocessing? Why
synchronization is so important in real life? 3+2 [5+8 Minutes]
Data synchronization ensures accurate, secure, compliant data and successful team and customer
experiences. It assures congruence between each source of data and its different endpoints. As data
comes in, it is cleaned, checked for errors, duplication, and consistency before being put to use. Local
synchronization involves devices and computers that are next to each other, while remote
synchronization takes place over a mobile network.
Data must always be consistent throughout the data record. If data is modified in any way, changes
must upgrade through every system in real-time to avoid mistakes, prevent privacy breaches, and
ensure that the most up-to-date data is the only information available. Data synchronization ensures
that all records are consistent, all the time.
Exception handling
25. Why exception handling mechanism has been introduced in java? Explain. Does finally
block executes always? 3+2 [8+5 Minutes]
It is one of the powerful mechanisms to handle runtime exceptions and makes it bug-free.
Exception handling helps in maintaining the flow of the program. An exception handling is
defined as an abnormal condition that may happen at runtime and disturb the normal flow of
the program.
Checked Exceptions: Unchecked Exceptions
Occur at compile time: Occur at runtime
Can be handled at the compilation time: Can’t ...
The finally block always executes when the try block exits. This ensures that the finally block is
executed even if an unexpected exception occurs.
26. Does catch block is mandatory for every try block? Explain. When NullPointerException is
thrown? Explain. 3+2 [8+5 Minutes]
Yes, It is possible to have a try block without a catch block by using a final block.
As we know, a final block will always execute even there is an exception occurred in a try
block, except System.exit() it will execute always.
Class NullPointerException
Thrown when an application attempts to use null in a case where an object is required. These
include: Calling the instance method of a null object. Accessing or modifying the field of a null
object. Taking the length of null as if it were an array.
Applet
27. Why Applets are not being used today? Explain. What is the order of method invocation in
an Applet? 2+3[5+8 Minutes]
Applets are a technology that are very much of their time, and they have not aged well. The
technology proved to be very difficult to evolve, and so applets have not been considered to be a
modern development platform for many years now.
It basically has five core methods namely init(), start(), stop(), paint() and destroy().These
methods are invoked by the browser to execute. Along with the browser, the applet also works on the
client side, thus having less processing time.
28. How will you communicate between two Applets? Can Applet have constructors? 3+2[8+5
Minutes]
A Java applet can communicate with other Java applets by using JavaScript functions in the parent
web page. JavaScript functions enable communication between applets by receiving messages from
one applet and invoking methods of other applets.
Applets can have a default constructor, but it is better to perform all initializations in the init
method instead of the default constructor. This method is automatically called after Java calls the init
method.
Event handling
29. What is the difference between panel and frame? What is the default layout of the panel and
frame? 3+2 [8+5 Minutes]
1. Panel requires a Frame to display it. A frame can consist of a panel or a set of panels.
2. A-frame is a top-level window. It has a title bar, menu bar, borders, and resizing corners.
Panel uses FlowLayout as default layout manager while Frame uses BorderLayout as
default layout manager
Arial
30. Applet using AWT or using Swing which one is better and why? Explain. What is the difference
between an applet and a Japplet? 3+2 [8+5 Minutes]
Java AWT has comparatively less functionality as compared to Swing. Java Swing has
more functionality as compared to AWT
Swing supports pluggable look and feel. AWT provides less components than Swing.
Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.