F7 Java
F7 Java
C- Language Java
C language was developed by Dennis M. Java was developed by James Gosling
Ritchie in the year 1972. in the year 1995.
C is Procedural-Oriented Java is Object-Oriented
Functions play a major role in the C Objects play a major role in the Java
language. language.
It is a middle-level language It is a high-level language.
Java supports OOPS concepts, in which
C language does not support OOPS Concepts. Inheritance the main property used for code
reusability.
In Java, memory is allocated using a new
In C, memory is allocated using Malloc
keyword.
The threading concept is not supported by C Java supports Threading
It is not portable It is portable
Default members of C are public Default members of Java are private
Storage classes are supported by C Storage classes are not supported in Java
Java is the first programming language that is used to write code on a virtual machine, so
that is the reason why it is called JVM (Java Virtual Machine). This JVM is a new concept
that is introduced in Java. It also provides a new feature called code reusability which is not
possible in C.
5. Compare both C++ and Java?
Java C++
Java is platform-independent C++ is platform dependent
The Goto statement is not supported by Java C++ supports the goto statement
Multiple inheritances are supported in Java by Multiple inheritances are supported
using interfaces in C++
Java doesn’t support structures and unions C++ does support unions and structures
C++ does not provide built-in support for
Java has built-in support for threading
threading
Java is used for building applications C++ is used for system programming
Java uses both an interpreter and a compiler C++ uses compiler only
Dynamic: Java is more dynamic when compared to C++ and C. Java is designed in
such a way that it is adaptable to any evolving environment.
Simple: Java is very easy to learn and code.
Object-oriented: In Java, everything is based on objects.
Secure: Java provides a secure platform to develop safe and virus-free applications.
Platform Independent: Unlike C and C++, when we compile Java code it is compiled
into platform-independent bytecode rather than the platform-specific machine code.
Portable: Java provides no implementation aspects for the specifications that make
Java portable.
Multithreaded: By this feature, we can perform multiple tasks simultaneously in Java.
High-Performance: With the built-in Just-in-Time compiler, Java provides high
performance.
Robust: Java makes more efforts to eliminate errors by concentrating more on runtime
checking and compile-time check.
Class is defined as a template or a blueprint that is used to create objects and also to define
objects and methods.
The instance of a class is called an object. Every object in Java has both state and behavior.
The state of the object is stored in fields and the behavior of the objects is defined by
methods.
JVM is the abbreviation for Java Virtual Machine. It is a virtual machine that provides a
runtime environment to write code. JVM is a part of JRE (Java Runtime Environment) and is
used to convert the bytecode into machine-level language. This machine is responsible for
allocating memory.
11. Name the memory areas that are allocated by JVM and explain the class loader in JVM?
There are totally five memory areas that are allocated by the JVM, and they are:
Class Area
Heap
Stack
Native Method Stack
PC Register
ClassLoader: class loader is a subschema of JVM which is used to load class files. Whenever
we run Java programs, the data will be first loaded from the classloader. There are mainly
three in-built classloaders in JVM, they are:
Application Classloader
Bootstrap Classloader
Extension Classloader
Java Development Kit is one of the three prominent technology packages used in Java
programming. JDK is used as a standalone component to run the Java programs by JVM and
JRE. This kit is used to implement Java platform specifications, including class libraries and
compiler.
Java Runtime Environment (JRE) is a collection of software tools that are designed for the
development of Java applications. This is a part of JDK, but it can be downloaded separately.
JRE is mainly responsible for orchestrating the component activities.
14. What is the significant difference between JVM, JRE, and JDK?
We can understand the difference between JVM, JDK, and JRE by the following diagram:
JVM: Java Virtual Machine is the main part of Java programming, which provides
platform independence. JRE and JDK both contain JVM in order to run our Java
programs.
JDK: This development kit is mainly used for developing programs.
JRE: Java Runtime Environment is mainly used for running Java programs.
Just In Time Compiler is the component of JRE, which is used to compile the bytecodes of
the particular method into the native machine code. This compiled code of the method is
directly called by JVM without interpreting it
Variables in Java can be defined as a basic storage unit of a program. It is a storage unit that
holds the value during the program execution. Always the variable is assigned with a
datatype.
For Example:
int a = 10;
There are mainly three different types of variables available in Java, and they are:
Static Variables
Local Variables
Instance Variables
Static Variables: A variable that is declared with the static keyword is called a static variable.
A static variable cannot be a local variable, and the memory is allocated only once for these
variables.
Local Variables: A variable that is declared inside the body of the method within the class is
called a local variable. A local variable cannot be declared using the static keyword.
Instance Variables: The variable declared inside the class but outside the body of the method
is called the instance variable. This variable cannot be declared as static and its value is
instance-specific and cannot be shared among others.
Example:
class A{
int num=30;//instance variable
static char name=pranaya;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Typecasting in Java is done explicitly by the programmer; this is done to convert one data
type into another data type.
Widening (automatically) - conversion of a smaller data type to a larger data type size.
byte -> short -> char -> int -> long -> float -> double
Narrowing (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Type conversion can be defined as converting one data type to another data type
automatically by the compiler.
There are two types of type conversions, and they are:
Datatypes in Java specify the values and sizes that can be stored in the variables. There are
mainly two types of data types; they are:
Primitive data types in Java are the major constituents of data manipulation. These are the
most basic data types that are available in Java. The primitive data types include int, char,
byte, float, double, long, short, and boolean.
22. What are the default values and sizes of primitive data types?
The non-primitive data types are something that is different from primitive data types, and
these non-primitive data types include String, arrays, and structures.
24. Why char uses 2 bytes in Java and what is this ‘u0000’ notation called?
This is only due to the reason that Java uses the Unicode system. The notation ‘u0000’ is the
lowest range of the Unicode system, and it is the default value of the char data type.
To overcome the problems present in the previous language standards, the Unicode system
has been introduced. Java uses the Unicode system because the character default size
provided by Unicode is 2 bytes and Java also needs only 2 bytes for the character.
It is because the Java compiler converts the code into byte code which is the main
transitional language between machine code and source code. This byte code is not platform-
dependent so that it can be compiled and executed on any platform.
29. Is exit, null, delete, main, and next are the keywords in Java?
1. Arithmetic operators
2. Assignment operators
3. Logical operators
4. Relational operators
5. Bitwise operators
6. Unary operators
7. Ternary operators
8. Shift operators
Java provides a set of rules and regulations for particularly specifying the order in which
operators are evaluated. If the expression has many numbers of operators then the operator
precedence comes into action. This operator precedence evaluates the operators present in
the expressions based on the priority. For example, multiplication has the highest priority
when compared to addition and subtraction.
Operator Description
This operator can be used with logical
expressions, boolean type variables, and
Logical NOT
relational variables, The Logical NOT
operator is denoted by the symbol “!”
These logical operators operate only on
Logical OR boolean variable types and the symbol
for this operator is “||”
We can combine many relational
operations using this operator and the
Logical AND
output will be of boolean type.
The “&&” is the symbol for logical AND
35. What is the role of the unary operator in Java?
This type of operator has only one operand and is mainly used to perform various operations
including negating an expression, either incrementing/ decrementing the value by one, and
invention on boolean values.
An example for the unary operator is given below:
class UnaryExample{
public static void main(String args[]){
int x=15;
System.out.println(x++);//15 (16)
System.out.println(++x);//17
System.out.println(x--);//12 (16)
System.out.println(--x);//15
}}
36. What is the difference between ++a and a++ increment operators?
++a is a prefix increment and a++ is the postfix increment. The prefix increment is used to
return the value after incrementing the present value. Whereas in postfix increment, the value
is returned before incrementing it.
Left Shift: This left shift is a bitwise operator in which bits are moved towards the left side
and zeros are placed at the rightmost places.
Example:
public class LeftShiftOperator {
public static void main(String[] args) {
int a=2;//
int i;
i=a<<1;//4
System.out.println("the value of a before left shift is: " +a);
System.out.println("the value of a after applying left shift is: " +i);
}
}
Output: 4
Right Shift: It is also of the bitwise operator in which bits are moved towards the right-hand
side and zeros are places at the leftmost places.
Example:
public class RightShiftOperator {
public static void main(String[] args) {
int a=2;
int i;
i=a>>1;
System.out.println("the value of a before right shfit is: " +a);
System.out.println("the value of a after applying right shfit is: " +i);
}
}
Output: 1
Bitwise operators are mainly used to work on bits and these operators continue to work on
bit-by-bit operations.
The following are the bitwise operators in Java, and they are:
Bitwise OR (A&B)
Bitwise AND (A|B)
Bitwise XOR (A^B)
Bitwise Complement (~A)
Left shift ( A<<2)
Right shift (A>>2)
Unsigned left shift ( <<<)
Unsigned right shift (>>>)
Ternary operator in Java is used to replace the if-else statement. The representation or the
syntax for the ternary operator is given as:
variable= (expression) ? expression true : expression false
Yes, Java allows us to save our Java file by .java only, we need to compile it by javac.java
and run it by Java class name.
For example:
class A{
public static void main(String args[]){
System.out.println("Hello Xx");
}
}
Java keywords are also called “Reserved keywords” that act as a key to a code. Keywords in
Java are predefined that cannot be used as an object name or variable. There are many
keywords in Java, and some of them are:
abstract
default
new
This
static
Extends and many more
There are four access specifiers present in Java, and they are:
1. Public: The methods, classes, and variables that are defined as the public can be
accessed by any class or method.
2. Private: The methods or classes which are declared as private can be accessible within
the same class only.
3. Protected: The variables, methods, and classes which are defined as private can be
accessed within the same class of the same package or by the subclass of the same
class.
4. Default: By default, all the classes, variables, and methods are of default scope. The
default is accessible within the package only.
The following are the advantages of packages in Java, and they are:
In Java control statements are divided into three types. They are:
Selection Statements
Iterative/looping Statements
Jump Statements.
A selection statement is mainly used to transfer program control to a specific flow based
upon the condition either true or false. These selection statements are also called conditional
statements.
Selection/Conditional statements in Java include:
If statement
If-else statement
Switch statements
The iterative statements in Java are also called looping statements, these statements are the
set of statements that repeat continuously until the condition for the termination is not met.
Looping/iterative statements in Java include:
For loop
While loop
Do-while loop
In Java, jump statements are mainly used to transfer control to another part of our program
depending on the condition. Moreover, these statements are used to jump directly to other
statements.
Break and Continue are the two jump statements present in Java.
49. Define for each loop in Java?
For-each is another kind of array traversing technique in Java which is the same as that of for
loop, while loop. It is most commonly used to iterate over a collection or an array such as
ArrayList. An example for for-each loop is as follows:
class ForEachPro{
public static void main(String args[]){
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12
12
14
44
50. What is the difference between a while loop and a do-while loop
In the case of a while loop the condition is tested first and then if the condition is true then
the loop continues if not it stops the execution. Whereas in the case of the do-while loop first
the condition is executed and at the end of the loop, the condition is tested.
The syntax for the while loop is as follows:
while(condition){
//code to be executed
}
Java comments are statements that are not executed by the interpreter and compiler. These
are used to provide information about the class, variables, methods, and any statements.
Comments are mainly used to hide program code for a specific time.
There are mainly three types of comments in Java, and they are:
Documentation comment
Multi-line comment
Single-line comment
Class
Object
Abstraction
Encapsulation
Inheritance
Polymorphism
In simple words, abstraction can be defined as hiding unnecessary data and showing or
executing necessary data. In technical terms, abstraction can be defined as hiding internal
processes and showing only the functionality.
Binding data and code together into a single unit are called encapsulation. The capsule is the
best example of encapsulation.
When an object of child class has the ability to acquire the properties of a parent class then it
is called inheritance. It is mainly used to acquire runtime polymorphism and also it provides
code reusability.
Polymorphism in Java provides a way to perform one task in different possible ways. To
achieve polymorphism in Java we use method overloading and method overriding. For
example, the shape is the task and various possible ways in shapes are triangles, rectangle,
circle, and so on.
58. What is the major difference between object-oriented language and object-based
language?
An object-based programming language provides the most effective way to follow all the
features of OOPs concepts except inheritance. VBScript and JavaScript are examples of
Object-based programming languages. Whereas Object-oriented programming language
supports all the features of OOPs concepts and examples of Object-oriented programming
language is Java, Python, and so on.
59. What will be an initial value for an object reference that is defined as an instance
variable?
It is a paradigm entirely based on objects having defined methods in the class to which it
belongs. This is mainly used to incorporate the advantages of reusability and modularity.
Objects are defined as instances of classes that interact with one another to design programs
and applications. The features of the object-oriented paradigm are as follows:
Java naming convention is a rule to be followed for naming your identifiers such as package,
variable, method, and constants. These conventions are supported by many Java
communities such as Netscape and Sun Microsystems and mostly all the fields of java
programming are given according to Java naming conventions.
A constructor is a special type of method with a block of code to initialize the state of an
object. A constructor is called only when the instance of the object is created. Every time in
Java object is created using the new keyword and by default, the constructor is called.
64. What all the rules must be followed while creating a constructor in Java?
The constructor should have the same name as its class name.
There is no explicit return type for a constructor.
In Java, a constructor cannot be synchronized, abstract, final, and static.
Default constructor
Parameterized constructor
66. Give examples for both a default constructor and a parameterized constructor?
Yes, the constructor will return the current or present instance of the class.
Yes, It is possible to overload a constructor by changing the number of arguments for each
constructor in a particular program or it is possible to overload a constructor by changing the
parameter data types.
No, We can not declare the constructor as final, if we declare it as final compiler throws a
“modified final not allowed” error.
71. Is there any Constructor class available in Java and what is its purpose of it?
Yes, there is a class called Constructor class available in Java. The purpose of the
Constructor class is to get the internal information of the constructor in the class. It is present
in java.lang.reflect package.
72. What is the use of a copy constructor in Java?
There is no copy constructor in Java, we can copy the values from one object to another
same as that of a copy constructor in C++. In Java, there are many ways to copy the values of
one object to another and they are:
In Java method is defined as a set of code that is represented by a name and can be invoked
at any point in a program with the help of the method name. Each and every method in the
program has its own name which is not the same as that of a class name.
Constructor Method
The constructor should have the same name as The method name is not the same as that
the class name of the class name
A constructor has no return type The method must have a return type
It can be invoked implicitly It can be invoked explicitly
The constructor is used to initialize the state of A method is used to expose the behavior
the object of an object
Default constructor can be provided by the The default method is not provided by
compiler the Java compiler
In Java method signature is given the specified format followed by the method name, type,
and order of its parameters. Exceptions are not considered as a part of the method signature.
return-type method name (parameter list)
{
//code
}
Keyword static in Java is mainly used for memory management and we can declare block,
variable, method, and nested class as static.
In Java, we can declare a variable as static, if we declare any variable as static the following
can be done, and they are:
A static variable can be mainly used to refer to all the common properties of objects.
Memory for the static variable is assigned only once in the class area at the time of
class loading
m1.display();
m2.display();
}
}
Output:
346 Pranaya Appmajix
222 Lilly Appmajix
If we declare a method as static, the following operations take place, and they are:
79. What are the cons observed if we declare a method as static in Java?
A static method cannot access non-static members and also cannot call the non-static
method directly.
This and super keywords cannot be used in the context of the static method as they are
non-static.
The main reason is that the object is not required to call for a static method so, if we declare
the main method as non-static we need to create an object first and then call the main()
method. In order to save memory, we declare the main method as static in Java.
Static block in Java is mainly used to initialize the static data members. The specialty of the
static block is that it is executed before the main method at the time of class loading.
An example of the static block is as follows:
Class Xx{
static{System.out.println("static block");
}
public static void main(String args[]){
System.out.println("Hello World");
}
}
Output:
static block
Hello World
Yes, we can execute the program in Java without the main method using a static block. It
was possible only till JDK 1.6 and from JDK 1.7 it is not possible to execute the program
without the main method in Java.
84. What happens if we remove the static modifier from the signature of the main() method?
As we know that the static context is suitable for only class, variable, and method, not for the
object. So the constructors are invoked only when an object is created, so there is no
possibility to declare the constructor as static in Java.
No, if we declare abstract methods as static it becomes a part of the class, and we can
directly call it which is not required. Calling an undefined method is unnecessary. Therefore
declaring an abstract method as static is not allowed.
87. Can we declare static methods and variables in the abstract class?
Yes, as we know that there is no need for an object to access the static block, therefore we
can access static methods and variables declared inside the abstract class by using the
abstract class name. Consider the following example.
abstract class Check
{
static int i = 113;
static void CheckMethod()
{
System.out.println("hi, how are you");
}
}
public class CheckClass extends Check
{
public static void main (String args[])
{
Check.CheckMethod();
System.out.println("i = "+Check.i);
}
}
Output:
hi, how are you
i = 113
The main use of this keyword is to refer to the current object in Java programming.
The following are the usage provided by this keyword in Java, and they are:
90. Can this keyword be used to refer to the current class instance variable?
Yes, this keyword is used to refer to the current class instance variable and it is also used to
initiate or invoke the current class constructor.
91. Which class is the superclass for all the classes in Java?
Singleton class can be defined as the class that consists of only one single instance. In this
class, all the methods and variables belong to only one instance. Singleton class is mainly
used in a situation where we need to limit the objects for a class.
In Java, we use inheritance mainly for two uses, and they are:
For code reusability
For method overriding
By using the Math.random() method we can generate random numbers in Java ranging from
0.1 to less than 1.0. Moreover, the random numbers can be generated by using the Random
class present in java. util package.
The main() method in Java doesn’t return any data because it is declared with a void return
type.
In Java, the package is defined as a collection of interfaces and classes that are bundled
together and related to each other. Usage of packages in the program will help developers to
group the code for proper re-use. In Java, packages are used by importing them into different
classes.
98. What is the reason why multiple inheritances are not supported in Java?
Java doesn’t support multiple inheritances in order to reduce the complexity and simplify the
language. An example of multiple inheritances in Java is given below:
class X{
void msg()
{
System.out.println("Hello");}
}
class Y{
void msg()
{
System.out.println("Welcome");}
}
class Z extends X,Y{//suppose if it were
public static void main(String args[]){
Z obj=new Z();
obj.msg();//Now which msg() method would be invoked?
}
}
Output:
Compile-time error
So, the above example shows that Java doesn’t support multiple inheritances.
In Java, main() method must be always public static to run any application or program
correctly. Suppose, if the main method is declared as private there will be no complications
but it will give a runtime error.
Yes, the classes present in Java can have multiple constructors with different parameters.
If a class in Java has multiple numbers methods with the same name and different
parameters, then it is called as method overloading. The main advantage of method
overloading is that it increases the readability score of a program.
There are two different ways to overload a method, and they are:
103. Write a program to demonstrate the method overloading by changing data types?
class Addition{
static int add(int x,int y)
{
return x+y;
}
static int add(int x,int y,int z)
{
return x+y+z;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(10,20));
System.out.println(Adder.add(10,20,30));
}}
Output:
30
60
class Addition{
static int add(int x, int y)
{
return x+y;
}
static double add(double x, double y)
{
return x+y;
}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(22,22));
System.out.println(Adder.add(12.5,12.5));
}}
Output:
44
25
105. Why method overloading is not possible only by changing the return type of method
only?
Ambiguity is the main reason why method overloading is not possible by changing the return
type of method only.
Yes, we can overload the main() method in Java by using method overloading but, JVM only
calls the main() method that receives string array as arguments only.
If the subclass in the program has the same method as declared in superclass then it is known
as method overriding.
Method overriding is used to achieve run-time polymorphism and also it is used to provide a
specific implementation for a method that is already given by its subclass.
109. What are the rules we need to follow during method overriding?
The method must have the same parameters as present in the parent class.
There must be an IS-A relationship which is called inheritance.
The method should have the name same as that of the class name.
No, a static method cannot be overridden, it is because a static method is bounded with a
class and an instance method is bounded with an object. So, the static belongs to the class
area whereas, the instance method belongs to the heap area.
Aggregation is built to represent the weak relationship whereas, the composition is built to
represent the strong relationship.
Pointer is a variable that mainly refers to the memory address. Java doesn’t support pointers
because they are complex to understand and unsecured.
Super keyword in Java is used to conjure immediate prompt parent class object. It is also
called a reference variable.
A Literal represents a value of a certain type where the type describes the behaviors of the
value. The different types of literals are:
Number literals
Character literals
Boolean literals
String literals
There are several integer literals as int, long, octal, hexadecimal etc. 10 is an example of a
decimal integer literal of type int. If a decimal integer literal is larger that the int, it is
declared to be of type long. A number can be made long by appending L or 1 to it. Negative
integers are preceded by the minus sign. These integers can also be expressed as octal or
hexadecimal. A leading 0 to the integer indicate that the number is an octal integer. For
example, 0987 is an octal integer. A leading 0x to the integer indicate that the number is a
hexadecimal integer, example 0xaf94 is a hexadecimal number.
Character literals are expressed by a single character enclosed within single quotes.
Characters are stored as Unicode characters.
Escape Meaning
\n Newline
\t Tab
\b Backspace
\r Carriage
\f return
\\ Form feed
Backslash
A string is a combination of characters. string literals are a set of characters that are enclosed
within double quotes. As they are real objects, it is possible to concatenate, modify and test
them. For example, “This is a test string” represents a string. Strings can contain character
constants and Unicode characters.
The variable is the basic unit of storage in a java program. A variable is defined by the
combination of an identifier, a type, and an optional initialize. All variables must be declared
before they can be used. The basic form of a variable declaration is shown have
Type identifier [= value],[,identifier [=value]]
The type in one of java’s atomic types. The identifier is the name of the variable. For
example
int a,b,c;
int d=3,c=5;
Variable are locations in the memory that can hold values. Java has three kinds of
variable namely,
Instance variable
Local variable
Class variable
Local variables are used inside blocks as counts or in methods as temporary variables. Once
the block or the method is executed, the variable ceases to exist. Instance variable are used to
define attributes or the state of a particular object. These are used to store information
needed by multiple methods in the objects.
Integers are used for storing integer values. There are four kinds of integer types in Java.
Each of these can hold a different range of values. The values can either be positive or
negative
Type Size
byte 8 bits
short 16 bits
int 32 bits
long 64 its
Type Size
float 32 bits
double 64 its
128. What are the difference between static variable and instance variable?
The data or variables, defined within a class are called instance variables.
Instance variables declared as static are, essentially, global variables. When objects of its
class are declared, no copy of a static variable is made.
An array is an object that stores a list of items. Each slot in an array holds individual
elements. An array should be of a single type, comprising of integers, strings and so on. To
create an array, a variable to hold the array is declared, and a new object is created and
assigned to it.
The conditional operator is otherwise known as the ternary operator and is considered to be
an alternative to the if else construct. It returns a value and the syntax is:
<test> ? <pass> : <fail>
Where,<test> is the condition to be tested. If the condition returns true then the statement
given in <pass> will be executed. Otherwise, the statement given in <fail> will be executed.
In certain languages like C++, dynamically allocated objects must be manually released by
use of a delete operator. In Java deallocation happens automatically. The technique that
accomplishes this is called garbage collection.
Encapsulation
Inheritance
Polymorphism
A class defines the shape and behavior of an object and is a template for multiple
objects with similar features.
(OR)
A class is a new data type. Once defined, this new type can be used to create objects
of that type. Thus, a class is a template for an object, and an object is an instance of a class
Abstract classes are classes from which instances are usually not created. It is basically used
to contain common characteristics of its derived classes. Abstract classes are generally
higher up the hierarchy and act as super classes. Methods can also be declared as abstract.
This implies that non-abstract classes must implement these methods
An inner class is a nested class whose instance exists within an instance of its enclosing class
and has direct access to the instance members of its enclosing instance
An inner class is a nested class whose instance exists within an instance of its enclosing class
and has direct access to the instance members of its enclosing instance
class <EnclosingClass>
{
class <InnerClass>
{
}
}
A constructor initializes an object immediately upon creation. It has the same name as
the class in which it resides and is syntactically similar to a method. Once defined, the
constructor is automatically called immediately after the object is created, before
the new operator completes.
In Java it is possible to define two or more methods within the same class that share
the same name, as long as their parameter declarations are different. When this is the case,
the methods are said to be overload, and the process is referred to as method overloading.
143.Define method?
Methods are functions that operates on instances of classes in which they are defined.
Objects can communicate with each other using methods and can call methods in other
classes. Just as there are class and instance variable, there are class and instance methods.
Instance methods apply and operate on an instance of the class while class methods operate
on the class.
The class can be declared as final, if instances or subclasses are not to be created.
The variables are declared as final, value of the variable must be provided at the
time of declaration.
The Method can be declared as final indicating that they cannot be overridden by
subclasses.
Static methods and variables can be used independently of any object. To do so, you need
only specify the name of their class following by the dot operator.
147.What is a package?
Packages contain a set of classes in order to ensure that class names are unique. Packages are
containers for classes that are used to compartmentalize the class name space. Packages are
stored in a hierarchical manner and are explicitly imported into new class definition. A
period is used as separator to enable this.
Classes external to a program be imported before they can be used. To import a class
the import keyword should be used as given below
import <classname>
The classes in Java are arranged in hierarchical order. The Java library consists of a number
of package. These package contain a set of related classes. The whole path of the class must
be specified to import a class from the Java library, For instance, to import the Data class
from the util package use the following code.
import java.util.Date;
It is also possible to import all classes that belong to a package using the * symbol.
150.Define an exception
The try and catch clause is used to handle an exception explicitly. The advantages of using
the try and catch clause are that, it fixes the error and prevents the program from terminating
abruptly.
152.What is use of ‘throw statement’ give an example? (or) state the purpose of the throw
statement.
Whenever a program does not want to handle exception using the try block, it can use the
throws clause. The throws clause is responsible to handle the different types of exceptions
generated by the program. This clause usually contains a list of the various types of
exception that are likely to occur in the program.
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-
zero
ArrayIndexOutOfBoundsException
Array index is out-of-bounds
IllegalThreadStateException
Requested operation not compatible
with current thread state
This occurs when two threads have a circular dependency on a pair of synchronized objects.
For example, suppose one thread enters the monitor on object X and another thread enters
the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will
block as expected. However, if the thread in Y, in turn, tries to call any synchronized method
on X, the thread waits forever, because to access X, it would have to release its own lock on
Y so that the first thread could complete.
155.Define multithreading?
A thread is a line of execution. It is the smallest unit of code that is dispatched by the
scheduler. Thus, a process can contain multiple threads to execute its different sections. This
is called multithread.
A thread is a line of execution. It is the smallest unit of code that is dispatched by the
scheduler. Thus, a process can contain multiple threads to execute its different sections. This
is called multithread.
There are four states associated with a thread namely – new, runnable, dead, blocked
Two or more threads accessing the same data simultaneously may lead to loss of data
integrity. For example, when two people access a savings account, it is possible that one
person may overdraw and the cheque may bounce. The importance of updating of the pass
book can be well understood in this case.