The Arrays class in java.util package is a part of the Java Collection Framework. This class provides static methods to dynamically create ...
Skiptocontent
CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests
ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew?
ChangeLanguage
DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects
RelatedArticles
▲RelatedArticlesArraysclassinJavaArraysinJavaReturningMultiplevaluesinJavaHowtoaddanelementtoanArrayinJava?HowtodeterminelengthorsizeofanArrayinJava?lengthvslength()inJavaSplit()StringmethodinJavawithexamplesJavaStringtrim()methodwithExampleTrim(Removeleadingandtrailingspaces)astringinJavaJavaProgramtoCounttheNumberofLines,Words,Characters,andParagraphsinaTextFileCheckifaStringContainsOnlyAlphabetsinJavaUsingLambdaExpressionRemoveelementsfromaListthatsatisfygivenpredicateinJavaCheckifaStringContainsOnlyAlphabetsinJavausingASCIIValuesCheckifaStringContainsonlyAlphabetsinJavausingRegexHowtocheckifstringcontainsonlydigitsinJavaCheckifgivenstringcontainsallthedigitsGivenastring,finditsfirstnon-repeatingcharacterFirstnon-repeatingcharacterusingonetraversalofstring|Set2MissingcharacterstomakeastringPangramCheckifastringisPangrammaticLipogramRemovingpunctuationsfromagivenstringRearrangecharactersinaStringsuchthatnotwoadjacentcharactersaresameProgramtocheckifinputisanintegerorastringQuickwaytocheckifallthecharactersofastringaresameProgramtofindtheinitialsofaname.Arrays.sort()inJavawithexamplesFor-eachloopinJavaReverseastringinJavaArraysclassinJavaArraysinJavaReturningMultiplevaluesinJavaHowtoaddanelementtoanArrayinJava?HowtodeterminelengthorsizeofanArrayinJava?lengthvslength()inJavaSplit()StringmethodinJavawithexamplesJavaStringtrim()methodwithExampleTrim(Removeleadingandtrailingspaces)astringinJavaJavaProgramtoCounttheNumberofLines,Words,Characters,andParagraphsinaTextFileCheckifaStringContainsOnlyAlphabetsinJavaUsingLambdaExpressionRemoveelementsfromaListthatsatisfygivenpredicateinJavaCheckifaStringContainsOnlyAlphabetsinJavausingASCIIValuesCheckifaStringContainsonlyAlphabetsinJavausingRegexHowtocheckifstringcontainsonlydigitsinJavaCheckifgivenstringcontainsallthedigitsGivenastring,finditsfirstnon-repeatingcharacterFirstnon-repeatingcharacterusingonetraversalofstring|Set2MissingcharacterstomakeastringPangramCheckifastringisPangrammaticLipogramRemovingpunctuationsfromagivenstringRearrangecharactersinaStringsuchthatnotwoadjacentcharactersaresameProgramtocheckifinputisanintegerorastringQuickwaytocheckifallthecharactersofastringaresameProgramtofindtheinitialsofaname.Arrays.sort()inJavawithexamplesFor-eachloopinJavaReverseastringinJavaArraysclassinJavaViewDiscussion
ImproveArticle
SaveArticle
LikeArticle
DifficultyLevel:
EasyLastUpdated:
07Jul,2022ReadDiscussViewDiscussion
ImproveArticle
SaveArticle
LikeArticle
TheArraysclassinjava.utilpackageisapartoftheJavaCollectionFramework.ThisclassprovidesstaticmethodstodynamicallycreateandaccessJavaarrays.ItconsistsofonlystaticmethodsandthemethodsofObjectclass.Themethodsofthisclasscanbeusedbytheclassnameitself.Theclasshierarchyisasfollows: java.lang.Object
↳java.util.ArraysGeek,nowyoumustbewonderingwhydoweneedjavaArraysclasswhenweareabletodeclare,initializeandcomputeoperationsoverarrays.Theanswertothisthoughlieswithinthemethodsofthisclasswhichwearegoingtodiscussfurtheraspracticallythesefunctionshelpprogrammersexpandinghorizonswitharraysforinstancethereareoftentimeswhenloopsareusedtodosometasksonanarraylike: Fillanarraywithaparticularvalue.SortanArrays.SearchinanArrays.Andmanymore.HereArraysclassprovidesseveralstaticmethodsthatcanbeusedtoperformthesetasksdirectlywithouttheuseofloops,henceforthmakingourcodesupershortandoptimized.Syntax:Classdeclaration publicclassArrays
extendsObjectSyntax:InordertouseArrays Arrays.;MethodsinJavaArrayClass TheArraysclassofthejava.utilpackagecontainsseveralstaticmethodsthatcanbeusedtofill,sort,search,etcinarrays.Nowletusdiscussthemethodsofthisclasswhichareshownbelowinatabularformatasfollows:Methods ActionPerformedasList()Returnsafixed-sizelistbackedbythespecifiedArraysbinarySearch()SearchesforthespecifiedelementinthearraywiththehelpoftheBinarySearchAlgorithmbinarySearch(array,fromIndex,toIndex,key,Comparator)SearchesarangeofthespecifiedarrayforthespecifiedobjectusingtheBinarySearchAlgorithmcompare(array1,array2)Comparestwoarrayspassedasparameterslexicographically.copyOf(originalArray,newLength)Copiesthespecifiedarray,truncatingorpaddingwiththedefaultvalue(ifnecessary)sothecopyhasthespecifiedlength.copyOfRange(originalArray,fromIndex,endIndex)CopiesthespecifiedrangeofthespecifiedarrayintoanewArrays.deepEquals(Object[]a1,Object[]a2)Returnstrueifthetwospecifiedarraysaredeeplyequaltooneanother.deepHashCode(Object[]a) Returnsahashcodebasedonthe“deepcontents”ofthespecifiedArrays.deepToString(Object[]a)Returnsastringrepresentationofthe“deepcontents”ofthespecifiedArrays.equals(array1,array2)Checksifboththearraysareequalornot.fill(originalArray,fillValue)Assignsthisfillvaluetoeachindexofthisarrays.hashCode(originalArray) ReturnsanintegerhashCodeofthisarrayinstance.mismatch(array1,array2) Findsandreturnstheindexofthefirstunmatchedelementbetweenthetwospecifiedarrays.parallelPrefix(originalArray,fromIndex,endIndex,functionalOperator)PerformsparallelPrefixforthegivenrangeofthearraywiththespecifiedfunctionaloperator.parallelPrefix(originalArray,operator)PerformsparallelPrefixforcompletearraywiththespecifiedfunctionaloperator. parallelSetAll(originalArray,functionalGenerator)Setsalltheelementsofthisarrayinparallel,usingtheprovidedgeneratorfunction. parallelSort(originalArray)Sortsthespecifiedarrayusingparallelsort.setAll(originalArray,functionalGenerator)Setsalltheelementsofthespecifiedarrayusingthegeneratorfunctionprovided. sort(originalArray)Sortsthecompletearrayinascendingorder. sort(originalArray,fromIndex,endIndex)Sortsthespecifiedrangeofarrayinascendingorder.sort(T[]a,intfromIndex,inttoIndex,Comparatorc)Sortsthespecifiedrangeofthespecifiedarrayofobjectsaccordingtotheorderinducedbythespecifiedcomparator.sort(T[]a,Comparatorc)Sortsthespecifiedarrayofobjectsaccordingtotheorderinducedbythespecifiedcomparator.spliterator(originalArray)ReturnsaSpliteratorcoveringallofthespecifiedArrays.spliterator(originalArray,fromIndex,endIndex) ReturnsaSpliteratorofthetypeofthearraycoveringthespecifiedrangeofthespecifiedarrays.stream(originalArray) Returnsasequentialstreamwiththespecifiedarrayasitssource.toString(originalArray) Itreturnsastringrepresentationofthecontentsofthisarray.Thestringrepresentationconsistsofalistofthearray’selements,enclosedinsquarebrackets(“[]”).Adjacentelementsareseparatedbythecharactersacommafollowedbyaspace.ElementsareconvertedtostringsasbyString.valueOf()function.Implementation:Example1:asList()Method Java//JavaProgramtoDemonstrateArraysClass//ViaasList()method //ImportingArraysutilityclass//fromjava.utilpackage importjava.util.Arrays; //Mainclass classGFG{ //Maindrivermethod publicstaticvoidmain(String[]args) { //GettheArray intintArr[]={10,20,15,22,35}; //ToconverttheelementsasList System.out.println("IntegerArrayasList:" +Arrays.asList(intArr)); }}OutputIntegerArrayasList:[[I@2f4d3709]
Example2:binarySearch()MethodThismethodssearchforthespecifiedelementinthearraywiththehelpofthebinarysearchalgorithm.Java//JavaProgramtoDemonstrateArraysClass//ViabinarySearch()method //ImportingArraysutilityclass//fromjava.utilpackageimportjava.util.Arrays; //MainclasspublicclassGFG{ //Maindrivermethod publicstaticvoidmain(String[]args) { //GettheArray intintArr[]={10,20,15,22,35}; Arrays.sort(intArr); intintKey=22; //Printthekeyandcorrespondingindex System.out.println( intKey+"foundatindex=" +Arrays.binarySearch(intArr,intKey)); }}Output22foundatindex=3
Example3:binarySearch(array,fromIndex,toIndex,key,Comparator)Method Thismethodsearchesarangeofthespecifiedarrayforthespecifiedobjectusingthebinarysearchalgorithm.Java//Javaprogramtodemonstrate//Arrays.binarySearch()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArray intintArr[]={10,20,15,22,35}; Arrays.sort(intArr); intintKey=22; System.out.println( intKey +"foundatindex=" +Arrays .binarySearch(intArr,1,3,intKey)); }}Output22foundatindex=-4
Example4:compare(array1,array2)Method Java//Javaprogramtodemonstrate//Arrays.compare()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArray intintArr[]={10,20,15,22,35}; //GetthesecondArray intintArr1[]={10,15,22}; //Tocomparebotharrays System.out.println("IntegerArraysoncomparison:" +Arrays.compare(intArr,intArr1)); }}OutputIntegerArraysoncomparison:1
Example5:compareUnsigned(array1,array2)Method Java//Javaprogramtodemonstrate//Arrays.compareUnsigned()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArrays intintArr[]={10,20,15,22,35}; //GetthesecondArrays intintArr1[]={10,15,22}; //Tocomparebotharrays System.out.println("IntegerArraysoncomparison:" +Arrays.compareUnsigned(intArr,intArr1)); }}OutputIntegerArraysoncomparison:1
Example6:copyOf(originalArray,newLength)Method Java//Javaprogramtodemonstrate//Arrays.copyOf()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArray intintArr[]={10,20,15,22,35}; //Toprinttheelementsinoneline System.out.println("IntegerArray:" +Arrays.toString(intArr)); System.out.println("\nNewArraysbycopyOf:\n"); System.out.println("IntegerArray:" +Arrays.toString( Arrays.copyOf(intArr,10))); }}OutputIntegerArray:[10,20,15,22,35]
NewArraysbycopyOf:
IntegerArray:[10,20,15,22,35,0,0,0,0,0]
Example7:copyOfRange(originalArray,fromIndex,endIndex)Method Java//Javaprogramtodemonstrate//Arrays.copyOfRange()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArray intintArr[]={10,20,15,22,35}; //Toprinttheelementsinoneline System.out.println("IntegerArray:" +Arrays.toString(intArr)); System.out.println("\nNewArraysbycopyOfRange:\n"); //Tocopythearrayintoanarrayofnewlength System.out.println("IntegerArray:" +Arrays.toString( Arrays.copyOfRange(intArr,1,3))); }}OutputIntegerArray:[10,20,15,22,35]
NewArraysbycopyOfRange:
IntegerArray:[20,15]
Example8:deepEquals(Object[]a1,Object[]a2)Method Java//Javaprogramtodemonstrate//Arrays.deepEquals()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArrays intintArr[][]={{10,20,15,22,35}}; //GetthesecondArrays intintArr1[][]={{10,15,22}}; //Tocomparebotharrays System.out.println("IntegerArraysoncomparison:" +Arrays.deepEquals(intArr,intArr1)); }}OutputIntegerArraysoncomparison:false
Example9:deepHashCode(Object[]a)Method Java//Javaprogramtodemonstrate//Arrays.deepHashCode()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArray intintArr[][]={{10,20,15,22,35}}; //TogetthedephashCodeofthearrays System.out.println("IntegerArray:" +Arrays.deepHashCode(intArr)); }}OutputIntegerArray:38475344
Example10:deepToString(Object[]a)Method Java//Javaprogramtodemonstrate//Arrays.deepToString()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArray intintArr[][]={{10,20,15,22,35}}; //TogetthedeepStringofthearrays System.out.println("IntegerArray:" +Arrays.deepToString(intArr)); }}OutputIntegerArray:[[10,20,15,22,35]]
Example11:equals(array1,array2)Method Java//Javaprogramtodemonstrate//Arrays.equals()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArrays intintArr[]={10,20,15,22,35}; //GetthesecondArrays intintArr1[]={10,15,22}; //Tocomparebotharrays System.out.println("IntegerArraysoncomparison:" +Arrays.equals(intArr,intArr1)); }}OutputIntegerArraysoncomparison:false
Example12:fill(originalArray,fillValue)Method Java//Javaprogramtodemonstrate//Arrays.fill()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArrays intintArr[]={10,20,15,22,35}; intintKey=22; Arrays.fill(intArr,intKey); //Tofillthearrays System.out.println("IntegerArrayonfilling:" +Arrays.toString(intArr)); }}OutputIntegerArrayonfilling:[22,22,22,22,22]
Example13:hashCode(originalArray)Method Java//Javaprogramtodemonstrate//Arrays.hashCode()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArray intintArr[]={10,20,15,22,35}; //TogetthehashCodeofthearrays System.out.println("IntegerArray:" +Arrays.hashCode(intArr)); }}OutputIntegerArray:38475313
Example14:mismatch(array1,array2)Method Java//Javaprogramtodemonstrate//Arrays.mismatch()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArrays intintArr[]={10,20,15,22,35}; //GetthesecondArrays intintArr1[]={10,15,22}; //Tocomparebotharrays System.out.println("Theelementmismatchedatindex:" +Arrays.mismatch(intArr,intArr1)); }}OutputTheelementmismatchedatindex:1
Example15:parallelSort(originalArray)MethodJava//Javaprogramtodemonstrate//Arrays.parallelSort()method //ImportingArraysclassfrom//java.utilpackage importjava.util.Arrays; //MainclasspublicclassMain{ publicstaticvoidmain(String[]args) { //GettheArray intintArr[]={10,20,15,22,35}; //TosortthearrayusingparallelSort Arrays.parallelSort(intArr); System.out.println("IntegerArray:" +Arrays.toString(intArr)); }}OutputIntegerArray:[10,15,20,22,35]
Example16:sort(originalArray)Method Java//Javaprogramtodemonstrate//Arrays.sort()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArray intintArr[]={10,20,15,22,35}; //Tosortthearrayusingnormalsort- Arrays.sort(intArr); System.out.println("IntegerArray:" +Arrays.toString(intArr)); }}OutputIntegerArray:[10,15,20,22,35]
Example17:sort(originalArray,fromIndex,endIndex)Method Java//Javaprogramtodemonstrate//Arrays.sort()method importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //GettheArray intintArr[]={10,20,15,22,35}; //Tosortthearrayusingnormalsort Arrays.sort(intArr,1,3); System.out.println("IntegerArray:" +Arrays.toString(intArr)); }}OutputIntegerArray:[10,15,20,22,35]
Example18:sort(T[]a,intfromIndex,inttoIndex,Comparatorc)Method Java//JavaprogramtodemonstrateworkingofComparator//interfaceimportjava.util.*;importjava.lang.*;importjava.io.*; //Aclasstorepresentastudent.classStudent{ introllno; Stringname,address; //Constructor publicStudent(introllno,Stringname, Stringaddress) { this.rollno=rollno; this.name=name; this.address=address; } //Usedtoprintstudentdetailsinmain() publicStringtoString() { returnthis.rollno+"" +this.name+"" +this.address; }} classSortbyrollimplementsComparator{ //Usedforsortinginascendingorderof //rollnumber publicintcompare(Studenta,Studentb) { returna.rollno-b.rollno; }} //DriverclassclassMain{ publicstaticvoidmain(String[]args) { Student[]arr={newStudent(111,"bbbb","london"), newStudent(131,"aaaa","nyc"), newStudent(121,"cccc","jaipur")}; System.out.println("Unsorted"); for(inti=0;ic)MethodJava//JavaprogramtodemonstrateworkingofComparator//interfaceimportjava.util.*;importjava.lang.*;importjava.io.*; //Aclasstorepresentastudent.classStudent{ introllno; Stringname,address; //Constructor publicStudent(introllno,Stringname, Stringaddress) { this.rollno=rollno; this.name=name; this.address=address; } //Usedtoprintstudentdetailsinmain() publicStringtoString() { returnthis.rollno+"" +this.name+"" +this.address; }} classSortbyrollimplementsComparator{ //Usedforsortinginascendingorderof //rollnumber publicintcompare(Studenta,Studentb) { returna.rollno-b.rollno; }} //DriverclassclassMain{ publicstaticvoidmain(String[]args) { Student[]arr={newStudent(111,"bbbb","london"), newStudent(131,"aaaa","nyc"), newStudent(121,"cccc","jaipur")}; System.out.println("Unsorted"); for(inti=0;i