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<Integer> studentIdList = new ArrayList<Integer>();
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 
			System.out.println("Array Element Pair not found");
		}
		}
		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
	      vec.add("INPROGRESS");
	      vec.add("UPDATED");
	      vec.add("PENDING_FOR_APPROVAL");
	      vec.add("APPROVED");
	      vec.add("ERROR");
	      vec.add("RE_PROCESSED");
	      //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


Java OOP Principle – Single Responsibility Principle

Single Responsibility Principle is one of the SOLID principles of object-oriented programming.  There are five (5) design principles defined for developing Java application to make it more flexible, scalable and easy to maintain.

SOLID is an acronym for the below given 5 design principles.

  • Single Responsibility Principle
  • Open –Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

The blog covers the 1st design principle – Single Responsibility Principle.

Robert C. Martin first published the theory of SOLID Principles 2000 paper Design Principles and Design Patterns.

The Design Principle – Single Responsibility depicts that every class should have the single responsibility to perform and ensure that the dependency should not be injected which makes the class changed again and again.

As per Robert C. Martin, he described as

“A class should have only one reason to change”

With the Current Business needs, there are many possible reasons that the implemented classes might get into change if they are not loosely coupled and have multiple dependent features within the same class. With such classes, the change in the requirement, requires the change in the already implemented classes. This happens so as each class is trying to perform more than a specific set of responsibilities and also contradicts the 1st OOP Principle of Single Responsibility.

Challenges with the above approach

Multiple changes in the existing class

  1. Multiple responsibilities injected in the same class makes it difficult to maintain
  2. Classes cannot be loosely coupled and thus does not provide flexibility.
  3. Recompilation of dependent classes
  4. Increased Testing to ensure included changes does not break the existing functionality.
  5. Written code cannot be re-used

Advantages of using Single Responsibility Principle

  1. Performs a specific responsibility
  2. Classes are loosely coupled
  3. Written Code can be re-used
  4. Does not require validation and re-compilation of dependent classes
  5. Helps in developing more robust and scalable applications
  6. Reduces coding issues and significantly reduces overall development time.
  7. Reduces testing cycle as specific set of changes need to be tested.
  8. Easy maintainability

Consider the MVC Framework, which segregates the Model, View and Controller and implements several classes internally which provide specific execution.

Similarly, the usage of Micro Services can have multiple API but each API will have separate resources for executing a specific set of responsibility. Example – The Customer API could have multiple resources as like createCustomer, updateCustomer, deleteCustomer, getCustomer, getCustomerList and so on.  Each resource segregates and performs specific operation.


Difference between String, StringBuilder and StringBuffer in Java commonly asked question in interview

String is one of the most commonly used class in java used by a developer. String can be used for multiple purposes for run time values, string manipulations , etc. But many developers ignore the fact that Strings are IMMUTABLE. That is whenever a value for string is modified a new internal memory is allocated for storing the string value and thus the previous value remains unchanged.

Being IMMUTABLE and final in nature it makes its hash code value to be cached and thus used in hash map for faster hash map key reference and also becomes useful in multiple thread execution being a thread safe value.

Accessive use of string operations in your code like upper case, lower case, concatenation, sub string leads to performance issue. So to manipulate the strings without creating STRING GARBAGE can be done with either StringBuffer or with StringBuilder.

Now, next question comes here whether we want the data to be thread safe or not ?

StringBuffer and StringBuilder both are mutuable and thus operation done on the StringBuffer or StringBuilder object does not create any new object. The main difference is that StringBuffer has all its public methods are SYNCHRONIZED which makes it thread safe but also makes it slow in execution. On the Other hand, StringBuilder is not synchronized and has same methods as StringBuffer has.

So we can summarize the following
1) String is immutable while StringBuffer and StringBuilder is mutable object.
2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
3) Concatenation operator “+” used in String is internally implemented using either StringBuffer or StringBuilder.

Developer should use String if require immutable objects
Developer should use of StringBuffer if require object to be mutable and thread safe
Developer should use StringBuilder if require mutable and no thread safe.