java array program to identify sub arrays with element sum equal to Zero

Core Java Array interview questions on the identification of multiple sub arrays within in the Array Input whose array elements sum is Zero.

Program Logic:

– Java Array provided with the list of array elements.
* Traverse the elements to identify if the value of that element is zero.
* Traverse the elements to identify if the value of multiple array elements sums up to Zero
* Print each such occurrence as an sub-array

```package core.java.oracleappshelp.array;
public class identifySubArrayInArrayWithSumZero {
// Function to print all sub-arrays with 0 sum present
// in the given array
public static void identifySubArrayToDisplay(int[] ArrayWithAllElements)
{
// Traverse for the sub- array through the outerLoop
for (int outerLoop = 0; outerLoop < ArrayWithAllElements.length; outerLoop++)
{
int sum = 0;
// Traverse for the sub- array through the innerLoop
for (int innerLoop = outerLoop; innerLoop < ArrayWithAllElements.length; innerLoop++)
{
// adding value for innerLoop and outerLoop to get total sum value.
sum += ArrayWithAllElements[innerLoop];
// validate if the array index for innerLoop and OuterLoop sums up to 0
if (sum == 0) {
System.out.println("Subarray [" + outerLoop + ".." + innerLoop + "]");
}
}
}
}
public static void main (String[] args)
{
int[] A = { -2, 2, 1, 5, -6,  3, 1, -4,  };
identifySubArrayToDisplay(A);
}
}
```

java array program to sort list in binary of 0s and 1s

The  below java program executes the java method – sortArrayElementsInBinaryFormat( ) to sort the received list into the Binary format of 0s and 1s in sequence.

Program Logic:

1. Pass the Array Element List to the method – sortArrayElementsInBinaryFormat( )

2. Traverse and identify the elements with 0 value

3. Move the elements with 0 value forward and elements with value 1 thereafter

4. Print the sorted binary array

Array Input :  { 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 }

Array Output: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

```/*
* Java Array Program to sort the received Array Binary Input of 0 and 1
* identify the elements with 0 value
* Move the elements with 0 value forward in the Array
* elements with 1 value to be placed after all 0s
* Input : { 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 }
* Output: {0,0,0,0,0,1,1,1,1,1,1}
*/
package core.java.oracleappshelp.array;
import java.util.Arrays;
public class GenerateBinaryArray {
/*  Method - sortArrayElementsInBinaryFormat
*  Java Method to sort the received list into the Binary format of 0 and 1 in sequence.
*/
public static void sortArrayElementsInBinaryFormat(int[] arrayElements)
{
// identify the elements with 0 value
int elementWithZeroValue = 0;
for (int elementValue : arrayElements) {
if (elementValue == 0) {
elementWithZeroValue++;
}
}
// move the elements with 0 value forward and elements with value 1 thereafter
int elementLoop = 0;
while (elementWithZeroValue-- != 0) {
arrayElements[elementLoop++] = 0;
}
// fill all remaining elements by 1
while (elementLoop < arrayElements.length) {
arrayElements[elementLoop++] = 1;
}
}
// Sort binary array in linear time
public static void main (String[] args)
{
int[] arrayElementList = { 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 };
sortArrayElementsInBinaryFormat(arrayElementList);
// print the sorted binary array
System.out.println(Arrays.toString(arrayElementList));
}
}
Java Array Program Output:
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]```

Main differences between Array and ArrayList in java

How is an array different from ArrayList ? What are the major differences between Array and ArrayList ? Why difference between Array and ArrayList is the most commonly asked Java Interview Question . Below given are the points for Array vs ArrayList which describes it.

 S. No Array ArrayList 1 Array is fixed length , thus static in nature ArrayList  is dynamic in nature 2 Array does not extend any class or implement interface ArrayList implements the List Interface and internally backed by Array 3 Array does not support Generics and throws ArrayStoreException ArrayList supports Generics and ensures type-safety. 4 Array provides length() method to calculate the Array Length Example: int studentObject[] = new Integer[3];int int studentObjectLength= studentObject.length ; ArrayList provides size() method to calculate the ArrayList size Example:ArrayList studentObject = new ArrayList();studentObject.add(101);studentObject.add(102);studentObject.size(); 5 Arrays allows to store primitive types and objects ArrayList allows to store objects only 6 Array uses assignment operator to store element into array Example: int[] studentId = { 101, 102,103,104,105 }; Object[] studentId = new Object[10]; ArrayList uses add() method to store element in ArrayList Example: ArrayList studentIdList = new ArrayList();studentIdList.add(100); 7 Arrays are faster when frequent access is required. Array operations execution time Arrays Lookup –  O(1) Arrays Append ( last element) – O(1) Array Insertion – O(n) Array Deletion – O(n) ArrayList is faster when frequent insert and deletion is required.  Overall ArrayList takes  more time as it uses List interface as part of Collection Framework and each node in the List has its own memory when compared to Arrays. 8 Array is traversed using for loop ArrayList is traversed using Iterator

Java Array program to find array elements with given sum

The java array program receives the list of unsorted array elements and sum value as input to the program. The array elements will be traversed and adds the sum of array elements at respective array index to compare if that equals to the sum value received as an input. If value matches at array index, the program will print the indexes else print “Array Element Pair not found”

Example:

```    int[] ArrayObjList = { 2, 8, 4, 6, 12, 17 };
int ArrayTotal = 20;```

Here , the index 1 and index 4 sum is equal to the given sum.

```package core.java.oracleappshelp.array;
public class ArrayPairSumEqualToArraySum {
private static void findPair(int[] ArrayWithAllElements, int sum) {
{
// Traverse for Array Object till Array length -1
for (int outerLoop = 0; outerLoop < ArrayWithAllElements.length - 1; outerLoop++)
{
// Traverse for the InnerLoop till last element
for (int innerLoop = outerLoop + 1; innerLoop < ArrayWithAllElements.length; innerLoop++)
{
// check if the 2 compared elements sum is equal to the Array Sum
if (ArrayWithAllElements[outerLoop] + ArrayWithAllElements[innerLoop] == sum)
{
System.out.println("Element Pair found at index " + innerLoop + " and " + outerLoop);
return;
}
}
}
// When no array element is qualified
}
}
public static void main (String[] args){
int[] ArrayObjList = { 2, 8, 4, 6, 12, 17 };
int ArrayTotal = 20;
findPair(ArrayObjList, ArrayTotal);
}
}
Array Program Output:
Element Pair found at index 4 and 1    ```

enum java type

Enum is provided as a new data type to provide the predefined values (constants) for a variable. The Enum data type is defined in java using the enum keyword. The enum data type fields are in uppercase letters being constant values.

The enum data types can be helpful in supporting the different values for a particular attribute . For instance , an application goes through the life cycle and maintains differnet values for each user action which results into the change of the status for the application. So, we can have the enum data type for the application status as given below:

public enum Status {

INPROGRESS,UPDATED,PENDING_FOR_APPROVAL,APPROVED,ERROR,RE_PROCESSED

}

difference between enum data type and constants in java

1, The enum data type is type Safe and provides limited set of values

2. The enum data type proivdes the listing of all constants in the predefined enum data type whereas constans store single values and thus requires as many of constants as the values to be maintained

public enum Status {

INPROGRESS,UPDATED //enum data type values

}

public static final String INPROGRESS = “INPROGRESS”; //constant value
public static final String UPDATED = “UPDATED”; //constant value

java enum data type example

The below java program provides the usage of enum ApplicationStatus to get the different statuses from the enum data type.

```package core.java.oracleappshelp.basics;
public class StatusEnumExample {
public enum ApplicationStatus{
INPROGRESS,UPDATED,PENDING_FOR_APPROVAL,APPROVED,ERROR,RE_PROCESSED
}
public void ValidateStatus(String ApplicationStatus) {
switch (ApplicationStatus) {
case "INPROGRESS":
System.out.println("Application Status is changed to INPROGRESS.");
break;

case "UPDATED":
System.out.println("Application Status is changed to UPDATED.");
break;

case "PENDING_FOR_APPROVAL":
System.out.println("Application Status is changed to PENDING_FOR_APPROVAL.");
break;
case "APPROVED":
System.out.println("Application Status is changed to APPROVED.");
break;

case "ERROR":
System.out.println("Application Status is changed to ERROR.");
break;

case "RE_PROCESSED":
System.out.println("Application Status is changed to RE_PROCESSED.");
break;

default:
System.out.println("Application Status value cannot be evaluated.....");
break;
}
}

public static void main(String[] args) {
StatusEnumExample status = new StatusEnumExample();
status.ValidateStatus("INPROGRESS");
status.ValidateStatus("UPDATED");
status.ValidateStatus("PENDING_FOR_APPROVAL");
status.ValidateStatus("APPROVED");
status.ValidateStatus("ERROR");
status.ValidateStatus("RE_PROCESSED");

}
}```

java enum data type program output:

Application Status is changed to INPROGRESS.
Application Status is changed to UPDATED.
Application Status is changed to PENDING_FOR_APPROVAL.
Application Status is changed to APPROVED.
Application Status is changed to ERROR.
Application Status is changed to RE_PROCESSED.

```package core.java.oracleappshelp.basics;
public class StatusEnumExample {
public enum ApplicationStatus{
INPROGRESS,UPDATED,PENDING_FOR_APPROVAL,APPROVED,ERROR,RE_PROCESSED
}
public static void main(String[] args) {
StatusEnumExample status = new StatusEnumExample();
//printing all the values of application status enum
ApplicationStatus  statusEnum[] = ApplicationStatus.values();
System.out.println("Value of application status enum : ");
for(ApplicationStatus statusValue: statusEnum) {
System.out.println(statusValue);
}

}
}```

Java program output:

Value of application status enum :
INPROGRESS
UPDATED
PENDING_FOR_APPROVAL
APPROVED
ERROR
RE_PROCESSED

Java Enumeration Interface

The java.util package provides the Enumeration class which implements the Enum Interface. The below given is the example for the Vector using Enumeration usage.

```package core.java.oracleappshelp.basics;
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationExample {
public static void main(String args[]) {
//instantiating a Vector
Vector<String> vec = new Vector<String>( );
//Populating the vector
//Retrieving the elements using the Enumeration
Enumeration<String> status = vec.elements();
while(status.hasMoreElements()) {
System.out.println(status.nextElement());
}
}
}
```

Java enumeration program implementation using vector:

INPROGRESS
UPDATED
PENDING_FOR_APPROVAL
APPROVED
ERROR
RE_PROCESSED

Interface class in java

The Tutorial discuss about the interface class in Java. The interface class in java is one of the core concept of the java programming language and supports the object oriented approach. The java collections, java design patterns, java List uses the implementation of interface classes. The Java Abstract Class provides the partial abstraction mechanism whereas Interface class implements the complete abstraction mechanism.

What is interface class in java ?

The java interface class is declared using the keyword ‘interface’. The java Interface class provides the complete abstraction by providing all the abstract methods for the implementation. With the addition of new features in Java 8 , interface class also provides static methods ( defined with static modifier) and default methods( defined with default modifier) now. Interface class also provides the declaration of constants. Constant values can be defined as public , static and final.

The Java interface class can extends interface or multiple interfaces but cannot extend the class which also concludes that the Java interface class cannot be instantiated but used by other class(es) for the abstract method implementation.

Java Interface Class Signature

The interface class signature includes:

• The keyword interface,
• name for the interface class ,
• parent interfaces (if any) and
• the interface body ( contains abstract methods, default methods, static methods)

Points to consider while using Java Interface class

• The java interface class is declared using the keyword ‘interface’
• The java interface class can extends interface or multiple interfaces but cannot extend the class
• Java interface class cannot be instantiated
• Java interface class provides complete abstractions as all abstract methods are without body.
• Java interface class does not support constructors
• The sub class requires implements keyword to implement the interface
• The attribute of the interface is public , static and final by default
• The abstract methods are by default implicitly abstract and public.

Java interface class example

Lets create an java interface class VehicleInterface.java with abstract methods and then Toyota.java implements the interface.

```package core.java.oracleappshelp.basics;
public interface  VehicleInterface {

//create the interface method
public abstract void getEnginePower(int enginePower);

//create the interface  method
public abstract void getVehicleModel(String model);
}```
```package core.java.oracleappshelp.basics;
public class Toyota implements VehicleInterface{
private int engineCC;
private String model;

public Toyota() {
System.out.println( "This is the implementation class for VehicleInterface");
}
@Override
public void getEnginePower(int enginePower) {
// TODO Auto-generated method stub
this.engineCC =enginePower;
System.out.println( "Toyota Engine Power is="+this.engineCC + "\n");

}
@Override
public void getVehicleModel(String model) {
// TODO Auto-generated method stub
this.model =model;
System.out.println( "Toyota Model is ="+ this.model);

}

public static void main(String args[]){
Toyota vehicle = new Toyota();
vehicle.getVehicleModel("Camry ZX");
vehicle.getEnginePower(1200);
}

}```

Java interface program output:

This is the implementation class for VehicleInterface
Toyota Model is =Camry ZX
Toyota Engine Power is=1200

Core Java Tutorial on Abstract class

The tutorial provides the detailing about the creation and usage of abstract class in java. The java abstract class is declared using the keyword’ abstract’ . The abstract class could have methods with or without implementation. The abstract classes cannot be initiated as they could have unimplemented methods but these abstract classes can be sub-classed.

abstract class usage in java

The below given is the abstract method which is declared but not implemented

abstract void model(String carModel);

abstract void engineCapacity(int cc);

The class using the abstract methods should also be declared as abstract class

public abstract class Car {

// declare class variables

//declare non-abstract methods (which includes implementation)

abstract void model(String carModel);

abstract void engineCapacity(int cc);

}

Points to Consider for creating java abstract class

• Java abstract class are required to be declared with “abstract” keyword
• Java abstract class cannot be initiated
• Java abstract class contains abstract method with or without body.
• Java abstract does not always require to have abstract methods even though it is being defined as an abstract class
• The sub class of the java abstract class must implement all abstract methods.
• Interfaces methods are implicitly abstract unless they are static or default. (https://docs.oracle.com/javase/tutorial/java/IandI/interfaceDef.html )

How java abstract class is different from interface class ?

The java abstract class is similar to Interface except the difference that the class which implements the interface must implement all of the interface methods whereas if we need the class which does not require to implement all the methods then the class with methods should be declared as ‘abstract’.

Java abstract class example

Lets consider the example of Vehicles where vehicles could be of different model and having different engine power. so the below abstract class Vehicle is created where the engine

```package core.java.oracleappshelp.basics;
//abstract class example
public abstract class Vehicle {

private String vehicleName;
//private String vehicleModel;

public Vehicle(String name){
this.vehicleName=name;
//this.vehicleModel=model;
}

//create the abstract method
public abstract void getEnginePower(int enginePower);

//create the abstract method
public abstract void getVehicleModel(String model);

@Override
public String toString(){
return "Vehicle Name="+this.vehicleName;
}
}
```
```package core.java.oracleappshelp.basics;
public class VehicleEngine extends Vehicle {

private int engineCC;
private String name;
private String model;

public VehicleEngine(String name) {
super(name);
this.name = name;

}
@Override
public void getEnginePower(int enginePower) {
if(enginePower == 0){
System.out.println("The Engine CC details are not provided");
}else{
this.engineCC =enginePower;
System.out.println( "Vehicle Engine Power is="+this.engineCC + "\n");
}
}

@Override
public void getVehicleModel(String model) {
if(model == null){
System.out.println("The Engine model  details are not provided");
}else{
this.model =model;
System.out.println( "Vehicle Name="+ this.name);
System.out.println( "Vehicle Model="+this.model );
}
}

public static void main(String args[]){
Vehicle vehicle = new VehicleEngine("Maruti");
vehicle.getVehicleModel("Maruti Suzuki ZX");
vehicle.getEnginePower(900);

Vehicle vehicle2 = new VehicleEngine("Toyota");
vehicle2.getVehicleModel("Camry");
vehicle2.getEnginePower(1200);

}
}
```
```Vehicle Name=Maruti
Vehicle Model=Maruti Suzuki ZX
Vehicle Engine Power is=900
Vehicle Name=Toyota
Vehicle Model=Camry
Vehicle Engine Power is=1200```

Core Java – Java Class and Objects

Java is an object oriented programming language and its is driven based on Java Classes and Object instantiation. The tutorial provides how to create Java Classes and instantiate object on the class.

What is Object in Java ?

An Object is a group of related items grouped together and can have characteristics like state and behavior.

Lets consider Room as an Object , then Blackboard, Table, chair, Chalk are considered as its State (attributes /fields) and totalChairs and TotalTables are considered as behaviour (methods) which defines the Room as an Object.

Similarly a furniture being an object could have attributes like table, chair, dine table, stool, sofa,etc.

Example -1

• Object – Room
• State – Blackboard, Table, chair, Chalk
• Behavior – Seat Capacity, TotalChairs, TotalTables

Exmaple -2

• Object -SwtichBoard
• State – On or Off
• Behavior – TurnOff / TurnOn

What is class in Java ?

Class in java acts as the Object constructor or we can say that its the blueprint which defines the attributes for the created object.

The Class contains the variables (State) and methods . The below given is the class with name Furniture and has variables

```/**
*  Oracleappshelp.com - Java Basics Tutorial
*  Program - Class Creation and Object Instantiation Example
*   */
package core.java.oracleappshelp.basics;
public class Furniture {
String strTable;
String strChair;
String strSofa ="Recliner";
String strDineTable;
public static void main(String[] args) {
// Object Creation for the Class Furniture
Furniture furnitureObj = new Furniture();
// Basic Output
System.out.println("This is basic furntiure class..");

// Object instantiation and execution
System.out.println("The Sofa Type is :" +  furnitureObj.strSofa);
}
}
Output:
This is basic furntiure class..
The Sofa Type is :Recliner```

Now consider the modified class which has varibles with setter and getter methods and a Method invocation

```/**
*  Oracleappshelp.com - Java Basics Tutorial
*  Program - Class Creation and Object Instantiation Example
*   */
package core.java.oracleappshelp.basics;
public class Furniture {

String strTable;
String strChair;
String strSofa ="Recliner";
String strDineTable;
public static void main(String[] args) {
// Object Creation for the Class Furniture
Furniture furnitureObj = new Furniture();
// Basic Output
System.out.println("This is basic furntiure class..");

// Object instantiation and execution
System.out.println("The Sofa Type is :" +  furnitureObj.strSofa);
furnitureObj.setSofaType();
}

public void setSofaType()
{
this.setStrSofa("3 seater sofa");
System.out.println("The Sofa Type is :" +  this.getStrSofa());
}

public String getStrTable() {
return strTable;
}
public void setStrTable(String strTable) {
this.strTable = strTable;
}
public String getStrChair() {
return strChair;
}
public void setStrChair(String strChair) {
this.strChair = strChair;
}
public String getStrSofa() {
return strSofa;
}
public void setStrSofa(String strSofa) {
this.strSofa = strSofa;
}
public String getStrDineTable() {
return strDineTable;
}
public void setStrDineTable(String strDineTable) {
this.strDineTable = strDineTable;
}
}
Output:
This is basic furntiure class..
The Sofa Type is :Recliner
The Sofa Type is :3 seater sofa```