Search This Blog

Showing posts with label Java Programming. Show all posts
Showing posts with label Java Programming. Show all posts
Tuesday, 4 February 2025

Find the Next Greatest Element of Integers in Main Array

0 comments

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:




Continue reading →
Friday, 22 December 2023

Solve Candy Distribution Problem using Computer

0 comments


Program in Java:

package assigncandies;
import java.io.DataInputStream;
import java.io.IOException;

public class AssignCandies {
    public static void main(String[] args) throws IOException
    {
        DataInputStream din;
        int i,n,minRating;
        int arrRating[] = new int[10];
        din = new DataInputStream(System.in);
        System.out.println("Enter the Total Number of Children Available :");
        n = Integer.parseInt(din.readLine());

        System.out.println("Enter Ratings of upto 10 Children.  Type 0 to quit:");

        for(i=0; i<n; i++)
        {
            arrRating[i] = Integer.parseInt(din.readLine());
 
        }
        
        minRating = arrRating[0];
        for(i=0; i<n; i++)
        {
          if(minRating > arrRating[i])
              minRating = arrRating[i];
        }
        
        int maxDistributed =1, cntCandies=0;
        for(i=0; i<n; i++)
        {
            if(arrRating[i] > minRating)
            {
                maxDistributed++;
                cntCandies = cntCandies + maxDistributed;
            }
            else
                cntCandies++;
        }
        System.out.println("The Minimum Number of Candies Required is:" + cntCandies);
    }
}

Sample Input and Output:






Continue reading →
Thursday, 22 December 2022

Defining and Implementing Interfaces in Java

0 comments

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.

In Java, interface is a structure like class that contains only the method signatures (like an abstract class) but not the data.  Using interface, we can specify what a class must do, with out specifying how it should be implemented. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body.

Unlike classes, multiple interfaces can be used for deriving a new class that will implement all its interfaces. Like abstract classes, interfaces can’t be used for object creation. They must be inherited to derive a new class, which will provide the implementation for all the abstract methods of the interface and then objects be created using it.

Defining an Interface

An interface is defined much like a class. This is the general form of declaring an interface:

access interface name
{
return_type method_name1(parameter list);
return_type method_name2(parameter list);
type final_varname1 = value;
type final_varname2 = value;
…………………
…………………
return_type method_nameN(parameter list);
type final_varnameN = value;
}
Here, access is either public or private. The default scope is private, i.e., the interface is only available to other members of the package in which it is declared. When it is declared as public, the interface can be used anywhere even outside the package. Name is the name of the interface, and can be any valid identifier.
Interfaces are often declared public, because it makes them accessible to the widest range of code.  When an interface is declared public, it must be in a file having the same name of the interface.  In an interface, all the methods are abstract and public.  The method signature includes a return type, a name and zero or more number of parameters.
Variables can also be declared inside an interface. Variables of an interface are implicitly final and static, meaning they can’t be changed by the implementation class. They must also be initialized with a constant value. All methods and variables are implicitly public if the interface itself is declared as public.

Implementing an Interface

Once defined, one or more classes can implement an interface. And one class can implement any number of interfaces.  The relationship between interfaces and classes that implement them is many to many.  An interface can be implemented in one or more classes.  Similarly, one class can implement the methods of one or more interfaces.
To implement an interface, a class must provide the body (implementation) for all the methods defined in the interface.  When an interface is implemented by more than one class, each class is free to determine the details of its own implementation.
The following are the steps to follow to implement an interface in a class:
  1. Define a class that implements the interface using the keyword implements (not using extends keyword)
  2. With in the body of the class that implements, provide the code that implements the methods defined in the interface.
 The general form of a class that implements an interface is as follows:
class classname [extends superclass] implements interface
{
// body of the class
}
To implement more than one interface, the interface names are separated by comma in the list of interface names provided after the keyword implements.  Using the extends keyword allows the class being defined to extend the functionality of the superclass for implementing the interface.

Interface References

Since an interface is a type definition, it can be used to declare a reference variable of type interface.  This reference variable can be used to refer to an object that implements the interface.  When we call a method of an object through the inerface reference, it refers to the version of the method implemented by the object.  This process of accessing an object through interface reference is similar to using a super class reference to access a sub class object.  
Here  program is the algorithm and program in Java for implementing two interfaces in a single class:


Algorithm:
  1. Define two Interfaces named Square and Rectangle with method a single method computeArea(), which is overloaded with their various parameters.
  2. Implement both interfaces in a class named Area by providing code for computeArea() of both interfaces.
  3. 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.
  4. In method main(), declare the variables s, l and w of type float. Also create input object - din of type DataInputStream
  5. Declare a variable (objA) of type Area and create an object for it.
  6. 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.
  7. Get the value of and w from the user and call the method computeArea() of objA with and w as parameters to compute the area of rectangle.
  8. Display the result – area of square and area of rectangle
Program in Java:
Area.java
interface Square
{
int sides = 3;
float computeArea(float side);
}


interface Rectangle
{
int sides = 4;
float computeArea(float length, float width);
}

public class Area implements Square, Rectangle
{
public float computeArea(float s)
{
return (s * s);
}
public float computeArea(float l, float w)
{
return (l * w);
}
}

MulInterface.java
import java.io.*;
public class MulInterface {


/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
float s, l, w;
DataInputStream din = new DataInputStream(System.in);
Area objA = new Area();
System.out.println("Enter the value of s (Side of a Square) : ");
s = Float.parseFloat(din.readLine());
System.out.println("The Area of the Square is : " + objA.computeArea(s));
System.out.println("Enter the value of l (Length of a Rectangle) : ");
l = Float.parseFloat(din.readLine());
System.out.println("Enter the value of w (Width of a Rectangle) : ");
w = Float.parseFloat(din.readLine());
System.out.println("The Area of the Rectangle is : " + objA.computeArea(l,w));
}
}

Sample Run:
Continue reading →
Wednesday, 21 December 2022

Accessing Parent Class from a Sub Class in Inheritance

0 comments

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
The method equals() compares two objects and returns true if the objects are equivalent, and false otherwise.  It simply checks if the invoking reference refers to the same object as the one passed as an argument.  However, equals() is frequently overridden to determine if two objects are equal in their contents.

The method - getClass() is declared as a final one and hence it can't be ovreridden.  The method - toString() returns a string that contains a description of the object on which it is called.  This method is called automatically when an object is output using println().


   





Continue reading →
Friday, 5 November 2021

Introduction to Abstract Window ToolKit (AWT) & Swing

0 comments

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.

Fig. Hierarchy of AWT and Swing Classes

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.

Continue reading →
Tuesday, 30 December 2014

Defining and Implementing Multiple Interfaces in Java

0 comments
IMPLEMENTING MULTIPLE INHERITANCE IN A CLASS

AIM: To write a program in Java to implement two interfaces in a single class.


PROCEDURE:
  1. Define two Interfaces named Square and Rectangle with method a single method computeArea(), which is overloaded with their various parameters.
  2. Implement both interfaces in a class named Area by providing code for computeArea() of both interfaces.
  3. 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.
  4. In method main(), declare the variables s, l and w of type float. Also create input object - din of type DataInputStream
  5. Declare a variable (objA) of type Area and create an object for it.
  6. 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.
  7. 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.
  8. Display the result – area of square and area of rectangle


PROGRAM:
Area.java
interface Square
{
int sides = 3;
float computeArea(float side);
}


interface Rectangle
{
int sides = 4;
float computeArea(float length, float width);
}




public class Area implements Square, Rectangle
{
public float computeArea(float s)
{
return (s * s);
}
public float computeArea(float l, float w)
{
return (l * w);
}
}


MulInterface.java
import java.io.*;
public class MulInterface {


/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
float s, l, w;
DataInputStream din = new DataInputStream(System.in);
Area objA = new Area();
System.out.println("Enter the value of s (Side of a Square) : ");
s = Float.parseFloat(din.readLine());
System.out.println("The Area of the Square is : " + objA.computeArea(s));
System.out.println("Enter the value of l (Length of a Rectangle) : ");
l = Float.parseFloat(din.readLine());
System.out.println("Enter the value of w (Width of a Rectangle) : ");
w = Float.parseFloat(din.readLine());
System.out.println("The Area of the Rectangle is : " + objA.computeArea(l,w));
}
}


Sample Run:

Continue reading →

Creating and Using Student Object for Managing Student Details

0 comments
CREATING AND USING STUDENT OBJECT
 
AIM: To write a program in Java to create and use objects of type Student to store the details like Register Number, Name and Marks in Three Subjects and to find the Total of Marks for 5 different students.

ALGORITHM:
  1. 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.
  2. Define methods setRegNo() and getRegNo() for storing and retrieving data from RegNo
  3. Define methods setName() and getName() for storing and retrieving data from Name
  4. Define methods setMarks() and getMarks() for storing and retrieving data from Marks array
  5. Declare 5 objects namely stud1, stud2, stud3, stud4 and stud5 of type Student in method main()
  6. Call the set methods and get methods for each and every object for storing and retrieving data from all five objects


PROGRAM:
Student.java
import java.io.*;
public class Student {
public DataInputStream din;
public int RegNo, Total;
public String Name;
public int Marks[] = new int[3];
Student()
{
din = new DataInputStream(System.in);
Total = 0;
}
public void setRegNo() throws IOException
{
System.out.println("Enter the Register Number : ");
RegNo = Integer.parseInt(din.readLine());
}
public void getRegNo()
{
System.out.println("Register Number : " + RegNo);
}
public void setName() throws IOException
{
System.out.println("Enter the Name : ");
Name = din.readLine();
}
public void getName()
{
System.out.println("Name : " + Name);
}
public void setMarks() throws IOException
{
System.out.println("Enter the Three Marks (one by one) : ");
for(int i=0; i<3; i++)
{
Marks[i] = Integer.parseInt(din.readLine());
Total = Total + Marks[i];
}
}
public void getMarks()
{
System.out.println("Marks : " + Marks[0] + " " + Marks[1] + " "+ Marks[2]);
System.out.println("Total Marks : " + Total);
}
}
StudentObj.java
import java.io.IOException;


public class StudentObj
{
public static void main(String[] args) throws IOException
{
Student stud1, stud2, stud3, stud4, stud5;
stud1 = new Student();
System.out.print("\n");
System.out.println("Enter the Details of 1st Student : ");
stud1.setRegNo();
stud1.setName();
stud1.setMarks();
stud2 = new Student();
System.out.print("\n");
System.out.println("Enter the Details of 2nd Student : ");
stud2.setRegNo();
stud2.setName();
stud2.setMarks();
stud3 = new Student();
System.out.print("\n");
System.out.println("Enter the Details of 3rd Student : ");
stud3.setRegNo();
stud3.setName();
stud3.setMarks();
stud4 = new Student();
System.out.print("\n");
System.out.println("Enter the Details of 4th Student : ");
stud4.setRegNo();
stud4.setName();
stud4.setMarks();
stud5 = new Student();
System.out.print("\n");
System.out.println("Enter the Details of 5th Student : ");
stud5.setRegNo();
stud5.setName();
stud5.setMarks();
System.out.print("\n");
System.out.println("Details of Student-1");
stud1.getRegNo();
stud1.getName();
stud1.getMarks();
System.out.print("\n");
System.out.println("Details of Student-2");
stud2.getRegNo();
stud2.getName();
stud2.getMarks();
System.out.print("\n");
System.out.println("Details of Student-3");
stud3.getRegNo();
stud3.getName();
stud3.getMarks();
System.out.print("\n");
System.out.println("Details of Student-4");
stud4.getRegNo();
stud4.getName();
stud4.getMarks();
System.out.print("\n");
System.out.println("Details of Student-5");
stud5.getRegNo();
stud5.getName();
stud5.getMarks();
}
}




Sample Run:
Enter the Details of 1st Student :
Enter the Register Number :
13508309
Enter the Name :
Anitha M
Enter the Three Marks (one by one) :
60
59
53


Enter the Details of 2nd Student :
Enter the Register Number :
13508311
Enter the Name :
Banu Priya M
Enter the Three Marks (one by one) :
47
52
51


Enter the Details of 3rd Student :
Enter the Register Number :
13508313
Enter the Name :
Dhivya R
Enter the Three Marks (one by one) :
53
56
70


Enter the Details of 4th Student :
Enter the Register Number :
13508321
Enter the Name :
Haripriya T
Enter the Three Marks (one by one) :
56
59
33


Enter the Details of 5th Student :
Enter the Register Number :
13508323
Enter the Name :
Iswariya Lakshmi M
Enter the Three Marks (one by one) :
84
72
67


Details of Student-1
Register Number : 13508309
Name : Anitha M
Marks : 60 59 53
Total Marks : 172


Details of Student-2
Register Number : 13508311
Name : Banu Priya M
Marks : 47 52 51
Total Marks : 150


Details of Student-3
Register Number : 13508313
Name : Dhivya R
Marks : 53 56 70
Total Marks : 179


Details of Student-4
Register Number : 13508321
Name : Haripriya T
Marks : 56 59 33
Total Marks : 148


Details of Student-5
Register Number : 13508323
Name : Iswariya Lakshmi M
Marks : 84 72 67
Total Marks : 223
BUILD SUCCESSFUL (total time: 2 minutes 54 seconds)
Continue reading →