0% found this document useful (0 votes)
8 views

Java

Java is an object-oriented, platform-independent programming language developed by James Gosling in 1991, initially called Oak. It features robust memory management, multithreading, and security, making it suitable for various applications, including embedded systems. Key concepts include bytecode, the Java Virtual Machine (JVM), data types, variable scope, and garbage collection, which simplifies memory management.

Uploaded by

wgamerz247
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Java

Java is an object-oriented, platform-independent programming language developed by James Gosling in 1991, initially called Oak. It features robust memory management, multithreading, and security, making it suitable for various applications, including embedded systems. Key concepts include bytecode, the Java Virtual Machine (JVM), data types, variable scope, and garbage collection, which simplifies memory management.

Uploaded by

wgamerz247
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

JAVA

1.​ Short note on Java


○​ Java is an Object Oriented Programming Language.
○​ It is a Platform Independent Language
○​ It is a High level & Secure Programming Language.
○​ The primary need for the development of Java was the necessity of a
platform independent language which could be used to create software for
embedded systems.
○​ Applications & Applets are programs that can be created with Java
○​ It Was Developed by James Gosling at Sun Microsystems Inc In 1991.
○​ It was Initially Called Oak But Renamed as JAVA in 1995.

2.​ What is Byte Code


○​ It is a Set Of Instructions which are designed to be executed by the Java
run time system called the Java Virtual Machine (JVM). Thus the JVM is
the interpreter for the bytecode. The bytecode also makes the Java run
time system execute programs faster.

3.​ Define JVM


○​ JVM is the interpreter for the bytecode
○​ Only the JVM needs to be implemented for each platform on which the
Java programs are to be run.
○​ JVM(Java Virtual Machine) acts as a run-time engine to run Java
applications.
○​ The execution of a Java program is under the control of the JVM, therefore
it makes the program secure and ensures that no side effects outside the
system are generated.
○​ JVM is the one that actually calls the main method present in a Java code.
○​ JVM is a part of JRE(Java Runtime Environment).

4.​ Features of Java / Java Buzzwords (ez confirm qsn)


○​ Simple - Java was designed to be easy to learn and effective to use. With
prior programming experience, it is not difficult to master Java. It inherits
the syntax of C and C++ & many of the object features of C++ thus making
users master Java with very little effort.
○​ Object Oriented - The object model in Java is simple and easy to extend.
The simple types, like integers, are kept as high performance non
objects.All program code & data reside within objects & classes. It supports
all Object Oriented concepts such as :
■​ Inheritance
■​ Polymorphism
■​ Abstraction
■​ Encapsulation
○​ Robust - Robustness is the capacity of a computer system to handle the
errors during execution and manage the incorrect input of data. The ability
to create robust programs was given a very high priority during the design
of Java. Java is a strictly typed language and restricts the programmer in a
few key areas. It checks the program code at compile time as well as at run
time. It manages memory allocation & deallocation on its own unlike C /
C++. Java provides object oriented exception handling.
○​ Multithreaded - Java was designed to meet the real world requirement of
creating interactive networked programs. Therefore to accomplish this,
Java supports multithreading. Multithreaded programming allows you to
write programs that can do many things simultaneously.
○​ Architecture Neutral - Java & JVM has been designed in such a way that
enables the programs to run in spite of severe environmental changes
such as Hardware upgradation or any changes in core system resources.
○​ Interpreted - Output of Java compiler is the bytecode which is platform
independent which can be interpreted by any system which provides a
JVM
○​ Distributed - Java handles TCP/IP protocols. Accessing a resource using a
URL is similar to accessing a file. Java has a package called Remote
Method Invocation (RMI) which brings a very high level of abstraction to
client/server programming.
○​ Dynamic - Java programs have the capability to carry a sufficient amount of
run time type information. This information can be used to verify and
resolve accesses to the objects at run time. This makes it possible to
dynamically link code in a safe manner.
○​ Security - Java provides security against both these attacks by providing a
firewall between the network application and the user’s personal computer.
This ability to maintain the security of the user’s computer is considered to
be one of the most important aspects of Java.
○​ Privacy - The execution of a Java program is under the control of the Java
Virtual Machine, therefore it makes the program secure and ensures that
no side effects outside the system are generated. Safety is also enhanced
by the features provided in the language itself.

5.​ Types of Comments


○​ Single line comments :
■​ These begin with the symbol // and end at the end of line.
■​ Such types of comments do not have an ending symbol
○​ Multiline comments :
■​ These begin with a /* and end with */.
■​ Anything that is written between these two comment symbols is a
comment and is ignored by the compiler.
■​ As the name suggests, these comments can be several lines long.
○​ Documentation comments :
■​ These begin with /** and end with */.
■​ This type of comment is used to produce and HTML file that
documents the program.

6.​ What are White Spaces in Java?


○​ In Java, whitespace is a character that represents the absence of character
and does not represent any visible mark.
○​ It is used to separate tokens in a Java program and improve its readability.
○​ Whitespace includes space, tab, and newline. Java ignores extra
whitespaces.
○​ Note : There has to be at least one whitespace character between each
token

7.​ Define Identifiers


○​ Identifiers are names given to classes, methods, variables.
○​ An identifier can be a combination of uppercase and lowercase characters,
numbers, the underscore and the dollar sign.
○​ But they cannot begin with a number.
○​ Java is case sensitive so MAX is different from max.

8.​ List the Data types in Java


Data types in Java are classified into:
○​ Primitive Data Types ( Predefined )
■​ Integer
●​ byte - Smallest integer type . Signed 8 bit type. Range from
-128 to 127.
●​ short - Signed 16 bit type.
●​ int - Most Commonly used integer data type. Most Versatile &
Efficient data type among integers. Signed 32 bit type.
●​ long - Signed 64 bit type. Used when int data type is not large
enough.
■​ Floating point types
●​ float - Represent single precision value. Uses 32 bits
●​ double - Represent double precision value.Uses 64 bits of
storage. Faster than float ( single precision )
■​ Characters
●​ char - Unicode is used to represent char. Unicode defines a
fully international character set that can represent all of the
characters found in all human languages. char is not treated as
integer in Java unlike C / C++. Uses 16 bits
■​ Boolean
●​ This is a special type for representing true/false values. This is
the type returned by all relational operators.
○​ Non - Primitive Data Types ( User Defined )
■​ Class & Objects
●​ A class in Java is a user defined data type i.e. it is created by
the user. It acts as a template to the data which consists of
member variables and methods.
●​ An object is the variable of the class, which can access the
elements of class i.e. methods and variables.
■​ Strings
●​ A string represents a sequence of characters
■​ Array
●​ An array is a data type which can store multiple homogenous
variables i.e., variables of the same type in a sequence. They
are stored in an indexed manner starting with index 0. The
variables can be either primitive or non-primitive data types.
■​ Interfaces
●​ An interface is similar to a class however the only difference is
that its methods are abstract by default i.e. they do not have
body. An interface has only the final variables and method
declarations. It is also called a fully abstract clas
9.​ Define Variables
○​ A variable is the basic unit of storage in a Java program. All variables must
be declared before they are used.
○​ The general form of declaring a variable is :
type identifier [=value][,identifier[=value]....];
○​ type is one of Java’s atomic type or the name of a class or an interface and
identifier is the name of the variable.
○​ Variables can be initialised at the time of declaration by giving an equal to
sign and a value.

10.​ Define the Scope of a Variable


○​ Variables can be declared in any block. A block defines the Scope
○​ Variable scope determines where a variable can be accessed.
○​ Variables declared inside a block are only visible within that block & it is
protected from unauthorised access & modification.
○​ Scope rules provide the basis of encapsulation.
○​ Scopes can be nested.
○​ Outer scope objects are visible to inner scopes, but not vice versa.
○​ Two major scopes: method and class level.
■​ Method scope: Variables only accessible within the method.
■​ Class level scope: Variables accessible across all methods in the
class.

11.​ Explain Automatic type conversion


○​ When one type of data is assigned to another type of variable, an
automatic conversion takes place when :
■​ the two types are compatible
■​ The destination type is larger than the source type.
○​ When this condition is satisfied java performs “Implicit Conversion” or
known as “Widening Conversion”
○​ Like byte can be converted to int but numeric data types can’t be converted
to char or boolean since it is not compatible.

12.​ Define Typecasting


○​ In a situation like where you want to convert an int data type to a byte,
automatic conversion is not possible since a byte is smaller than int.
○​ In such situations you have to use a cast. A cast is an explicit type
conversion.
○​ It takes the following form :
(target-type) value
the target-type specifies the desired type to convert the specified value to.
○​ eg.
int a;
byte b;
b = (byte) a;

13.​ Describe with example Arrays


○​ An array is a data type which can store multiple homogenous variables i.e.,
variables of the same type in a sequence.
○​ They are stored in an indexed manner starting with index 0.
○​ Arrays are dynamically allocated in Java.
○​ Arrays in Java have a fixed size, set at the time of declaration.
○​ The variables can be either primitive or non-primitive data types.
○​ They are of two types:
■​ One Dimensional Array - A one dimensional array is a list of like
typed variables. They are used to store a collection of elements of
the same data type in a linear sequence.
■​ The general form for creating a one dimensional array is :
type var-name[ ] ;
Here type is the base type of the array which determines the
datatype of the elements of the array. var-name is an array variable.
Ex.
public class Main {​
​ public static void main(String[ ] args) {
​ ​ Int[ ] numbers = {1, 2, 3, 4, 5};
​ ​ System.out.println(“First Element: “ + numbers[0]);​
//Output: 1
​ ​ System.out.println(“Second Element: “ + numbers[1]);
//Output: 2
}
}

Output:
1
2
■​ Multidimensional Array - Multidimensional array is an array of arrays.
It is useful when you want to store data as a tabular form, like a table
with rows and columns. Accessed using multiple indices, one for
each dimension.
Syntax : Datatype variable_name[ ][ ];
Ex.
public class Main {
public static void main(String[] args) {
// Declaration and initialization of an integer array
int[ ][ ] matrix = {​ {1,2}, {4,5}​ };
System.out.println(matrix[1][1]);​
}
​ ​ ​ }
​ ​ ​
​ ​ ​ Output:
5

14.​ Boolean Operators


○​ These operators operate only on boolean operands. All the binary logical
operators combine two boolean values to form a resultant boolean value
.
15.​ Bitwise Operators
○​ Bitwise operators can be applied to the integer data types. It works on
individual bits of operands. Java uses 2's complement encoding method for
signed integers
○​ Bitwise NOT ( ~ ) -> Also called as the bitwise complement operator and it
inverts all of the bits of its operand.
○​ Bitwise AND ( & ) -> Produces 1 bit if both the operands are also 1 and a 0
bit otherwise.
○​ Bitwise OR ( | ) -> In bitwise OR if either of the bits in the operands is a 1,
then the resultant bit is 1.
○​ Bitwise XOR ( ^ ) -> If exactly one operand is 1, then the result is a 1,
otherwise the result is a 0.
○​ Left Shift( << ) -> The left shift operator shifts all of the bits in a value to the
left a specified number of times. The general form of the left shift operator
is :
value << num
where num specifies the number of positions to the left shift the value of
value.
○​ Right Shift( >> ) ->:This operator shifts all of the bits in a value to the right
the specified number of times. The general form of right shift is :
value >> num
where num specifies the number of positions to right shift the value in
value.
○​ The Unsigned Right Shift : In the right shift operator, the sign of the
numbers is preserved. However in certain situations, especially when you
are not shifting numeric values you may not want the sign extension to take
place.For this purpose you make use of the unsigned right shift operator
>>> which always shifts zeroes into the high order bit. This is known as an
unsigned shift.

Strings
16.​ Explain in detail String Class
17.​ Describe various constructors of String Class
18.​ List out the methods of String Class
19.​ Write any 4 StringBuffer methods
20.​ Give three different ways of creating a String object
21.​ Explain String Concatenation
22.​ Difference between string and stringbuilder

OOPs
23.​ What is Garbage Collection? (Bht imp qsn)
○​ Unlike C++, Java automatically handles deallocation of dynamically
allocated objects.
○​ Java employs a technique called garbage collection for memory
management.
○​ When no references to an object exist, it's assumed to be no longer
needed.
○​ This allows developers to focus on writing code without worrying about
memory management
○​ The Java Virtual Machine (JVM) is responsible for garbage collection.
○​ The JVM keeps track of all the objects that are created in the heap, and it
automatically reclaims the memory occupied by objects that are no longer
needed.
○​ Memory occupied by such objects is reclaimed by the garbage collector.
○​ No explicit need to destroy objects as in C++.
○​ Garbage collection occurs occasionally during program execution, not
immediately when objects are no longer used.

24.​ Short note on finalise() method


○​ finalize() method in Java allows specific actions to be performed when an
object is about to be destroyed.
○​ It's used for releasing resources like file handles held by the object.
○​ Defined with the syntax:
protected void finalize()
{ /* finalization code */ }
○​ The protected keyword prevents access to finalize() by code defined
outside its class.
○​ finalize() is called by the Java runtime prior to garbage collection.
○​ It's not guaranteed to be called when an object goes out of scope.
○​ The method should not be relied upon for normal program operation, as its
execution timing is unpredictable.
○​ Programs should have alternative means for releasing system resources
used by objects.
25.​ Explain Class
○​ A class is a fundamental concept in Java, defining the structure and
behaviour of objects. It defines a template or blueprint for objects.
○​ It encapsulates data and methods that operate on that data.
○​ Declaration format: class classname { ... }.
○​ The variables defined within a class are called instance variables. Dot (.)
operator is used to access instance variables.
○​ Class contains instance variables (data) and methods (code), called
members of the class.
○​ Each instance of a class has its own copy of instance variables, making
data unique per object.
○​ Classes do not necessarily need a main() method unless they are the entry
point of the program.

26.​ What are Nested Class


○​ It is possible to define a class within another class; such classes are known
as nested classes.
○​ A nested class can have access to the members of the class in which it is
nested (including private members). However, the enclosing class does not
have access to the members of the nested class.
○​ There are two types of nested classes:
■​ Static Nested Classes: nested classes that are declared static are
called static nested classes
■​ Non Static Nested Classes: nested classes that are non-static are
called inner classes or non-static nested classes

27.​ Brief about Inner Class


○​ Nested classes that are non-static are called inner classes or non-static
nested classes.It has access to all the members of its outer class and can
refer to them directly. Thus an inner class is fully within the scope of its
enclosing class.
Class Outer {
int outer_var = 69;
void test() {
Inner obj = new Inner();
obj.display();
}
class Inner {
void display() {
System.out.println(“Display member variable of outer : “ +
outer_var);
}
}
}
class InnerOuter {
public static void main(String args[]) {
Outer abc = new Outer();
abc.test();
}
}

Output:
Display member variable of outer : 69

28.​ What are Access Specifiers?


○​ By introducing access control you can control what parts of the program
can access the members of a class and thus prevent misuse. An access
specifier determines how a member can be accessed
○​ Access control in Java is managed through access specifiers: public,
private, protected, and default.
○​ An access specifier determines how a member can be accessed
○​ Public members can be accessed by any code in the program.
○​ Private members are accessible only within the class where they are
declared.
○​ Protected members are accessible within package and outside the
package but through inheritance only.
○​ Default access allows access within the same package but not outside of it.
○​ The main() method is declared as public because it is called by code
outside the program.

29.​ Define Methods


○​ Methods contain code that operates on class data.
○​ General form: type name(parameter-list) { body }.
○​ type specifies return data type; void if no return.
○​ Parameters receive values passed to the method.
○​ Methods define class interfaces, hiding internal data.
○​ Directly access instance variables within methods.

30.​ Constructors
○​ Constructor is a special method that initialises objects upon creation.
○​ Must have the same name as the class.
○​ Has no return type, not even void.
○​ A Java constructor cannot be abstract, static, final, and synchronised
○​ Automatically invoked when an object of the class is created.
○​ Constructor is of two types :
■​ Default Constructor - A constructor is called a "Default Constructor"
when it doesn't have any parameter. Java provides a default
constructor if not explicitly defined. Default constructor is overridden
when a custom constructor is defined.
■​ Parameterized Constructor - Constructor with arguments is called a
parameterized constructor. Allow different initial values for objects.
Set values specified in parameters during object creation.
○​ Ex.
class Box {
int width, height, depth;
// constructor used when no dimensions specified
Box()
{ width = height = depth = 0; }
// constructor used when all dimensions specified
Box(int w, int h, int d)
{
​ width = w;
​ height = h;
​ depth = d;
}
int volume()
{ return width * height * depth; }
}
public class Test {
public static void main(String args[])
{
​ Box mybox1 = new Box();
​ Box mybox2 = new Box(10, 20, 15);
​ int vol;
​ vol = mybox1.volume();
​ System.out.println("Volume of mybox1 is " + vol);
​ vol = mybox2.volume();
​ System.out.println("Volume of mybox2 is " + vol);
}
}
​ ​
​ ​ Output:
​ ​ Volume of mybox1 is 0
​ ​ Volume of mybox2 is 3000

31.​ What is the use of this keyword


○​ this keyword is a reference variable. Refers to the current object in a
method.
○​ this can also be used to:
■​ Invoke current class constructor
■​ Invoke current class method
■​ Return the current class object
■​ Pass an argument in the method call
■​ Pass an argument in the constructor call
○​ Using “this” reference can improve code readability and reduce naming
conflicts
○​ Useful for accessing instance variables or invoking other methods of the
current object.
○​ Use this keyword to refer directly to the object and resolve namespace
collisions between instance variables and local variables.

32.​ Explain static keyword


○​ The "static" keyword in Java is used to define class members that are
independent of any object of the class.
○​ Static members can be accessed without creating objects and before any
objects of the class are created.
○​ The static keyword can be used with class, variable, method, and block
○​ The "main()" method is declared as static because it must be called before
any object exists.
○​ Instance variables declared as static are like global variables, shared
among all instances of the class.
○​ Static methods have restrictions:
■​ They can only call other static methods.
■​ They can only access static data; it's illegal to refer to any instance
variable inside a static method.
■​ They cannot refer to "this" or "super" in any way.
○​ Outside the class in which they are declared, static methods and variables
can be used independently by referencing the class name followed by the
method or variable name.
○​ Ex.
package Demo;
import java.util.*;
public class StaticBlockDemo
{
​ //static variable
​ static int j = 10;
​ static int n;
​ //static block
​ static
​ {
​ System.out.println ("Static block initialized.");
​ n = j * 8;
​ }
​ public static void main (String[]args)
​ {
​ System.out.println ("Inside main method");
​ System.out.println ("Value of j : " + j);
​ System.out.println ("Value of n : " + n);
​ }
}

Output:
Static block initialized
Inside main method
Value of j : 10
Value of n : 80

33.​ Difference between static & final keyword in Java


○​ The static keyword always fixed the memory which means that it will be
located only once in the program whereas the final keyword always fixed
the value which means it makes variable values constant.

34.​ Call by Value & Call by Reference


○​ In call by value, the value of an argument is copied into the formal
parameter of the subroutine. Changes made to parameters don't affect the
argument.
○​ In call by reference, a reference to an argument is passed to the
parameter. Changes made to parameters affect the argument.
○​ Java uses both call by value and call by reference.
○​ Simple types are passed by value in Java, so changes made to parameters
don't affect the argument's value.
○​ Objects are passed as references in Java, meaning changes made to
objects within methods affect the object used as an argument.

35.​ Define Recursion


○​ Java supports recursion, where a method calls itself.
○​ Recursion is a powerful technique, but it requires an exit condition to
prevent infinite looping.
○​ Without an exit condition, recursive methods will keep calling themselves
indefinitely.
○​ Just like in C programming, Java recursive methods need an if statement
to enforce a base case where the recursion stops.
○​ This base case ensures the method eventually returns, preventing infinite
recursion.

36.​ OOP Principles


○​ These are the four main principles of the object-oriented programming
paradigm.
○​ Abstraction - Abstraction is a process of hiding the implementation details
and showing only functionality to the user. In Java, we can achieve
abstraction in two ways: abstract class (0 to 100%) and interface (100%).
The keyword abstract can be applied to classes and methods. abstract and
final or static can never be together.
○​ Inheritance - Inheritance is a mechanism in which one object acquires all
the states and behaviors of a parent object. Inheritance uses a parent-child
relationship (IS-A relationship). Types of Inheritances:
■​ Single
■​ Multilevel
■​ Hierarchical
○​ Encapsulation - Encapsulation is a process of wrapping code and data
together into a single unit. This can be achieved by using private access
modifiers that can’t be accessed by anything outside the class. In order to
access private states safely, we have to provide public getter and setter
methods.
○​ Polymorphism - Polymorphism is the ability of an entity to take several
forms. In object-oriented programming, it refers to the ability of an object
(or a reference to an object) to take different forms of objects.
Polymorphism is of two types :
■​ Static polymorphism / compile-time polymorphism / Early binding
■​ Dynamic polymorphism / Run-time polymorphism / Late binding

37.​ Explain Abstraction


○​ Data abstraction is the way to create complex data types and expose only
meaningful operations to interact with the data type, whereas hiding all the
implementation details from outside works.
○​ The benefit of this approach involves the capability of improving the
implementation over time.
○​ It reduces the complexity of viewing things and increases the readability of
the code.
○​ It helps to increase the security of an application or program as only
important details are provided to the user.
○​ In Java, we can achieve abstraction in two ways: abstract class (0 to
100%) and interface (100%).

38.​ What is Abstract Class & methods ? Explain with example


○​ A class that is declared by using the abstract keyword is called an abstract
class in java.
○​ It is always created as a superclass next to the interface in the object
inheritance hierarchy for implementing common operations from the
interface.
○​ An abstract class may or may not have abstract methods. But if a class
contains an abstract method then it must be declared as abstract.
○​ If a class is declared as abstract it cannot be instantiated violation leads to
compile-time Error.
○​ The subclass of an abstract class should override all abstract methods
○​ A method that does not have a body is called an abstract method in Java.
If a class contains an abstract method, then it must be declared as
abstract.
○​ Abstract methods are not allowed to be declared as static, final or private.
○​ Ex.
abstract class Bike{
​ abstract void run();
}
class Honda4 extends Bike{
​ void run()
{​
System.out.println("Running safely");
}
​ public static void main(String args[]){
​ ​ Bike obj = new Honda4();
​ ​ obj.run();
​ }
}
Output:
Running safely

39.​ Difference Between Interface and Abstract Class in Java


Interfaces Abstract Class
The interface is a fully un-implemented An abstract class is a partially
class used for declaring a set of implemented class which implements
operations of an object. some of the operations of the object
those are declared in its interface.
The interface supports Multiple does not support Multiple Inheritance.
Inheritance.
doesn’t contain Data Members. contains Data Members.
doesn’t contain Constructors. contains Constructors.
cannot have access modifiers, by can have access modifiers for the
default, everything is assumed as subs, functions, and properties.
public.
Members of the interface cannot be Only a complete member of the
Static. abstract class can be Static.

40.​ What is Inheritance?


○​ Inheritance is an integral part of Java OOPs which lets the properties of
one class be inherited by the other. For example, a child inherits the traits
of his/her parents.
○​ In Java, Inheritance is done using the “extends” keyword.
○​ The class whose features are inherited is known as a superclass. The
class from which the subclass is derived is called a superclass (also a base
class or a parent class).
○​ The class that inherits the other class is known as a subclass(or a derived
class, extended class, or child class). The subclass can add its own fields
and methods in addition to the superclass fields and methods.
○​ Types of Inheritance in Java:
■​ Single Inheritance
■​ Multilevel Inheritance
■​ Hierarchical Inheritance
○​ Multiple Inheritance is not supported in Java
○​ The most important use is the reusability of code. The code that is present
in the parent class doesn’t need to be written again in the child class. To
achieve runtime polymorphism through method overriding.
○​ It increases the maintenance of the Application and reduces application
development time.

41.​ Explain types of Inheritance


○​ Single Inheritance - Single Inheritance means creating a subclass to
extend only one superclass at a time. In the diagram given below, class B
inherits class A, so there is single inheritance.
Ex.
package Demo;
class A
{
​ int returnSum(int i, int j)
​ {
​ ​ return i + j;
​ }
}
class B extends A
{
​ void display ()
​ {
​ ​ int result = returnSum(10, 20);
​ ​ System.out.println (result);
​ }
}
public class SingleInheritance
{
​ public static void main (String args[])
​ {
​ ​ B b1 = new B ();
​ ​ b1.display ();
​ ​ b1 = null;
​ }
}

Output: 30
○​ Multilevel Inheritance - Creating a subclass (derived class) indirectly to the
superclass is known as multilevel inheritance. As you can see below in the
diagram, class C inherits class B which again inherits class A, so there is a
multilevel inheritance.
package Demo;
class SampleA
{
​ void f1 ()
​ {
​ System.out.println ("class A f1()");
​ }
}
class SampleB extends SampleA
{
​ void f2 ()
​ {
​ System.out.println ("class B f2()");
​ }
}
class SampleC extends SampleB
{
​ void f3 ()
​ {
​ System.out.println ("class C f3()");
​ }
}
public class MultilevelInheritance
{
​ public static void main (String srgs[])
​ {
​ SampleC a1 = new SampleC ();
​ a1.f1 ();
​ a1.f2 ();
​ a1.f3 ();
​ a1 = null;
​ }
}

Output:
class A f1()
class B f2()
class C f3()
○​ Hierarchical Inheritance - When two or more classes inherit a single class,
it is known as hierarchical inheritance. In the diagram given below, the B
and C classes inherit class A, so there is hierarchical inheritance.

package Demo;
class one
{
​ public void print_hello()
​ {
​ System.out.println("Hello");
​ }
}
class two extends one
{
​ public void print_world()
​ {
​ System.out.println("World");
​ }
}
class three extends one
{
​ public void printHW()
{
​ System.out.println("Hello World");
}
}
public class HierarchicalInheritance
{
​ public static void main(String[] args)
​ {
​ three g = new three();
​ g.print_hello();
​ two t = new two();
​ t.print_world();
​ g.printHW();
​ }
}

Output:
Hello
World
Hello World

42.​ Explain super keyword


○​ The super keyword is similar to this keyword. The keyword super can be
used to access any data member or method of the parent class. The super
keyword can be used at the variable, method, and constructor levels.
○​ Following are the scenarios where the super keyword is used:
■​ To access the superclass variable from a subclass.
■​ To access the superclass methods from a subclass.
■​ To access the superclass constructor from a subclass.
○​ Syntax of super(): super. <method_name> ();
○​ Just as this() must be the first element in a constructor that calls another
constructor in the same class, super() must be the first element in a
constructor that calls a constructor in its superclass.
○​ Ex.
package Demo;
class Father
{
​ int bank_balance = 500000;
}
class Daughter extends Father
{
​ int bank_balance = 300000;
​ public void displayBalance ()
​ {
​ ​ System.out.println ("Bank Balance: " + super.bank_balance);
​ }
}
public class Inheritance
{
​ public static void main (String[]args)
​ {
​ ​ Daughter d = new Daughter ();
​ ​ d.displayBalance ();
​ }
}

Output:
Bank Balance: 500000

43.​ Explain Encapsulation in Java


○​ The meaning of Encapsulation is to make sure that “sensitive” data is
hidden from users. Encapsulation is defined as the wrapping up of data
under a single unit. It is the mechanism that binds together code and the
data it manipulates
○​ Need for Encapsulation
■​ Better control of class attributes and methods.
■​ Encapsulation helps us to keep related fields and methods together,
which makes our code cleaner and easy to read.
■​ Helps us to achieve a loose couple.
■​ An object exposes its behavior by means of public methods or
functions.
■​ Increased security of data.
○​ To achieve encapsulation in Java, you need to:
■​ declare class variables/attributes as private
■​ provide public getter and setter methods to access and update the
value of a private variable
○​ The get method returns the variable value, and the set method sets the
value.
○​ Ex.
public class EncapsulationDemo
{
​ private String Name;
​ private int Age;
​ public int getAge()
​ {
​ ​ return Age;
​ }
​ public String getName()
​ {
​ ​ return Name;
​ }
​ public void setAge(int newAge)
​ {
​ ​ Age = newAge;
​ }
​ public void setName(String newName)
​ {
​ ​ Name = newName;
​ }
​ public static void main(String[ ] args)
​ {
​ EncapsulationDemo obj = new EncapsulationDemo();
​ obj.setName("Harsh");
​ obj.setAge(19);
​ System.out.println ("Student's Name: " + obj.getName());
​ System.out.println ("Student's Age: " + obj.getAge());
​ }
}

Output:
Student’s Name: Harsh
Student’s Age: 19

44.​ Difference Between Data Hiding and Encapsulation in Java


○​ Data hiding only hides class data components, whereas data
encapsulation hides class data parts and private methods.
○​ Data hiding focuses more on data security and data encapsulation focuses
more on hiding the complexity of the system.

45.​ What is Polymorphism


○​ Polymorphism is the ability of an entity to take several forms. In
object-oriented programming, it refers to the ability of an object (or a
reference to an object) to take different forms of objects.
○​ Polymorphism allows us to create consistent code.
○​ It encourages ‘extendibility’ which means an object or a class can have its
uses extended.
○​ Polymorphism makes software applications a third-party independent
applications.
○​ It decreases maintenance support and makes the application more
dynamic.
○​ Types of Polymorphism is of two types
■​ Static polymorphism / compile-time polymorphism / Early binding -
●​ A polymorphism that is resolved during compile time is known
as compile-time polymorphism.
●​ Static Polymorphism is achieved by using method Overloading
■​ Dynamic polymorphism / Run-time polymorphism / Late binding -
●​ A polymorphism that is resolved during run time is known as
dynamic polymorphism.
●​ Dynamic Polymorphism is achieved by using method
overriding.

​ ​
○​ Advantages of Polymorphism
■​ More flexible and reusable code.
■​ The single variable name can be used to store variables of multiple
data types.
■​ Faster and efficient code at Runtime.
■​ Code that is protected from extension by other classes.
■​ More dynamic code at runtime.

46.​ What is Method Overriding


○​ If the same method is defined in both the superclass and the subclass,
then the method of the subclass class overrides the method of the
superclass. This is known as method overriding.
○​ The method must have the same name as in the parent class
○​ The method must have the same parameter as in the parent class.
○​ A static method cannot be overridden.
○​ Ex.
class Animal {
public void displayInfo() {
​ System.out.println("I am an animal.");
}
}
class Dog extends Animal {
@Override
public void displayInfo() {
​ System.out.println("I am a dog.");
}
}
class Main {
public static void main(String[] args) {
​ Dog d1 = new Dog();
​ d1.displayInfo();
}
}
Output:
I am a dog

47.​ What is Method Overloading


○​ Method overloading in Java allows multiple methods with the same name
in a class, differing in parameter declarations.
○​ Java determines which overloaded method to call based on the type and/or
number of arguments provided.
○​ Overloading facilitates polymorphism, reducing multiple method names to a
common one for related operations.
○​ Overloaded methods can perform any desired activity, and they need not
be directly related to each other.
○​ It's recommended to overload methods that are closely related in
functionality.
○​ Ex.
class Adder{
​ ​ ​ int add(int a,int b)
{​ return a+b;​}
​ ​ ​ double add(double a, double b)
{​ return a+b;​}
}
class TestOverloading1{
​ public static void main(String[] args){
Adder obj = new Adder();
​ ​ System.out.println(obj.add(11,11));
​ ​ System.out.println(obj.add(3.3, 3.6));
​ }
}
Output:
22
6.9

48.​ What is Dynamic Method Dispatch


○​ This is the mechanism by which a call to an overridden function is resolved
at run time rather than compile time. This is how Java implements run time
polymorphism.
○​ When a method that is overridden is called through a superclass reference,
Java determines which version of that method to execute, based upon the
object being referred to at the time the call occurs.
○​ Thus, this determination is made at run time.
○​ Thus, it is the type of the object being referred to and not the type of the
reference variable, which determines the particular version of the method
to be executed.
○​ Ex.
class A
{
​ void m1()
​ {
​ System.out.println("Inside A's m1 method");
​ }
}
class B extends A
{
​ void m1()
​ {
​ System.out.println("Inside B's m1 method");
​ }
}
class C extends A
{
​ void m1()
​ {
​ System.out.println("Inside C's m1 method");
​ }
}
class Dispatch
{
​ public static void main(String args[])
​ {
​ ​ A a = new A();
​ ​ B b = new B();
​ ​ C c = new C();
​ ​ A ref;
​ ​ ref = a;
​ ​ ref.m1();
​ ​ ref = b;
​ ​ ref.m1();
​ ​ ref = c;
​ ​ ref.m1();
​ }
}

Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method

49.​ Explain final class, variable and method


○​ In the Java programming language, the final keyword is used in several
contexts to define an entity that can only be assigned once.
○​ The final keyword in java is used to restrict the user. In Java, the final
keyword can be used while declaring an entity. Using the final keyword
means that the value can’t be modified in the future.
○​ Following are the different context of using the final keyword
■​ Final Variable - When a variable is declared with the final keyword, its
value can’t be modified, essentially, a constant. This also means that
you must initialize a final variable.
■​ Final Method - A final method cannot be overridden or hidden by
subclasses which means even though a subclass can call the final
method of parent class without any issues but it cannot override it.
This is used to prevent unexpected behavior from a subclass altering
a method that may be crucial to the function or consistency of the
class
■​ Final Class - In Java, the final class cannot be inherited by another
class. The main purpose of using a class being declared as final is to
prevent the class from being subclasses.

50.​ List two uses of final


○​ To stop a value from changing
○​ Preventing method overriding
○​ Preventing Inheritance
Packages
51.​ CLASSPATH?
52.​ Define Package
○​ A set of classes and interfaces grouped together are known as Packages
in JAVA. Every class is a part of a certain package. When you need to use
an existing class, you need to add the package within the Java program.
○​ Packages are containers for classes which are used to keep the class
name space compartmentalised. They are stored in a hierarchical manner
and are explicit
○​ There are two types of Packages
■​ Built in Packages
■​ User Defined Packages

53.​ Steps to Create a Package


○​
54.​ How do you import Packages
import java.util.*; //get all classes from subpackage loads Date class
import java.util.Scanner; //get one specific class Scanner
public class PackageImportExample
{
public static void main(String args[])throws Exception
{
// Instantiate a scanner object
Scanner scanObj = new Scanner(System.in);
System.out.print("Kindly Enter Your UserName :");
String sName = scanObj.nextLine();
System.out.println("UserName is: " + sName);
​ scanObj.close();
// Instantiate a Date class from Util package
Date currdate = new Date();
System.out.println(currdate.toString());
//Without importing java.util package, But instead using a complete
qualified name to access the Date Class.
java.util.Date f = new java.util.Date();
System.out.println(f);
}
}
Output:
Kindly Enter Your Username :Prem
Username is: Prem
Mon Apr 13 02:21:22 IST 2024
Mon Apr 13 02:21:22 IST 2024
○​ To get the use of a package or a class from a library, We need the help of
the keyword “import”
○​ In the above code, there are three ways to import the package:
■​ Import one specific class from a package -
import java.util.scanner
In the above program, you have included only one scanner class from util
subpackage. It will get the user value and display.
■​ Import one whole package -
​ ​ import java.util.*
In the above program, the * denotes all the classes from the util
package. Along with the other classes, it loads the date class as well.
The date class displays the current date & time
■​ Use complete qualified name -
​ ​ ​ ​ ​ java.util.Date​
The Date class is available in the java.util package, without
using the import keyword. Directly call the Date class with the
complete package name java.util.Date. This will display the current
date & time.

Interface
55.​ Define Interface
○​ An interface in Java is a blueprint of a class. It has static constants and
abstract methods. The interface in Java is a mechanism to achieve
abstraction
○​ The interface in Java is a mechanism to achieve abstraction. There can be
only abstract methods in the Java interface, not method bodies. It is used
to achieve abstraction and multiple inheritance in Java.
○​ It cannot be instantiated just like the abstract class.

56.​ How to declare Interface


○​ An interface is declared by using the interface keyword. It provides total
abstraction; means all the methods in an interface are declared with the
empty body, and all the fields are public, static and final by default.
○​ A class that implements an interface must implement all the methods
declared in the interface.
○​ Syntax:
interface interface_name
{
// declare constant fields
// declare methods that are abstract by default.
}
57.​ How to Implement an Interface
○​ To implement an interface include the implements clause in the class
definition and then create the methods that are defined by the interface.
○​ The general form of a class which includes the implements clause is :
access class classname [implements interfaceName1 [,interfaceName2,...]]
{​
​ //overriding interface methods
}
○​ The methods that implement an interface must be declared public.

58.​ Example of Interface


interface A
{
void display();
​ ​ }
​ ​ class B implements A
​ ​ {
​ ​ ​ public void display()
​ ​ ​ {
​ ​ ​ ​ System.out.println(“Hello World”);
​ ​ ​ }
​ ​ }
​ ​ class MB
​ ​ {
​ ​ ​ public static void main(String args[])
​ ​ ​ {
​ ​ ​ ​ B obj = new B();
​ ​ ​ ​ obj.display();
​ ​ ​ }
​ ​ }

​ ​ Output -
​ ​ Hello World

Exception Handling
59.​ What is an Exception?
○​ An exception is an event, which occurs during the execution of a program,
that disrupts the normal flow of the program's instructions.

60.​ What is an Error?


○​ An error can be defined as a state at which the computer program cannot
recover, and stays in a non-executable mode or sometimes collapses from
normal-execution.

61.​ Hierarchy of Execution & Types of Execution

62.​ List the five keywords used for Exception Handling in Java
Exception handling in Java is managed by five keywords :
○​ try - The “try” keyword is used to specify the exception block.This block is
always followed either by a catch block or finally block, we cannot use try
block alone.
○​ catch - In this block code is written to handle the exception. Catch block is
never written alone; it is always preceded by the try block, and also catch
block could be followed by a finally block.
○​ throw - This keyword is used to manually throw the exception.
○​ throws - Any exception that is thrown out of a method is specified by the
throws clause
○​ finally - Any code that must absolutely be executed before a method
returns is put in a finally block.We can have only one finally block with a
try-catch statement.
○​ General Form for all the keywords for Exception Handling
class ExException{
public static void foo() throws aCheckedException{
try{
​ ​ //some code that can throw an exception.
} catch (Exception e){
//handle the exception
}
finally{
​ ​ //release resources acquired in the try block
}
if(someCondition) {
​ ​ throw new aCheckedException();
} else{
​ ​ throw new anUncheckedException();
}
​ ​ ​ ​ }
​ ​ ​ }

63.​ Write & Describe the general form of Exception Handling Block with Example
○​ The general form of an Exception Handling block is:
try{
//try block to monitor for errors
​ ​ }
​ ​ catch(ExceptionType1 exOb){
​ ​ ​ //exception handler for ExceptionType1
​ ​ }
​ ​ catch(ExceptionType2 exOb)
​ ​ {
​ ​ ​ //exception handler for ExceptionType2
​ ​ }
​ ​ //…
​ ​ finally{
​ ​ ​ //block of code to be executed before try block ends
​ ​ }

​ ​ ExceptionType is the type of exception that has occurred.
○​ Example of The General form of Exception Handling block:
public class Main
{
public static void main (String[]args)
{
​ try
​ {
​ ​ System.out.println ("in try");
​ ​ System.out.println (10 / 0);
​ }
​ catch (ArithmeticException ae)
​ {
​ ​ System.out.println ("in catch");
​ }
​ finally
​ {
​ ​ System.out.println ("in finally");
​ }
​ System.out.println ("after try catch finally");
}
}

​ Output -
​ In try
​ In catch
​ In finally
After try catch finally
64.​ Difference between throw & throws with example
throw throws
Is used to explicitly throw an exception Is used to declare that a method might
from within a block of code or method throw an exception
Can only throw a single exception at a Allows for the declaration of multiple
time exceptions that a function could throw.
The 'throw' keyword should be used The 'throws' keyword should be used
within the body of a method. within the method signature.
Can only propagate unchecked Can be used to declare both checked
exceptions. & unchecked exceptions
Is followed by the instance variable Is followed by the names of Exception
classes
​ ​
​ ​ Ex.,
class ThrowsExecp {
​ static void fun() throws IllegalAccessException
​ {
​ System.out.println("Inside fun(). ");
​ throw new IllegalAccessException("demo");
​ }
​ public static void main(String args[])
​ {
​ try {
​fun();
​ }
​ catch (IllegalAccessException e) {
​System.out.println("caught in main.");
​ }
​ }
}

Output -
Inside fun().
Caught in main.

65.​ How to declare User Defined Exception

66.​ Define printStackTrace() method in Java


○​ The printStackTrace() method in Java is a tool used to handle exceptions
and errors.
○​ It is a method of Java’s throwable class which prints the throwable along
with other details like the line number and class name where the exception
occurred.
○​ The printStackTrace() is very useful in diagnosing exceptions.
○​ For example, if one out of five methods in your code cause an exception,
printStackTrace() will pinpoint the exact line in which the method raised the
exception.

Threads
67.​ What are Threads?
○​ A thread is a thread of execution in a program. Thread requires less
resources to create and exists in the process, thread shares the process
resources.
○​ Generally, all the programs have at least one thread, known as the main
thread, that is provided by the JVM or Java Virtual Machine at the starting
of the program’s execution. At this point, when the main thread is provided,
the main() method is invoked by the main thread.
○​ The Java Virtual Machine allows an application to have multiple threads of
execution running concurrently.

68.​ Explain the Lifecycle of Threads in detail


The Life Cycle of a Thread in Java refers to the state transformations of a thread
that begins with its birth and ends with its death.

The stages in the lifecycle of a thread are given below:


○​ NEW - A NEW Thread (or a born Thread) is a thread that’s been created
but not yet started. It remains in this state until we start it using the start()
method.
○​ RUNNABLE - After calling the start() method on a thread, it enters the
runnable state but they’re waiting for resource allocation from the system.
○​ RUNNING - When a thread executes its code inside the run() method.
○​ BLOCKED - When a thread tries to access a synchronised block or
method, but another thread already holds the lock.
○​ WAITING - Using the wait method inside a synchronised block, a thread
can wait until another thread calls the notify() or notifyAll() methods to wake
it up.
○​ TIMED WAITING - Using methods like sleep(milliseconds) or
join(milliseconds) causes a thread to enter the timed waiting state for the
specified duration.
○​ TERMINATED/DEAD - When the run() method finishes its execution or
when the stop() method is called on the Thread.

69.​ What is the main thread, Describe its features


○​ When a Java program starts up, one thread begins running immediately.
This thread is usually called the main thread of the program since it is the
one that is executed when the program begins.
○​ The main thread has the following features :
■​ It is the thread from which other child threads are spawned.
■​ It must be the last thread to finish execution. When the main thread
stops, your program terminates.
○​ The main thread is automatically created when the program starts. It can
be controlled through a Thread object.

70.​ Explain the different Thread Class Methods


○​ start() - Causes this thread to begin execution; the Java Virtual Machine
calls the run method of this thread.
Syntax - public void start()
○​ run() - If this thread was constructed using a separate Runnable run object,
then that Runnable object's run method is called; otherwise, this method
does nothing and returns. Subclasses of Thread should override this
method.
Syntax - public void run()
○​ yield() - A hint to the scheduler that the current thread is willing to yield its
current use of a processor. The scheduler is free to ignore this hint. It is
rarely appropriate to use this method. It may be useful for debugging or
testing purposes, where it may help to reproduce bugs due to race
conditions
Syntax - public static void yield()

71.​ Write a note on isAlive()


○​ Tests if this thread is alive. A thread is alive if it has been started and has
not yet died.
○​ Returns true if this is alive; false otherwise.
○​ Syntax - public final boolean isAlive()

72.​ Write a note on join()


○​ The join method allows one thread to wait for the completion of another.
○​ If t is a Thread object whose thread is currently executing,
t.join();
causes the current thread to pause execution until t's thread terminates.
○​ Syntax - public final void join() throws InterruptedException
○​ Other forms of join() are also there where you can specify the maximum
amount of time that you want to wait for the specified thread to terminate.

73.​ Difference between sleep() & wait()
wait() sleep()
When called, the thread goes to When called, the thread goes to
WAITING state TIMED_WAITING
Must be called from the synchronised Can be called from within or without
context (can be a synchronised block synchronised block
or method)
When called, the Thread will release The Thread will keep holding the lock
the lock it was holding even after calling the sleep() method
Is defined in java.lang.Object class Is defined in java.lang.Thread class
The Thread which is waiting can be The Sleeping Thread cannot be woken
woken up by other threads by calling by another thread until the time out,
notify() & notifyAll() method but it can always be interrupted by
another method.

74.​ Explain notify() & notifyAll()


○​ notify() - The notify() method wakes up the first thread that called wait() on
the same object. If multiple threads are waiting, it is not specified which
one will be awakened. The awakened thread will then compete for the lock
on the object.
○​ notifyAll() - A call to this method wakes up all threads that are waiting on
this object’s monitor. A thread waits on an object’s monitor by calling one of
the wait methods. The awakened threads will not be able to proceed until
the current thread relinquishes(voluntarily releases) the lock on this object.
75.​ Runnable Interface? Give example to create a thread using Runnable
Interface

76.​ Note on Thread Priorities


○​ The number of services assigned to a given thread is referred to as its
priority. Any thread generated in the JVM is given a priority. The priority
scale runs from 1 to 10.
○​ 1 is known as the lowest priority. 5 is known as standard priority. 10
represents the highest level of priority.
○​ The main thread's priority is set to 5 by default, and each child thread will
have the same priority as its parent thread.
○​ We have the ability to adjust the priority of any thread, whether it is the
main thread or a user-defined thread. It is advised to adjust the priority
using the Thread class's constants, which are as follows:
■​ MIN_PRIORITY - The minimum priority that a thread can have. (1)
■​ NORM_PRIORITY - The default priority that is assigned to a thread.
(5)
■​ MAX_PRIORITY - The maximum priority that a thread can have. (10)
○​ The priority of a thread can be set by using the setPriority() and read using
the getPriority() method, both are defined in the Thread class with the
below prototype:
■​ public final void setPriority(int newPriority)
■​ public final int getPriority()
○​ Ex.
public class ThreadPriority extends Thread
{
public void run ()
{
System.out.println ("running thread name is:" + Thread.currentThread
().getName ());
System.out.println ("running thread priority is:" +
Thread.currentThread ().getPriority ());
}
public static void main (String args[])
{
ThreadPriority m1 = new ThreadPriority ();
ThreadPriority m2 = new ThreadPriority ();
m1.setPriority (Thread.MIN_PRIORITY);
m2.setPriority (Thread.MAX_PRIORITY);
m1.start ();
m2.start ();
}
}

Output:
running thread name is:Thread-0
running thread priority is:1
running thread name is:Thread-1
running thread priority is:10

77.​ Define Multithreading

78.​ Describe Synchronisation with an example.


○​ Synchronisation in Java is the process that allows only one thread at a
particular time to complete a given task entirely.
○​ By default, the JVM gives control to all the threads present in the system to
access the shared resource, due to which the system approaches race
conditions.
○​ We need Synchronisation for the following reasons
■​ To prevent thread interleaving or interference
■​ To provide consistency to the program
○​ Synchronisation in Java is done by using the synchronised keyword. This
keyword can be used on Instance methods, Static methods & code blocks.
○​ When we use a synchronised block, Java internally uses a monitor, also
known as a monitor lock or intrinsic lock, to provide synchronisation
○​ These monitors are bound to an object; therefore, all synchronised blocks
of the same object can have only one thread executing them at the same
time.
○​ Ex.
class School extends Thread
{
​ synchronised public void Teach(String teacherName)
​ {
​ ​ for(int i=0; i<3; i++)
​ ​ {
​ ​ ​ System.out.println(i + ". " + teacherName);
​ ​ }
​ }

}
class MyThread extends Thread
{
​ School sch;
​ String teacherName;
​ @Override
​ public void run()
​ {
​ ​ sch.Teach(teacherName);
​ }
​ MyThread(School sch, String teacherName)
​ {
​ ​ this.sch = sch;
​ ​ this.teacherName = teacherName;
​ }
}​
public class Pack extends Thread
{
​ public static void main(String args[])
​ {
​ ​ School sch = new School();
​ ​ MyThread t1 = new MyThread(sch, "Raj");
​ ​ MyThread t2 = new MyThread(sch, "Rohan");
​ ​ t1.start();
​ ​ t2.start();
​ }
}
​ ​
Output:
0. Rohan
​ ​ 1. Rohan
​ ​ 2. Rohan
​ ​ 0. Raj
​ ​ 1. Raj
​ ​ 2. Raj

79.​ Explain Deadlock with example


○​ Deadlock describes a condition in which two or more threads are blocked
(hung) forever because they are waiting for each other. There are many
causes of deadlocks
○​ Here is a simple example of a deadlock condition:
Thread 1 holds Lock A and requests Lock B
Thread 2 holds Lock B and requests Lock A

80.​ When does a Deadlock situation occur?


A process with two or more threads can deadlock when the following conditions
hold:
○​ Threads that are already holding locks request new locks
○​ The requests for new locks are made concurrently
○​ Two or more threads form a circular chain in which each thread waits for a
lock which is held by the next thread in the chain

File I/O
81.​ Charachteristics of Stream Classes
82.​ Describe Byte Stream classes in detail
○​ Java defines two types of streams : byte streams and character
streams.Byte streams provide a convenient way to handle input/output of
bytes. They are useful when reading or writing binary data.
○​ Byte Streams are defined by using two class hierarchies. At the top are two
abstract classes:
■​ InputStream - The InputStream class of the java.io package is an
abstract superclass that represents an input stream of bytes. Since
InputStream is an abstract class, it is not useful by itself. However, its
subclasses can be used to read data.
●​ FileInputStream - used to read the content of the specified file
byte by byte.
●​ ByteArrayInputStream - used to read the bytes of byte array
byte by byte.
●​ DataInputStream - used to perform reading operation from any
input device like keyboard, file, etc
●​ BufferedInputStream - used with other input streams to read
the data (in bytes) more efficiently.
●​ ObjectInputStream - used to read data written by the
ObjectOutputstream.
■​ OutputStream - The OutputStream class of the java.io package is an
abstract superclass that represents an output stream of bytes. Since
OutputStream is an abstract class, it is not useful by itself. However,
its subclasses can be used to write data.
●​ FileOutputStream - used to write the content onto a file byte by
byte
●​ ByteArrayOutputStream - used to write an array of output data
(in bytes).
●​ DataOutputStream - allows an application to write primitive
Java data types to the output stream in a machine-independent
way.
●​ BufferedOutputStream - used for buffering an output stream.
●​ ObjectOutputStream - encodes Java objects using the class
name and object values and generates corresponding stream
●​ PrintStream - used to write output data in commonly readable
form (text) instead of bytes.
○​ In order to use the stream classes you have to import java.io. There are
abstract classes in InputStream and OutputStream which define several
key methods which the other stream classes implement.

83.​ Describe Character Stream classes in detail


○​ Java defines two types of streams : byte streams and character
streams.Character streams provide a convenient way of handling input and
output of characters. They use Unicode and can therefore be
internationalised.
○​ They are also defined by using two class hierarchies. At the top are two
abstract classes
■​ Reader - The Reader class of the java.io package is an abstract
superclass that represents a stream of characters. Since Reader is
an abstract class, it is not useful by itself. However, its subclasses
can be used to read data.
●​ InputStreamReader - used to convert data in bytes into data in
characters.
●​ BufferedReader - used to perform reading operations from any
input device like keyboard, file, etc.
●​ StringReader - takes an input string and changes it into the
character stream.
●​ FileReader - used to read data from the file.
■​ Writer - The Writer class of the java.io package is an abstract
superclass that represents a stream of characters. Since Writer is an
abstract class, it is not useful by itself. However, its subclasses can
be used to write data.
●​ OutputStreamWriter - used to convert data in character form
into data in bytes form.
●​ BufferedWriter - used with other writers to write data (in
characters) more efficiently.
●​ StringWriter - a character stream that collects output from a
string buffer.
●​ FileWriter - used to write the content onto the file char by char.
●​ PrintWriter - used to print the formatted representation of
objects to the text-output stream.
○​ The Reader and Writer classes define several methods which are
implemented by the other stream classes.
○​ The most common among them are read() and write() which read and write
characters of data, respectively.These methods are overridden by the
derived stream classes.
84.​ Explain Predefined Streams
○​ The java.lang package defines a class called System which encapsulates
several aspects of the Java runtime environment.
○​ System contains three predefined stream variables in, out and err which
are declared public and static within System.
■​ System.out (standard output stream) - This stream is used for writing
data from the program to an output device such as a monitor /
console by default or to some specified file.
■​ System.in (standard input stream) - This stream is used for reading
data for the program from the keyboard by default.
■​ System.error (standard error stream) - This is used to show an error
message on the screen i.e. console by default for the users.
○​ System.in is an object of InputStream. On the other hand, System.out and
System.err are both an object of type PrintStream.
○​ All these Java Predefined Streams are automatically initialised by Java’s
JVM (Java Virtual Machine) on startup.
○​ All these streams are byte streams but these are used to read and write
character streams as well.

85.​ Explain read() method


○​ To read a character from a BufferedReader we use the read() method as :
int read() throws IOException
○​ Every time a read() is called it reads a character from the input stream and
returns it as an integer value.
○​ When the end of stream is encountered it returns -1.
○​ It can throw an IOException.

86.​ Explain readLine() method


○​ readLine() is a method of the BufferedReader class which can be used to
read a string from the keyboard.
○​ Its general form is :
String readLine() throws IOException
○​ Note that it returns a String object.

87.​ Explain write() method


○​ It is the low level method which is implemented by PrintStream since it is
an output stream derived from OutputStream
○​ Thus, write() can also be used to write to the console.
○​ The simplest form of write() is :
void write(int byteval) throws IOException
○​ This method writes to the file the byte which is specified by byteval.
88.​ PrintWriter Class
○​ The recommended method of writing to the console when using Java is
through a PrintWriter stream. PrintWriter is one of the character based
classes.
○​ It is used to print the formatted representation of objects to the text-output
stream.
○​ Unlike other writers, PrintWriter converts the primitive data (int, float, char,
etc.) into the text format. It then writes that formatted data to the writer.
○​ Also, the PrintWriter class does not throw any input/output exceptions.
Instead, we need to use the checkError() method to find any error in it.
○​ A constructor of PrintWriter is :
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
○​ Here, outputStream is an object of type OutputStream and flushOnNewline
controls whether Java flushes the output stream every time a ‘\n’ character
is output.
○​ Ex.
import java.io.*;
public class PrintWriterDemo
{
​ public static void main(String args[]) throws Exception
​ {
​ ​ String data = "This is a line of text inside the file.";
​ ​ try {
​ ​ ​ PrintWriter output = new PrintWriter("output.txt");
​ ​ ​ output.print(data);
​ ​ ​ output.close();
​ ​ ​ System.out.println("Success?");
​ ​ } catch (Exception e) {
​ ​ ​ e.getStackTrace();
​ ​ }
​ }
}

Output:
Success?

output.txt
This is a line of text inside the file.

AWT
89.​ Detail about AWT
90.​ Write a short note on AWT Hierarchy.
91.​ Short note on Component Class
○​ At the top of the AWT, the hierarchy is the component class. The
Component is an abstract class that encapsulates all of the attributes of a
visual component. All user interface elements that interact with the user are
subclasses of Component and are displayed on the screen
○​ Some useful methods of Component Class
■​ public void add(Component c): It is used to insert a component on
this component.
■​ public void setSize(int width, int height): It is used to set the size
(height and width) of the component.
■​ public void setLayout(LayoutManager m): It defines the layout
manager of the component.
■​ public void setStatus(boolean status): It is used to change the
visibility of the component, by default false.
92.​ Short note on Frames in AWT
○​ A Frame may be a top-level window with a title and a border.
○​ It can produce other components like buttons, text fields, etc. The default
layout for a frame is BorderLayout.
○​ Frames are capable of generating the subsequent sorts of window events:
WindowOpened, WindowClosing, WindowClosed, WindowIconified,
WindowDeiconified, WindowActivated, WindowDeactivated.
○​ When a Frame window is made by a stand-alone application instead of an
applet, a traditional window is made.
○​ Here are two of Frame’s constructors:
■​ Frame(): It creates a standard window that does not contain a title.
■​ Frame(String title): It creates a window with the title specified by the
title.
○​ The frame can be created in two ways:
■​ Create the object of the Frame class directly.
​​ Frame f = new Frame();
■​ Create the object of any class that extends the Frame class.
​ ​ MyFrame mf = new MyFrame();
○​ Different methods of Frames
■​ void setSize(int newWidth, newHeight): It is used to set the
dimensions of the window by specifying the width and height fields of
the dimensions. The dimensions are specified in terms of pixels.
■​ Dimension getSize() : The getSize() method is used to obtain the
current size of a window. This method returns the current size of the
window contained within the width and height fields of a Dimension
object.
■​ void setVisible(Boolean visibleFlag): The component is visible if the
argument to this method is true. Otherwise, it is hidden.
■​ void setTitle(String newTitle): You can change the title in a frame
window using setTitle(). Here, newTitle is the new title for the window.
■​ windowClosing(): When using a frame window, your program must
remove that window from the screen when it is closed, by calling
setVisible(false). To intercept a window-close event, you must
implement the windowClosing() method of the WindowListener
interface. Inside windowClosing(), you must remove the window from
the screen.
○​ Ex.
import java.awt.*;
public class FrameDemo2 extends Frame
{
public static void main (String[]args)
{
FrameDemo2 fd = new FrameDemo2 ();
Button btn = new Button ("Hello World");
fd.add (btn);
fd.setVisible (true);
fd.setSize (500, 200);
}
}

93.​ Explain controls in AWT (Any 5 karlo)


Controls are components that allow a user to interact with your application in
various ways. The AWT supports the following types of controls:
○​ Label - The easiest control to use is a label. A label contains a string and is
an object of type Label. Labels are passive controls that do not support any
interaction with the user.​
Creating Label : Label lab1 = new Label(String);​
The different Label Constructors are:
■​ Label() - It creates a blank label
■​ Label(String str) - It creates a label that contains the string specified
by str.
■​ Label(String str, int how) - It creates a label that contains the string
specified by str using the alignment specified by how. The value of
how must be one of these three constants: Label.LEFT, Label.RIGHT,
Label.CENTER.

○​ Button - The most widely used control is Button. A button is a component


that contains a label and that generates an event when it is pressed.
Creating Button : Button b = new Button(String label);
The different Button Constructors are:
■​ Button() - It creates an empty button.
■​ Button(String str) - It creates a button that contains str as a label.
​ ​
○​ Checkbox - A checkbox may be a control that’s used to turn an option on or
off. It consists of a little box that will either contain a check or not. There’s a
label related to each checkbox that describes what option the box
represents. You modify the state of a checkbox by clicking on. Checkboxes
are often used individually or as a part of a gaggle. Checkboxes are
objects of the Checkbox class.
Creating Checkbox : Checkbox cb = new Checkbox(Label);
The different Checkbox Constructors are:
■​ Checkbox()
■​ Checkbox(String str)
■​ Checkbox(String str, Boolean on)
■​ Checkbox(String str, boolean on, CheckboxGroup cbGroup)
str specifies the label for a check box. on allows you to set the initial state
of the check box. If on is true then the checkbox is initially checked,
otherwise it is cleared. cbGroup specifies the group for a checkbox. If the
checkbox is not a part of the group then cbGroup must be null.

○​ CheckboxGroup: Radio Buttons - Radio buttons are a set of mutually


exclusive checkboxes in which one and only one check box in the group
can be checked at any one time.In order to create radio buttons you must
first define a group to which they belong and then specify that group when
you construct the check boxes. Checkbox groups are objects of type
CheckBoxGroup.
Creating Radio Button :
CheckboxGroup cbg = new CheckboxGroup();
Checkbox rb = new Checkbox(Label, cbg, boolean);
It has only the default constructor defined, which creates an empty group.

○​ Choice Controls - This component will display a group of times as a


drop-down menu from which a user can select only one item. The choice
component is used to create a pop-up list of items from which the user may
choose. Therefore, Choice control is a form of a menu. When it is inactive,
a Choice component takes up only enough space to show the currently
selected item. When the user clicks on a Choice component, the whole list
of choices pops up, and a new selection can be made.
Creating Choice : Choice ch = new Choice();
Choice only defines the default constructor, which creates an empty list.
○​ List Control - This component will display a group of items as a drop-down
menu from which a user can select only one item. The List class provides a
compact, multiple-choice, scrolling selection list. Unlike the selection
object, which shows only the only selected item within the menu, an
inventory object is often constructed to point out any number of choices
within the visible window. It also can be created to permit multiple
selections.
Creating List : List lst1 = new List(int, Boolean);
The different List Constructors are:
■​ List()
■​ List(int numRows)
■​ List(int numRows, boolean multipleSelect)
where numRows specifies the number of entries in the list that will alway
be visible. Others are scrolled into view as needed. If multipleSelect is
true, then the user may select two or more items at a time, if it is false, then
only one item can be selected.

○​ Scroll Bar - Scrollbars are used to select continuous values between a


specified minimum and maximum. Scroll bars may be oriented horizontally
or vertically. A scroll bar is really a composite of several individual parts.
Each end has an arrow that you simply can click to get the present value of
the scroll bar one unit within the direction of the arrow. The current value of
the scroll bar relative to its minimum and maximum values are indicated by
the slider box for the scroll bar. Scrollbars are encapsulated by the
Scrollbar class.
Creating Scrollbar : Scrollbar sb = new Scrollbar();
The different Scrollbar Constructors are:
■​ Scrollbar() - It creates a vertical scrollbar.
■​ Scrollbar(int style) - It allows you to specify the orientation of the
scrollbar. If the style isScrollbar.VERTICAL, a vertical scrollbar is
created. If a style is Scrollbar.HORIZONTAL, the scroll bar is
horizontal.
■​ Scrollbar(int style, int initialValue, int thumbSize, int min, int max) -
Here, the initial value of the scroll bar is passed in initialValue. The
number of units represented by the peak of the thumb is passed in
thumbSize. The minimum and maximum values for the scroll bar are
specified by min and max.

○​ TextField - The TextField component will allow the user to enter some text.
It is used to implement a single-line text-entry area, usually called an edit
control. It also allows the user to enter strings and edit the text using the
arrow keys, cut and paste keys, and mouse selections. TextField is a
subclass of TextComponent.
Creating TextField : TextField tf = new TextField(size);
The different TextField constructors are:
■​ TextField() - creates a default text field
■​ TextField(int numChars) - Creates a text field which is numChars
wide
■​ TextField(String str) - It initialises the text field with the string
contained in str
■​ TextField(String str, int numChars) - It initialises a text field and sets
its width.

○​ TextArea - Sometimes one line of text input isn’t enough for a given task.
To handle these situations, the AWT includes an easy multiline editor called
TextArea.
Creating TextArea : TextArea ta = new TextArea();
The different TextArea constructors are:
■​ TextArea()
■​ TextArea(int numLines, int numChars)
■​ TextArea(String str)
■​ TextArea(String str, int numLines, int numChars)
■​ TextArea(String str, int numLines, int numChars, int sBars)
numLines specifies the height, in terms of lines of the text area and
numChars specifies its width, in characters. Initial text can be specified in
str. sBars allows you to specify the scroll bars you want the control to
have.must be one of these values : SCROLLBARS_BOTH,
SCROLLBARS_NONE . SCROLLBARS_HORIZONTAL_ONLY .
SCROLLBARS_VERTICAL_ONLY

94.​ Describe methods of Graphics Class


○​ The Graphics class defines a number of drawing functions. Each shape
can be drawn edge-only or filled. Objects are drawn and filled in the
currently selected graphics colour, which is black by default. When a
graphics object is drawn that exceeds the dimensions of the window, the
output is automatically clipped.
○​ The java.awt.Graphics class provides many methods for graphics
programming:
■​ public abstract void drawString(String str, int x, int y) - is used to
draw the specified string.
■​ public void drawRect(int x, int y, int width, int height): draw a
rectangle with the specified width and height.
■​ public abstract void fillRect(int x, int y, int width, int height): is used to
fill the rectangle with the default colour and specified width and
height.
■​ public abstract void drawOval(int x, int y, int width, int height): is used
to draw an oval with the specified width and height.
■​ public abstract void fillOval(int x, int y, int width, int height): is used to
fill an oval with the default colour and specified width and height.
■​ public abstract void drawLine(int x1, int y1, int x2, int y2): is used to
draw a line between the points(x1, y1) and (x2, y2).
○​ Ex.
import java.applet.Applet;
import java.awt.*;
/*
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
*/
public class GraphicsDemo extends Applet
{
public void paint (Graphics g)
{
g.setColor (Color.red);
g.drawString ("Welcome", 50, 50);
g.drawLine (20, 30, 20, 300);
g.drawRect (70, 100, 30, 30);
g.fillRect (170, 100, 30, 30);
g.drawOval (70, 200, 30, 30);
g.fillOval (170, 200, 30, 30);
}
}

95.​ Explain font class in AWT


○​ The AWT supports multiple type fonts. Fonts have a family name, a logical
font name and a face name.
○​ The family name is the general name of the font eg. Courier. The logical
name specifies a category of the font eg. Monospaced. The face name
specifies a specific font eg. Courier Italic.
○​ Fonts are encapsulated in the Font class which defines several methods.
○​ To select a new font, you should first construct a Font object that describes
the font. One of the constructors of Font which is used for this purpose is :
Font(String fontName, int fontStyle, int pointSize)
○​ fontName specifies the name of the desired font, which can be specified
either using the logical name or the face name. The default font, if you
don’t explicitly set a font, is the Dialog font.
○​ The style of the font is specified by fontStyle. It may consist of one or more
of the three constants : Font.PLAIN, Font.BOLD, Font.ITALIC. To combine
the styles you have to OR them together eg. Font.BOLD | Font.ITALIC
specifies a bold, italic style.
○​ pointSize is used to specify the size of the font in points.
○​ In order to use the font that you have created you should select it using the
setFont() method which is defined by Component. Its general form is :
void setFont(Font fontObj)
○​ where fontObj is the object that contains the desired font.

96.​ Short note on Color Class


○​ Java supports color in a portable, device independent fashion. You can
specify any color that you want in the AWT.
○​ Color is encapsulated by the class Color. Color defines a number of
constants to specify a number of common colors.
○​ You can also create your own colors by using the color constructors. Some
of the constructors for Color are :
■​ Color(int red, int green, int blue) - you can specify three integer
values to specify the color as a mix of red, green and blue. These
values must be between 0 and 255.
■​ Color(int rgbValue) - It takes a single integer value that contains a
mix of red, green and blue packed in an integer. This integer is
organised as : red in bits 16 to 23, green in bits 8 to 15 and blue in
bits 0 to 7.
■​ Color(float red, float green, float blue) - It takes three float values
between 0.0 to 1.0 to specify the relative mix of red, green and blue.
○​ The setForeground() and setBackground() are the methods which can be
used to set the foreground and background colors respectively.
○​ You can obtain the red, green and blue components of a color
independently using the following methods :
■​ int getRed()
■​ int getGreen()
■​ int getBlue()
○​ Each of these methods returns the RGB color component found in the
invoking Color object in the lower 8 bits of an integer.
○​ To obtain a packed RGB representation use the method getRGB(). Its form
is -> int getRGB()
○​ By default graphics objects are drawn in the current foreground color. You
can change this color with the method setColor().
○​ This method has the following form void setColor(Color newColor) where
newColor specifies the new drawing color.
○​ getColor() is the method used to obtain the current color. Its form is : Color
getColor()

97.​ setXORMode()
○​ The paint mode determines how objects are drawn in a window. By default
the new output to a window overwrites any pre-existing contents.
○​ However, it is possible to have new objects XORed onto the window. For
this purpose you use the setXORMode() method which is as follows :
void setXORMode(Color xorColor)
○​ where xorColor specifies the color that will be XORed to the window when
an object is drawn.
○​ The XOR mode guarantees that the new object is always to be visible no
matter what color the object is drawn over.
○​ To return to the overwrite mode you use the setPaintMode() method. Its
form is : ​ ​ void setPaintMode()
○​ In general, you will want to use the overwrite mode for normal output and
the XOR mode for any special purposes.

98.​ Menus in AWT


○​ A Menu object is a pull-down menu component that is deployed from a
menu bar
○​ A menu can optionally be a tear-off menu. A tear-off menu can be opened
and dragged away from its parent menu bar or menu. It remains on the
screen after the mouse button has been released.
○​ Different Constructors of Menus are:
■​ Menu() - Constructs a new menu with an empty label.
■​ Menu(String label) - Constructs a new menu with the specified label.
■​ Menu(String label, boolean tearOff) - Constructs a new menu with the
specified label, indicating whether the menu can be torn off.

99.​ What is a Layout Manager?


○​ Layout Manager is a class or component that’s responsible for rearranging
the components on the container consistent with the required layout.
○​ A layout manager automatically arranges your controls within a window by
using some algorithm
○​ Each Container object features a layout manager related to it.
○​ A layout manager is an instance of any class implementing the
LayoutManager interface.
○​ The layout manager is about by the setLayout( ) method. If no call to
setLayout( ) is formed, the default layout manager is employed.
○​ Whenever a container is resized (or sized for the primary time), the layout
manager is employed to position each of the components within it.
○​ The setLayout( ) method has the subsequent general form: void
setLayout(LayoutManager layoutObj)
○​ Here, layoutObj may be a reference to the specified layout manager.
○​ If you want to manually disable the layout manager and position
components, pass null for layoutObj.
○​ If you do this, you’ll get to determine the form and position of every
component manually, using the setBounds() method defined by
Component.

100.​ Explain different types of Layout with constructor & methods


AWT package provides the following types of Layout Managers:
○​ Flow Layout - This layout will display the components from left to right,
from top to bottom. The components will always be displayed in the first
line and if the first line is filled, these components are displayed on the next
line automatically. This is the default layout manager.
The different ways to create a flow layout are:
■​ FlowLayout f1 = new FlowLayout(); - all components are centred and
a space of 5 pixels is left between each component.
■​ FlowLayout f1 = new FlowLayout(int align); - In this form, you can
specify how each line is aligned. The valid values for how are :
FlowLayout.LEFT FlowLayout.CENTER FlowLayout.RIGHT. These
values specify the left, center and right alignment respectively.
■​ FlowLayout f1 = new FlowLayout(int align, int horz, int vert); - allows
to specify the horizontal and vertical space left between components
in horz and vert respectively

○​ Border Layout - This layout will display the components along the border of
the container. This layout contains five locations where the component can
be displayed. Locations are North, South, East, west, and Center. The
default region is the center. The above regions are the predefined static
constants belonging to the BorderLayout class.
○​ The different ways to create a border layout are:
■​ BorderLayout bl = new BorderLayout(); - creates the default border
layout.
■​ BorderLayout bl = new BorderLayout(int vgap, int hgap); - In the
second form you can specify the horizontal and vertical space left
between the components by horz and vert respectively.
○​ BorderLayout defines the following constants which specify the regions :
BorderLayout.CENTER, BorderLayout.SOUTH, BorderLayout.EAST,
BorderLayout.WEST, BorderLayout.NORTH

○​ Card Layout - A card layout represents a stack of cards displayed on a


container. At a time, only one card can be visible, each containing only one
component.
○​ The different ways to create a Card layout are:
■​ CardLayout cl = new CardLayout(); - creates the default card layout.
■​ CardLayout cl = new CardLayout(int hgap, int vgap); - this form you
can specify the horizontal and vertical spaces left between
components by horz and vert respectively.
○​ The different methods of Card Layout are:
■​ void first(Container): It is used to flip to the first card of the given
container.
■​ void last(Container): It is used to flip to the last card of the given
container.
■​ void next(Container): It is used to flip to the next card of the given
container.
■​ void previous(Container): It is used to flip to the previous card of the
given container.
■​ void show(Container, cardname): It is used to flip to the specified
card with the given name.

○​ Grid Layout - The layout will display the components in the format of rows
and columns statically. The container will be divided into a table of rows
and columns. The intersection of a row and column cell and every cell
contains only one component, and all the cells are of equal size. According
to the Grid Layout Manager, the grid cannot be empty.
○​ The different ways to create a Grid layout are:
■​ GridLayout gl = new GridLayout() - This creates a single column grid
layout.
■​ GridLayout gl = new GridLayout(int rows, int cols); - This create a grid
layout of the specified number of rows and columns
■​ GridLayout gl = new GridLayout(int rows, int cols, int horz, int vert); -
It allows you to specify the horizontal and vertical space between
components using the horz and vert respectively.

101.​ What is Event Delegation Model


○​ The delegation event model defines standard and consistent mechanisms
to generate and process events.
○​ In this model, the concept is that a source generates an event and sends it
to one or more listeners. The listener simply waits for an event, once it
receives the event, the listener processes it and returns.
○​ The advantage of this design is that the application logic which processes
the events is cleanly separated from the user interface logic that generates
the events.
○​ Thus the user interface element is able to delegate the processing of an
event to a separate piece of code.
○​ In this model, the listeners must register with a source in order to receive
the notification of an event. This means that notifications are sent only to
those listeners who wish to receive them.

102.​ What are Events?


○​ In the delegation model, an event is an object which describes a state
change in a source.
○​ The event can be generated as a result of a person interacting with the
elements in a graphical user interface.
○​ Ex. Pressing a button, entering a character via a keyboard, selecting an
item in a list, clicking the mouse are some of the activities which cause
events to be generated.
○​ Events may also occur as a consequence which is not directly caused by
user interface. eg. an event may be generated if a timer expires, a counter
exceeds a value, a hardware or software failure occurs etc.

103.​ What are sources of Events


○​ A source is an object which generates an event. This occurs when the
internal state of the object changes in some way.
○​ Sources may generate more than one type of event. A source must
register listeners in order for the listeners to receive notifications about a
specific type of event.
○​ Each type of event has its own registration method.
○​ The general form is :
public void addTypeListener(TypeListener el)
○​ where Type is the name of the event and el is the reference to the event
listener. eg the method that registers a keyboard event listener is called
addKeyListener().

104.​ What is Multicasting & Unicasting the Event


○​ When an event occurs, all the registered listeners are notified and receive
a copy of the event object. This is known as multicasting the event.
○​ The general form of this method is :
public void addTypeListener(TypeListener el) throws
java.util.TooManyListenersException
○​ where Type is the name of the event and el is the reference to the event
listener.
○​ Some sources may allow only one listener to register.
○​ When such an event occurs, the registered listener is notified. This is
called unicasting the event.

105.​ What is an Event Listeners


○​ A listener is an object that is notified when an event occurs.
○​ It has two major requirements :
■​ First it must have been registered with one or more sources to
receive the notifications about specific types of event.
■​ Second, it must implement methods to receive and process these
notifications.
○​ The methods which receive and process events are defined in a set of
interfaces found in java.awt.event.

106.​ Describe any four EventListener interfaces & the specific methods contained
in them. (naam yaad rakhlo atleast)
○​ ActionEvent Class - An ActionEvent is generated when a button is pressed,
a list item is double clicked or a menu item is selected. This class defines
four integer constants which can be used to identify any modifiers
associated with an action event.
These constants are ALT_MASK, CTRL_MASK, META_MASK,
SHIFT_MASK.
There is also an integer constant ACTION_PERFORMED, which can be
used to identify action events.
The constructors of ActionEvent are :
■​ ActionEvent(Object src, int type, String cmd)
■​ ActionEvent(Object src, int type, String cmd, int modifiers)
where src is a reference to the object which generated the event. type
specifies the type of the event and cmd is the command string. The
argument modifiers indicate which of the modifier keys (ALT, CTRL, META
and/or SHIFT) were pressed when the event was generated.
The different ActionEvent Class methods are:
■​ String getActionCommand(): It is used to obtain the command name
for the invoking ActionEvent object.
■​ int getModifiers(): It returns a value that indicates which modifier keys
(ALT, CTRL, META, and /or SHIFT) were pressed when the event
was generated.

○​ ComponentEvent Class - This class is generated when the size, position or


visibility of a component is changed. There are four types of component
events. The ComponentEvent class defines integer constants that can be
used to identify these component events.
The constants and their meanings are :
■​ COMPONENT_HIDDEN The component was hidden
■​ COMPONENT_MOVED The component was moved
■​ COMPONENT_RESIZED The component was resized
■​ COMPONENT_SHOWN The component became visible
The constructor for the class is :
■​ ComponentEvent(Component src, int type) - where src is a reference
to the object that generated this event and type specifies the type of
the event.
Its method getComponent() returns the component which generated the
event and its general form is :
■​ Component getComponent();

○​ ContainerEvent Class - A ContainerEvent is generated when a component


is added to or removed from a container. There are two types of container
events. ​
The class defines integer constants that can be used to identify them :
COMPONENT_ADDED and COMPONENT_REMOVED. They indicate that
a component has been added or removed from the container.
ContainerEvent is a subclass of ComponentEvent. Its constructor is :
■​ ContainerEvent(Component src, int type, Component comp) - where
src is a reference to the container that generated this event, the type
of the event is specified by type, and the component that has been
added or removed is specified by comp.
The different ContainerEvent Class Methods include:
■​ Container getContainer(): It is used to obtain a reference to the
container that generates this event.
■​ Container getChild(): It returns a reference to the component that
was added to or removed from the container.

○​ InputEvent Class - This abstract class is a subclass of ComponentEvent


and is the superclass for component input events. KeyEvent and
MouseEvent are its subclasses.
The InputEvent class defines the following eight integer constants that can
be used to obtain information about any modifiers associated with this
event - ALT_MASK, ALT_GRAPH_MASK, BUTTON1_MASK,
BUTTON2_MASK, BUTTON3_MASK, CTRL_MASK, META_MASK,
SHIFT_MASK
The methods isAltDown(), isAltGraphDown(), isControlDown(),
isMetaDown() and isShiftDown() are used to test whether these modifiers
were pressed at the time this event was generated. All these methods
return a boolean value.
The getModifiers() method returns a value that contains all of the modifier
flags for this event. Its form is : int getModifiers()

○​ ItemEvent Class - An ItemEvent is generated when a check box or list item


is clicked or when a checkable menu item is selected or deselected.
There are two types of item events and they are identified by the following
integer constants :
■​ DESELECTED The user deselects an item
■​ SELECTED The user selects an item
This class also defines one integer constant ITEM_STATE_CHANGED
which signifies a change of state.
The constructor is
■​ ItemEvent(ItemSelectable src, int type, Object entry, int state)
src is a reference to the component that generated the event, type
specifies the type of the event. The specific item that generated the item
event is passed in entry, and the current state of that item is passed in
state.
The different ItemEvent Class include:
■​ Object getItem(): It can be used to obtain a reference to the item that
generated an event.
■​ ItemSelectable getItemSelectable( ): It can be used to obtain a
reference to the ItemSelectable object that generated an event.
■​ int getStateChange( ): It returns the state change (that is,
SELECTED or DESELECTED) for the event.

○​ KeyEvent Class - A KeyEvent is generated when a keyboard input occurs.


There are three types of key events which are identified by the integer
constants : KEY_PRESSED, KEY_RELEASED, KEY_TYPED. The first
two events are generated when any key. KeyEvent is a subclass of
InputEvent.
Its constructors are :
■​ KeyEvent(Component src, int type, long when, int modifiers, int code,
char ch) - where src is a reference to the component that generated
the event, type of the event is specified by type.The system time at
which the key was pressed is passed in when. The modifiers
argument indicates which modifiers were pressed when this key
event occured. The virtual key code is passed in code. The character
equivalent, if it exists, is passed in ch. If no valid character exists,
then ch contains CHAR_UNDEFINED.
The commonly used methods of the KeyEvent class are :
■​ char getKeyChar( ) : It returns the character that was entered.
■​ int getKeyCode( ) : It returns the key code.

○​ MouseEvent Class - MouseEvent is a subclass of InputEvent. There are


eight types of mouse events. The MouseEvent class defines the following
integer constants that can be used to identify them: MOUSE_CLICKED,
MOUSE_DRAGGED, MOUSE_ENTERED, MOUSE_EXITED,
MOUSE_MOVED, MOUSE_PRESSED, MOUSE_RELEASED and
MOUSE_WHEEL.
It has the following constructor
■​ MouseEvent(Component src, int type, long when, int modifiers, int x,
int y, int clicks, boolean triggersPopup)
The most commonly used methods of this class are int getX() and int
getY() which return the coordinates of the mouse when the event occured.

○​ WindowEvent Class - There are seven types of window events and the
WindowEvent class defines integer constants to identify them.
The constants are : WINDOW_ACTIVATED, WINDOW_CLOSED,
WINDOW_CLOSING WINDOW_DEACTIVATED.WINDOW_DEICONIFIED
WINDOW_ICONIFIED. WINDOW_OPENED
WindowEvent is a subclass of ComponentEvent and its constructor is :
■​ WindowEvent(Window src, int type) - where src is a reference to the
object that generated this event and type is the type of the event.
getWindow() is the most commonly used method of this class and it returns
the Window object that generated this event. Its general form is : Window
getWindow()

Applets
107.​ Explain Applets
○​ A Java applet is a special kind of Java program that a browser enabled
with Java technology can download from the internet and run.
○​ An applet is typically embedded inside a web page and runs in the context
of a browser.
○​ An applet must be a subclass of the java.applet.Applet class.
○​ The Applet class provides the standard interface between the applet and
the browser environment.
○​ In addition, java.applet package also defines three interfaces:
AppletContext, AudioClip, and AppletStub

108.​ Difference between Applets & Applications


109.​ Describe the Skeleton of an Applet Program
○​ Applets override a set of methods which provide the basic mechanism by
which the browser or applet viewer interfaces to the applet and controls its
execution.
○​ Four of these methods init(), start(),stop() and destroy() are defined by
Applet. The method paint() is defined by the AWT Component class.
○​ These five methods can be assembled into the skeleton shown below:
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet
{
// Called first.
​ public void init()
​ {
// initialization
}
/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start()
{
// start or resume execution
}
// Called when the applet is stopped.
public void stop()
{
// suspends execution
}
/* Called when the applet is terminated. This is the last
method executed. */
public void destroy()
{
​ ​ // perform shutdown activities
​ }
// Called when an applet's window must be restored.
public void paint(Graphics g)
{
​ ​ // redisplay contents of window
}
}
○​ When an applet begins, the AWT calls the following methods, in this
sequence:
■​ init() - This is the first method to be called. This is where variables
should be initialised. This method is called only once during the
runtime of your applet.
■​ start() - The start( ) method is called after init( ). It is also called to
restart an applet after it has been stopped(i.e start() method is called
every time the applet resumes execution).
■​ paint() - The paint( ) method is called each time your applet’s output
must be redrawn. This situation can occur for several reasons.
Whatever the cause, whenever the applet must redraw its output,
paint( ) is called. The paint( ) method has one parameter of type
Graphics.
○​ When an applet is terminated, the following sequence of method calls
takes place:
■​ stop() - :The stop() method is called when the applet is stopped(i.e
for example ,when the applet is minimised the stop method is called).
■​ destroy() - The destroy( ) method is called when the environment
determines that your applet needs to be removed completely from
memory(i.e destroy() method is called when the applet is about to
terminate).The stop( ) method is always called before destroy( ).
110.​ What is the use of the repaint() method?
○​ The repaint() is intended to allow various methods to call for a re-rendering
of the component. No graphics context is needed for repaint(). A call to
repaint() calls update()

111.​ Define update() method


○​ update() is a method defined by AWT. This method is called when your
applet has requested that a portion of its window be redrawn.The default
implementation of update(): first clears the background; then calls paint().
112.​ How do you pass parameters to an Applet
113.​ Which methods do you use to load data in the Applet?

Swing
114.​ What is Swing?
○​ Swings are used to develop a better efficient GUI.
○​ The Swing component is part of JFC (Java Foundation Classes) which are
developed in Java.
○​ The Swing components are called lightweight components which will
improve the performance of the application because the amount of
resources required is very minimum.
○​ Swing is not a replacement for AWT but is an extension of AWT.
○​ Features of Swing:
■​ It provides a lightweight architecture.
■​ It provides support for the look and feels management.
■​ It allows us to add images to the background of UI Components.
■​ It provides advanced classes that support fro latest UI Components
creation like Dialog boxes, etc.

115.​ Explain any five Swing Components.


○​ Icons - In Swing, icons are encapsulated by the ImageIcon class, which
paints an icon from an image.
Its constructors are :
■​ ImageIcon(String filename) - uses the image in the file named
filename.
■​ ImageIcon(URL url) - uses the image in the resource identified by url.
ImageIcon class implements the Icon interface which declares the following
methods :
■​ int getIconHeight() - returns the height of the icon in pixels
■​ int getIconWidth() - returns the width of the icon in pixels
■​ void paintIcon(Component comp,Graphics g, int x, int y) - paints the
icon at position x, y on the graphics context g.

○​ JLabel - Swing labels are instances of the JLabel class which extends
JComponent. It can display text and/or icon.
Syntax: JLabel jlab = new JLabel();
The different constructors are:
■​ JLabel(Icon i)
■​ JLabel(String s)
■​ JLabel(String s, Icon i, int align)
Where s and i are the text and icon used for the label. The align argument
is either LEFT, RIGHT or CENTER. These constants are defined in the
SwingConstants interface.
The methods with which the icons and the text associated with the label
can be read and written are :
■​ Icon getIcon()
■​ void setIcon(Icon i)
■​ String getText()
■​ void setText(String s)
where i and s are icon and text respectively.

○​ JTextField - JTextComponent encapsulates the Swing text field and


extends JComponent. One of its subclasses is the JTextField which allows
you to edit a single line of text.
Syntax: JTextField jtf = new JTextField();
Some of its constructors are :
■​ JTextField()
■​ JTextField(int cols)
■​ JTextField(String s)
■​ JTextField(String s, int cols)
s is the string to be presented and cols is the number of columns in the text
field.

○​ JButton - This class allows an icon, a string or both to be associated with a


push button.
Syntax: JButton jb = new JButton();
Some of its constructors are :
■​ JButton(Icon i)
■​ JButton(String s)
■​ JButton(String s, Icon i)
where s and i are string and icon used for the button respectively.

○​ JCheckBox - The JCheckBox class provides the functionality of the check


box and it is a concrete implementation of AbstractButton.
○​ Some of its constructors are :
■​ JCheckBox(Icon i)
■​ JCheckBox(String s)
■​ JCheckBox(Icon i, boolean state)
■​ JCheckBox(String s, boolean state)
■​ JCheckBox(String s, Icon i)
■​ JCheckBox(String s, Icon i, boolean state)
○​ where i is the icon for the button, s specifies the text. If state is true, then
the checkbox is initially selected, otherwise it is not.
○​ The state of the checkbox can be changed with the following method :
■​ void setSelected(boolean state)
○​ Whenever a check box is slected or deselected an item event is generated.
This is handled by the itemStateChanged() method

○​ JRadioButton - Radio Buttons are supported by the JRadioButton class,


which is a concrete implementation of AbstractButton. Some of its
constructors are :
■​ JRadioButton(Icon i)
■​ JRadioButton(String s)
■​ JRadioButton(String s, Icon i)
■​ JRadioButton(Icon i, boolean state)
■​ JRadioButton(String s, boolean state)
■​ JRadioButton(String s, Icon i, boolean state)
○​ where i is the icon for the button, s specifies the text. If state is true, the
button is initially selected, otherwise not.

○​ JTextArea

116.​ Difference between Swing and AWT


Swing AWT
It doesn’t depend on peer classes. AWT package-based classes must
depend on peer classes for creating UI
components.
It makes Java platform-independent. It makes Java platform-dependent.
It follows the Model View Controller(MVC) It doesn’t follow the MVC architecture
architecture style. pattern.

117.​ Write a detailed note on the tree components of Swing.

You might also like