FAQ in Java Programming
Find the Next Greatest Element of Integers in Main Array
Write a Program in a high level language like JAVA
Next Greater Element I (LeetCode 496) Problem Description:
1.You are given two integer arrays nums1 and nums2 where nums1 is a subset of numbers
2. For each element of nums1, find its next greater element in nums2. If it does not exist, return -1 for that element.
Program in Java:
package compare2arays;
import java.io.DataInputStream;
import java.io.IOException;1
/**
*
* @author MAXHUB
*/
public class Compare2Arays {
public static void main(String[] args) throws IOException
{
DataInputStream din;
int arrMain[] = new int[10];
int arrSub[] = new int[10];
int i,j, nextHigh=0, iHigh=0;
din = new DataInputStream(System.in);
System.out.println("Enter upto 10 numbers for Main Array:");
for(i=0; i<10; i++)
{
j = Integer.parseInt(din.readLine());
if (j==0)
break;
else
arrMain[i] = j;
}
System.out.println("Enter upto 10 numbers for Sub Array:");
for(i=0; i<10; i++)
{
j = Integer.parseInt(din.readLine());
if (j==0)
break;
else
arrSub[i] = j;
}
System.out.println("Next Highest Element of Integers of Main Array:");
for(i=0; i<10; i++)
{
if(arrMain[i] > 0)
{
nextHigh = -1;
for(j=0; j<10; j++)
{
if(arrMain[i] < arrSub[j])
if(nextHigh == -1)
nextHigh = arrSub[j];
else if(nextHigh > arrSub[j])
nextHigh = arrSub[j];
}
System.out.println(" " + nextHigh);
}
}
}
}
Sample Run:
Solve Candy Distribution Problem using Computer
Defining and Implementing Interfaces in Java
A class is a container for both data and methods. The public methods of a class are also called as interfaces to the private data (instance variables) hidden withi in a class.
An abstract class in Java, is an abstract one, i.e., it includes abstract methods as a part of it. An abstract method has only the signature part of a method, without implementation (the body). Hence, an abstract class can't be used for object creation. Another class that extends the abstract class must provide the implementation of each of the abstract class defined in the abstract class before object creation.
An interface is similar to an abstract class, but contains only abstract methods and one or more final (static) variables. Through interface, Java abstracts (separates) the implementation part of all methods defined in an interface from their implementation. Thus, an interface specifies what must be done, but not how.
Defining an Interface
Implementing an Interface
- Define a class that implements the interface using the keyword implements (not using extends keyword)
- With in the body of the class that implements, provide the code that implements the methods defined in the interface.
Interface References
- Define two Interfaces named Square and Rectangle with method a single method computeArea(), which is overloaded with their various parameters.
- Implement both interfaces in a class named Area by providing code for computeArea() of both interfaces.
- Implement the method main() in another java file named MulInterface.java for creating the objects of Area and to compute the area for both square and rectangle.
- In method main(), declare the variables s, l and w of type float. Also create input object - din of type DataInputStream
- Declare a variable (objA) of type Area and create an object for it.
- Get the value of s from the user and call the method computeArea() of objA with s as the parameter to compute the area of square.
- Get the value of l and w from the user and call the method computeArea() of objA with l and w as parameters to compute the area of rectangle.
- Display the result – area of square and area of rectangle

Accessing Parent Class from a Sub Class in Inheritance
In a hierarchy of classes, it is possible for both super class and sub class to have their own constructors - one in the super class and the other one in the sub class. Now, when we create an object of the super class, the super class constructor is responsible for creating the super class object.
Suppose, we create the object of the sub class, both constructors are responsible for creating the object of the sub class. The constructor of the super class constructs the super class portion of the object, and the constructor of the sub class constructs the sub class part of the object.
super() method & super keyword
When both the super class and the sub class define their own constructors, it is the responsibility of the sub class to invoke the super class constructor before it does its initialization of the sub class portion of the object. This process of calling the constructor of the super class from the constructor of the sub class is done with the help of super() method.
Calling the method super() without arguments will call the default constructor of the super class, whereas calling super() with arguments will invoke a parameterized constructor of the super class for initializing the super class for initializing the super class portion of the object.
'super' keyword acts as a reference to the super class object. Using the keyword - super, we can access the members of the super class (both variables and methods). super keyword is also required to access the members (variables/methods) of the super class when they are hidden by the members of the sub class by name.
Order of Execution of Constructors
At the time of object creation of a sub class, the order of execution of constructors (of base class and derived class) is determined based on their order of derivation. They are executed in the same order of their derivation, that means, base class constructor will be executed first, followed by the constructor of the derived class.
Since super() must be the first statement to be called in the sub class' constructor, the order is the same whether or not super() is called explicitly from the sub class. If super() is not used as the first statement, the default constructor of the super class will be called implicitly.
Super class Reference and Sub Class Object
In general, an object reference variable can refer only to object of its type. However, a reference variable of a super class can be used to point to the object of any of its sub classes derived from it. In other words, a super class reference can refer to the object of any of its sub classes.
It is important to note that it is the type of the reference variable, and not the type of object that it referes to - determines the members that can be accessed in an object created in a hierarchy of objects. That means, when a reference to a super class is assigned a reference to the object of its sub class, it can have access only to those members of the object defined by the super class.
Method Overriding
In a class hierarchy, when a method in a sub class has the same name, return type and parameters as same as that of its super class, then the method of the sub class is said to override the method of the super class.
When the overridden method is called from an object of sub class, it will always refer to the overridden method of the sub class. The base class version of the overridden method in the sub class is hidden after overriding.
To prevent a method from being overridden in a sub class, use the keyword - final as a modifer at the start of its declaration in the base class. Methods declared as final can't be overrdden in a sub class.
Abstract class
Abstrat class is a super class that has one or more abstract methods declared in it. An abstract class determines the generalized form of one or more behavior of a class of objects. It doesn't provide the implementation of one or more of its methods, leaving it to each sub class to fill in the details.
An abstract class can't be used for object creation. Instead it can be used to define another class that implements the code for all abstract methods of the base class, and then the objects be created using the derived class. That means, objects can't be directly created using an abstract class, but through a child class that implements all the abstract methods of the base class.
The Object Class
Java has a special class class Object class, which is at the top of the hierarchy of classes defined in Java. By default, Object class is the super class of all other classes in the hierarchy, i.e., all other classes are sub classes of Object class. And hence, a reference variable of type Object can refer to an object of any other class in Java.
Some of the methods defined in Object class are as follows:
- Object clone() - This method creates a new object that is same as the object being cloned
- boolean equals(Object object) - determines whether one object is equal to another
- void finalize() - This is the last method to be called before an unused object is recycled. This method can be used for freeing the resources utilized by the object.
- class <?> getClass() - obtains the class of an object at run time
- int hasCode() - returns the has code associated with the invoking object
- String toString() - returns a string that describes the object
Introduction to Abstract Window ToolKit (AWT) & Swing
AWT & Swing
AWT is a package that contains numerous classes and methods that allow a programmer to create and manage windows applications using Java. A collection of classes are provided in java.awt package for creating and running GUI (Graphical User Interface) applications in Java. java.awt is one of the largest packages provided by Java. AWT lays the foundation upon which Swing and Applets built.
AWT defines and manages a basic set of components that support a usable, but limited, graphical interface. One reason for the limited nature of the AWT is that its components rely on platform-specific native windows, or peers. Because of this they are referred to as heavy weight.
Two most common classes provided in AWT for creating windows applications are Panel and Frame. Panel is a type of window used by applets, whereas Frame is another type of window used by standard window application. Much of the functionality of window are defined in the base classes - Panel and Frame.
Swing Technology
Swing addresses the limitations associated with the AWT's components through the use of two key features: lightweight components and a pluggable look and feel. Swing components are lightweight. This means that a component is written entirely in Java. Lightweight components have two important advantages: efficiency and flexibility.
For example, a lightweight component can be transparent, which enables non rectangular shapes. Furthermore, because lightweight components do not translate into platform-specific peers, the look and feel of each component is determined by Swing. This means that each component can work in a consistent manner across all platforms.
Swing's pluggable look-and-feel is made possible because Swing uses a modified version of a classic component architecture called Model-View-Controller (MVC). In MVC terminology, the model corresponds to the state information associated with the component. For example, in the case of a check box, the model contains a field that indicates if the box is checked or unchecked.
The view determines how the component is displayed on the screen, including any aspects of the view that are affected by the current state of the model. The controller determines how the component reacts to the user. For example, when the user clicks on a check box, the controller reacts by changing the model to reflect the user's choice (checked or unchecked).
Containers and Components of Swing
A Swing GUI consists of two types of visual elements: Containers and Components. A component is an independent visual control, such as a push button or a text box, where as a container is a special type of component that is designed to hold other components. All Swing GUIs will have at least one container.
Because containers are components, a container can also hold other containers. Swing defines two types of containers: top-level containers and light-weight containers. Top-level containers are used to create and display main windows, and light-weight containers can be used to create child windows (window with in another window).
JFrame, JApplet, JWindow and JDialog are four classes that define the top-level containers in Java. A top-level container can't be contained within any other container. The commonly used top-level container for stand-along Windows applications is JFrame. The top-level container JApplet is used for creating the main window of Applets.
Light-weight containers are used for organizing and managing groups of related components collectively, because a light-weight container can be contained within another container. Moreover, light-weight containers are derived from the base class JComponent, which is the base class for all component classes. Examples of light-weight containers are JPanel and JRootPane.
Component Classes of Swing Package
All Swing components are derived from the parent class JComponent. The only exception to this are the top-level containers - JFrame, JWindow, JDialog and JApplet. JComponent provides the functionality that is common to all components of swing. JComponent inherits the AWT classes Container and Component and hence 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. All component classes in swing package begins with the letter J. The following are some of the component classes defined in this package:
JLabel - defines a label
JButton - defines a push button
JScrollBar - defines a scroll bar
Swing programs differ from the console-based applications by providing Graphical User Interface (GUI) elements for user interaction. Console-based applications make user of terminal (command-line) in which the input and output are handled in the form of text. Whereas swing applications are graphical applications in which Graphical User Interface (GUI) elements are used for user interaction.
There are two types of Java programs in which Swing classes are typically used. The first is a desktop application, and the second is the applet. Desktop applications are windows application that can run on a stand along computer. On the other hand, applets are java applications that run on a browser. They are used for developing client-side web application that usually runs on Internet.
Defining and Implementing Multiple Interfaces in Java
- Define two Interfaces named Square and Rectangle with method a single method computeArea(), which is overloaded with their various parameters.
- Implement both interfaces in a class named Area by providing code for computeArea() of both interfaces.
- Implement the method main() in another java file named MulInterface.java for creating the objects of Area and to compute the area for both square and rectangle.
- In method main(), declare the variables s, l and w of type float. Also create input object - din of type DataInputStream
- Declare a variable (objA) of type Area and create an object for it.
- Get the value of s from the user and call the method computeArea() of objA with s as the parameter to compute the area of square.
- Get the value of l and w from the user and call the method computeArea() of objA with l and w as parameters to compute the area of rectangle.
- Display the result – area of square and area of rectangle
Creating and Using Student Object for Managing Student Details
- Declare a Class named Student that define the student object with three data members namely RegNo, Name, and Marks. RegNo is of type int, Name is of type String and Marks is an array of int.
- Define methods setRegNo() and getRegNo() for storing and retrieving data from RegNo
- Define methods setName() and getName() for storing and retrieving data from Name
- Define methods setMarks() and getMarks() for storing and retrieving data from Marks array
- Declare 5 objects namely stud1, stud2, stud3, stud4 and stud5 of type Student in method main()
- Call the set methods and get methods for each and every object for storing and retrieving data from all five objects




