Advanced Java Question Bank Answers

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

ADVANCED JAVA QUESTION BANK ANSWERS

1. Explain String comparison Functions?


Ans: The String class includes a number of methods that
compare strings or substrings within strings. Several are
examined here.
1.equals( ) and equalsIgnoreCase( )
To compare two strings for equality, use equals( ). It has this general form:
booleanequals(Object str)
Here, str is the String object being compared with the invoking String object. It returns
true if the strings contain the same characters in the same order, and false otherwise. The
comparison is case-sensitive.
class equalsDemo {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}
The output from the program is shown here:
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
2.regionMatches()
 The regionMatches( ) method compares a specific region inside a string with another
specific region in another string.
 Two types of comparisons are there
1.Ignoring the case of the string
2.considering the case of the string
 Formats for two types of comparison are
booleanregionMatches(int startIndex, String str2,int str2StartIndex, int numChars)
booleanregionMatches(booleanignoreCase, int startIndex, String str2, int
str2StartIndex, int numChars)
3.startsWith( ) and endsWith( )
 String defines two methods that are, more or less, specialized forms of
regionMatches( ). The startsWith( ) method determines whether a given String
begins with a specified string. Conversely, endsWith( ) determines whether the
String in question ends with a specified string.
 They have the following general forms:
booleanstartsWith(String str)
booleanendsWith(String str)
4.equals( ) Versus ==
 The equals( ) method compares the characters insidea String object.
 The == operator compares two object references to see whether they refer tothe same
instance.
 The following program shows how two different String objects cancontain the same
characters, but references to these objects will not compare as equal:
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
5.compareTo( )
 The method compareTo() is used to check whether stringis less than another
if it comes before the other in dictionary order. A string is greater thananother
if it comes after the other in dictionary order.
 It is specified by the Comparable<T> interface, which String implements.
 It hasthis general form:
int compareTo(String str)
 Here, str is the String being compared with the invoking String.

2. Briefly explain about modifying a string?


Ans: Modifying a String
 String objects are immutable,in order to modify a String, either copy it into a StringBuffer or
StringBuilder, or use a String method that constructs a new copy of the string with your modifications
complete. A sampling of these methods are described here.
 substring( )
 To extract a substring using substring( ). It has two forms.
 String substring(int startIndex)
 String substring(int startIndex, int endIndex)
 class StringReplace {
 public static void main(String[] args) {
 String org = "This is a test. This is, too.";
 String search = "is";
 String sub = "was";
 String result = "";
 int i;
 do { // replace all matching substrings
 System.out.println(org);
 i = org.indexOf(search);
 if(i != -1) {
 result = org.substring(0, i);
 result = result + sub;
 result = result + org.substring(i + search.length());
 org = result;
 }
 } while(i != -1);
 }
 }
 The output from this program is shown here:
 This is a test. This is, too.
 Thwas is a test. This is, too.
 Thwas was a test. This is, too.
 Thwas was a test. Thwas is, too.
 Thwas was a test. Thwas was, too

 concat( )
 String concat(String str)
 This method creates a new object that contains the invoking string with the contents
of str appended to the end. concat( ) performs the same function as +. For example,
 String s1 = "one"; String s2 = s1.concat("two");
 puts the string "onetwo" into s2. It generates the same result as the following
sequence:
 String s1 = "one"; String s2 = s1 + "two";
 replace( )
 The replace( ) method has two forms. The first replaces all occurrences of one
character in the invoking string with another character. It has the following general
form:
 String replace(char original, char replacement)
 Here, original specifies the character to be replaced by the character specified by
replacement.
 trim( ) and strip( )
 The trim( ) method returns a copy of the invoking string from which any leading and
trailing spaces have been removed. As it relates to this method, spaces consist of those
characters with a value of 32 or less.
 The trim( ) method has this general form:
 String trim( )
 Here is an example:
 String s = " Hello World ".trim();

3. Write a note on String Buffer.?


Ans: StringBuffer defines these four constructors:
StringBuffer( ) StringBuffer(int size) StringBuffer(String str)
StringBuffer(CharSequence chars)
The default constructor (the one with no parameters) reserves room for 16 characters
without reallocation. The second version accepts an integer argument that explicitly sets
the size of the buffer. The third version accepts a String argument that sets the initial
contents of the StringBuffer object and reserves room for 16 more characters without
reallocation. StringBuffer allocates room for 16 additional characters when no specific
buffer length is requested, because reallocation is a costly process in terms of time.
Also, frequent reallocations can fragment memory. By allocating room for a few extra
characters, StringBuffer reduces the number of reallocations that take place. The fourth
constructor creates an object that contains the character sequence contained in chars and
reserves room for 16 more characters.
public class Main {

public static void main(String[] args) {

// Create a StringBuffer object

StringBuffer stringBuffer = new StringBuffer("Hello");

// Append method

stringBuffer.append(", World!");

// Append a string

System.out.println("After append: " + stringBuffer);

// Insert method

stringBuffer.insert(5, " Java");


// Insert a string at index 5

System.out.println("After insert: " + stringBuffer);

// Delete method

stringBuffer.delete(5, 10);

// Delete characters from index 5 to index 9

System.out.println("After delete: " + stringBuffer);

// Reverse method

stringBuffer.reverse();

// Reverse the string

System.out.println("After reverse: " + stringBuffer);

// Replace method

stringBuffer.replace(0, 5, "Hola");

// Replace characters from index 0 to index 4 with "Hola"

System.out.println("After replace: " + stringBuffer);

// Capacity and length methods

int capacity = stringBuffer.capacity();

// Get the current capacity

int length = stringBuffer.length();

// Get the current length

System.out.println("Capacity: " + capacity);

System.out.println("Length: " + length);

// Set length method

stringBuffer.setLength(5);

// Set the length of the string to 5

System.out.println("After setting length: " + stringBuffer);

Output

After append: Hello, World!

After insert: Hello Java, World!

After delete: Hello, World!


After reverse: !dlroW ,olleH

After replace: HolaW ,olleH

Capacity: 21

Length: 12

After setting length: HolaW

4. Discuss in detail trim() and strip() methods?


Ans: The trim( ) method returns a copy of the invoking string from which any
leading and trailing spaces have been removed. As it relates to this method, spaces
consist of those characters with a value of 32 or less.
The trim( ) method has this general form:
String trim( )
Here is an example:
String s = " Hello World ".trim();
This puts the string "Hello World" into s.
The trim( ) method is quite useful when you process user commands. For example,
the following program prompts the user for the name of a state and then displays that
state’s capital. It uses trim( ) to remove any leading or trailing spaces that may have
inadvertently been entered by the user.
// Using trim() to process commands.
import java.io.*;
class UseTrim {
public static void main(String[] args)
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in, System.console().charset()));
String str;
System.out.println("Enter 'stop' to quit.");
System.out.println("Enter State: ");
do {
str = br.readLine();
str = str.trim(); // remove whitespace
if(str.equals("Illinois"))
System.out.println("Capital is Springfield.");
else if(str.equals("Missouri"))
System.out.println("Capital is Jefferson City.");
else if(str.equals("California"))
System.out.println("Capital is Sacramento.");
else if(str.equals("Washington"))
System.out.println("Capital is Olympia.");
// ...
} while(!str.equals("stop"));
}
}
Beginning with JDK 11, Java also provides the methods strip( ), stripLeading( ), and
stripTrailing( ). The strip( ) method removes all whitespace characters (as defined by
Java)from the beginning and end of the invoking string and returns the result. Such
whitespace characters include, among others, spaces, tabs, carriage returns, and line
feeds.

5. Implement a java program to illustrate the use of


different types of string buffer methods.?
Ans: public class Main {
public static void main(String[] args) {

// Create a StringBuffer object

StringBuffer stringBuffer = new StringBuffer("Hello");

// Append method

stringBuffer.append(", World!");

// Append a string

System.out.println("After append: " + stringBuffer);

// Insert method

stringBuffer.insert(5, " Java");

// Insert a string at index 5

System.out.println("After insert: " + stringBuffer);

// Delete method

stringBuffer.delete(5, 10);

// Delete characters from index 5 to index 9

System.out.println("After delete: " + stringBuffer);

// Reverse method

stringBuffer.reverse();

// Reverse the string


System.out.println("After reverse: " + stringBuffer);

// Replace method

stringBuffer.replace(0, 5, "Hola");

// Replace characters from index 0 to index 4 with "Hola"

System.out.println("After replace: " + stringBuffer);

// Capacity and length methods

int capacity = stringBuffer.capacity();

// Get the current capacity

int length = stringBuffer.length();

// Get the current length

System.out.println("Capacity: " + capacity);

System.out.println("Length: " + length);

// Set length method

stringBuffer.setLength(5);

// Set the length of the string to 5

System.out.println("After setting length: " + stringBuffer);

Output

After append: Hello, World!

After insert: Hello Java, World!

After delete: Hello, World!

After reverse: !dlroW ,olleH

After replace: HolaW ,olleH

Capacity: 21

Length: 12

After setting length: HolaW

6. .Implement a java program to illustrate the use of


different types of character extraction,string
comparison,string search and string modification
methods?
Ans: public class Main {
public static void main(String[] args) {

// Character extraction

String str = "Hello, World!";

char firstChar = str.charAt(0);

// Extract the first character

char lastChar = str.charAt(str.length() - 1);

// Extract the last character

System.out.println("First character: " + firstChar);

System.out.println("Last character: " + lastChar);

// Substring extraction

String substring = str.substring(7);

// Extract substring from index 7 to end

System.out.println("Substring: " + substring);

// String comparison

String str1 = "hello";

String str2 = "HELLO";

boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2);

// Compare ignoring case

System.out.println("Strings are equal ignoring case: " + isEqualIgnoreCase);

// String search

int indexOfComma = str.indexOf(',');

// Find index of first occurrence of ','

System.out.println("Index of comma: " + indexOfComma);

// String modification

String modifiedStr = str.replace("Hello", "Hi");

// Replace "Hello" with "Hi"

System.out.println("Modified string: " + modifiedStr);


// String concatenation

String concatStr = str.concat(" How are you?");

// Concatenate another string

System.out.println("Concatenated string: " + concatStr);

// String trimming

String paddedStr = " Trim me ";

String trimmedStr = paddedStr.trim();

// Trim leading and trailing whitespace

System.out.println("Trimmed string: " + trimmedStr);

// String case conversion

String lowerCaseStr = str.toLowerCase();

// Convert to lower case

String upperCaseStr = str.toUpperCase();

// Convert to upper case

System.out.println("Lower case: " + lowerCaseStr);

System.out.println("Upper case: " + upperCaseStr);

Output

First character: H

Last character: !

Substring: World!

Strings are equal ignoring case: true

Index of comma: 5

Modified string: Hi, World!

Concatenated string: Hello, World! How are you?

Trimmed string: Trim me

Lower case: hello, world!

Upper case: HELLO, WORLD!

7. Explain painting in swing with example?


Ans: The paint() method is used to place code for drawing and writing. It's called by both the
system and the app when there's a paint request, and it's also called when a rendering is damaged,
like when it's partially covered by another window. Swing uses a bit more sophisticated approach to
painting that involves three distinct methods:

paintComponent( )

paintBorder( )

paintChildren( ).

 paintComponent The main painting method, which paints the background if the component is
opaque, and then performs any custom painting.

 paintBorder Tells the component's border to paint, if it has one. It's not recommended to invoke or
override this method.

 paintChildren Tells any components contained by this component to paint themselves. It's also not
recommended to invoke or override this method .

Compute the Paintable Area 

Swing automatically clips any output that will exceed the boundaries of a component, it is still
possible to paint into the border, which will then get overwritten when the border is drawn

A Paint Example

// Paint lines to a panel.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.util.*;

// This class extends JPanel. It overrides

// the paintComponent() method so that random

// lines are plotted in the panel.

class PaintPanel extends JPanel {

Insets ins;

// holds the panel’s insets

Random rand;

// used to generate random numbers

// Construct a panel.

PaintPanel() {

// Put a border around the panel.


setBorder( BorderFactory.createLineBorder(Color.RED, 5));

rand = new Random();

// Override the paintComponent() method.

protected void paintComponent(Graphics g) {

// Always call the superclass method first.

super.paintComponent(g);

int x, y, x2, y2;

// Get the height and width of the component.

int height = getHeight();

int width = getWidth();

// Get the insets.

ins = getInsets();

// Draw ten lines whose endpoints are randomly generated.

for(int i=0; i < 10; i++) {

// Obtain random coordinates that define

// the endpoints of each line.

x = rand.nextInt(width-ins.left);

y = rand.nextInt(height-ins.bottom);

x2 = rand.nextInt(width-ins.left);

y2 = rand.nextInt(height-ins.bottom);

// Draw the line.

g.drawLine(x, y, x2, y2);

8. Discuss in detail
1.JLabel
2.ImageIcon
Ans: JLabel and ImageIcon :
JLabel is Swing’s easiest-to-use component. It creates a label and was introduced in the JLabel can
be used to display text and/or an icon.

It is a passive component in that it does not respond to user input.

JLabel defines several constructors. Here are three of them:

JLabel(Icon icon)

JLabel(String str)

JLabel(String str, Icon icon, int align)

 Here, str and icon are the text and icon used for the label. The align argument specifies the
horizontal alignment of the text and/or icon within the dimensions of the label. It must be one of the
following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. These constants are defined in the
SwingConstants interface, along with several others used by the Swing classes.

The icon and text associated with the label can be obtained by the following methods: Icon
getIcon( ) String getText( )

The icon and text associated with a label can be set by these methods: void setIcon(Icon icon) void
setText(String str)

//Example program

import java.awt.*;

import javax.swing.*;

public class JLabelDemo {

public JLabelDemo() {

// Set up the JFrame.

JFrame jfrm = new JFrame("JLabelDemo");

jfrm.setLayout(new FlowLayout());

jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jfrm.setSize(260, 210);

// Create an icon.

ImageIcon ii = new ImageIcon("hourglass.png");

// Create a label.

JLabel jl = new JLabel("Hourglass", ii, JLabel.CENTER);

// Add the label to the content pane.

jfrm.add(jl);

// Display the frame.


jfrm.setVisible(true);

public static void main(String[] args) {

// Create the frame on the event dispatching thread.

SwingUtilities.invokeLater

new Runnable()

public void run() {

new JLabelDemo();

);

9.Discuss in detail swing buttons?


Ans:Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton.
All are subclasses of the AbstractButton class, which extends JComponent. Thus, all buttons share a
set of common traits.

JButton :
The JButton class provides the functionality of a push button. JButton allows an icon, a string, or
both to be associated with the push button.  Three of its constructors are shown here: JButton(Icon
icon) JButton(String str) JButton(String str, Icon icon)  Here, str and icon are the string and icon used
for the button.

JToggleButton:
A useful variation on the push button is called a toggle button. A toggle button looks just like a push
button, but it acts differently because it has two states: pushed and released. That is, when you press
a toggle button, it stays pressed rather than popping back up as a regular push button does.

Check Boxes :
 The JCheckBox class provides the functionality of a check box. Its immediate superclass is
JToggleButton, which provides support for two-state buttons, as just described. JCheckBox defines
several constructors. The one used here is o JCheckBox(String str).

Radio Buttons :
Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at
any one time. They are supported by the JRadioButton class, which extends JToggleButton.
JRadioButton provides several constructors. The one used in the example is shown here: 
JRadioButton(String str)  Here, str is the label for the button. Other constructors let you specify the
initial selection state of the button and specify an icon.

// Demonstrate button

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class JToggleButtonDemo {

public JToggleButtonDemo() {

// Set up the JFrame.

JFrame jfrm = new JFrame("JToggleButtonDemo");

jfrm.setLayout(new FlowLayout());

jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jfrm.setSize(200, 100);

// Create a label.

JLabel jlab = new JLabel("Button is off.");

// Make a toggle button.

JToggleButton jtbn = new JToggleButton("On/Off");

// Add an item listener for the toggle button.

jtbn.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent ie) {

if(jtbn.isSelected()) jlab.setText("Button is on.");

else jlab.setText("Button is off.");

);
// Add the toggle button and label to the content pane.

jfrm.add(jtbn); jfrm.add(jlab);

// Display the frame.

jfrm.setVisible(true);

public static void main(String[] args) {

// Create the frame on the event dispatching thread.

SwingUtilities.invokeLater( new Runnable() {

public void run() {

new JToggleButtonDemo();

);

10. What is swing ?Explain key features of swing?


Ans: Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window
Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components, expanded
components features, and excellent event handling with drag-and-drop support

Two Key Swing Features:


1.Swing Components Are Lightweight: With very few exceptions,
Swing components are lightweight. This means that they are written entirely in Java and do not map
directly to platform-specific peers. Thus, lightweight components are more efficient and more
flexible. Furthermore, because lightweight components do not translate into native peers, the look
and feel of each component is determined by Swing, not by the underlying operating system. As a
result, each component will work in a consistent manner across all platforms.

2.Swing Supports a Pluggable Look and Feel:


 Swing supports a pluggable look and feel (PLAF). Because each Swing component is rendered by
Java code rather than by native peers, the look and feel of a component is under the control of
Swing. This fact means that it is possible to separate the look and feel of a component from the logic
of the component, and this is what Swing does..  Pluggable look-and-feels offer several important
advantages. It is possible to define a look and feel that is consistent across all platforms. Conversely,
it is possible to create a look and feel that acts like a specific platform. It is also possible to design a
custom look and feel. Finally, the look and feel can be changed dynamically at run time.

11. Explain components and containers?


Ans: Components :
In general, Swing components are derived from the JComponent class. JComponent provides the
functionality that is common to all components. For example, JComponent supports the pluggable
look and feel. JComponent inherits the AWT classes Container and Component. Thus, a Swing
component is built on and compatible with an AWT component.  All of Swing’s components are
represented by classes defined within the package javax.swing. The following table shows the class
names for Swing components . .

JApplet (Deprecated) JButton JCheckBox JCheckBoxMe nuItem


JColorChooser JComboBox JComponent JDesktopPane
JDialog JEditorPane JFileChooser JFormattedText Field
JFrame JInternalFrame JLabel JLayer

Containers:
Swing defines two types of containers. The first are top-level containers: JFrame, JApplet, JWindow,
and JDialog. These containers do not inherit JComponent. They do, however, inherit the AWT classes
Component and Container. Unlike Swing’s other components, which are lightweight, the top-level
containers are heavyweight. This makes the top-level containers a special case in the Swing
component library.  A top-level container is not contained within any other container. Furthermore,
every containment hierarchy must begin with a top-level container. The one most commonly used for
applications is JFrame. In the past, the one used for applets was JApplet.  As a result, JApplet is also
deprecated for removal. Furthermore, beginning with JDK 11, applet support has been removed. 
The second type of containers supported by Swing are lightweight containers. Lightweight containers
do inherit JComponent. An example of a lightweight container is JPanel, which is a general-purpose
container. Lightweight containers are often used to organize and manage groups of related
components because a lightweight container can be contained within another container. Thus, you
can use lightweight containers such as JPanel to create subgroups of related controls that are
contained within an outer container.

12. .Explain event handling in swing?


Ans: The event handling mechanism used by Swing is the same as that used by the AWT. This
approach is called the delegation event model,  In many cases, Swing uses the same events as does
the AWT, and these events are packaged in java.awt.event. Events specific to Swing are stored in
javax.swing.event.

// Handle an event in a Swing program.

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

class EventDemo {

JLabel jlab; EventDemo() {

// Create a new JFrame container.

JFrame jfrm = new JFrame("An Event Example");

// Specify FlowLayout for the layout manager.

jfrm.setLayout(new FlowLayout());

// Give the frame an initial size.

jfrm.setSize(220, 90);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Make two buttons.

JButton jbtnAlpha = new JButton("Alpha");

JButton jbtnBeta = new JButton("Beta");

// Add action listener for Alpha.

jbtnAlpha.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {

jlab.setText("Alpha was pressed.");

);

// Add action listener for Beta.

jbtnBeta.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae)

jlab.setText("Beta was pressed.");

);

// Add the buttons to the content pane.


jfrm.add(jbtnAlpha);

jfrm.add(jbtnBeta);

// Create a text-based label.

jlab = new JLabel("Press a button.");

// Add the label to the content pane.

jfrm.add(jlab);

// Display the frame.

jfrm.setVisible(true);

public static void main(String[] args) {

// Create the frame on the event dispatching thread.

SwingUtilities.invokeLater(new Runnable() {

public void run()

new EventDemo();

);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy