Java
Java
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
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.
Output:
Display member variable of outer : 69
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
Output:
Static block initialized
Inside main method
Value of j : 10
Value of n : 80
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
Output:
Student’s Name: Harsh
Student’s Age: 19
○ 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.
Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
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.
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.
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.
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.
Output:
running thread name is:Thread-0
running thread priority is:1
running thread name is:Thread-1
running thread priority is:10
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.
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);
}
}
○ 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
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.
○ 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
○ 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.
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.
○ 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
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.
○ 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.
○ JTextArea