Showing posts sorted by date for query recursion-in-java-with-example-programming. Sort by relevance Show all posts
Showing posts sorted by date for query recursion-in-java-with-example-programming. Sort by relevance Show all posts

Sunday, March 29, 2020

10 Points Most Static Inward Java

What is static inward Java
Static inward Java is related to class, if a plain is static agency it belongs to class, similarly static method belongs to classes together with you lot tin access both static method together with plain using shape elevate e.g. if count field is static inward Counter class than you lot tin access it every bit Counter.count, of course of written report dependent plain to restriction applied past times access modifier e.g. person fields are alone accessible inward shape on which they are declared, protected fields are accessible to all classes inward same bundle but alone accessible inward sub shape exterior package. See private vs protected vs public for consummate details on access modifier. Similarly if you lot receive got a static method increment() in Counter class which increment counter than you lot tin telephone yell upwardly it every bit Counter.increment(). There is no demand to do an object of Counter class to access either static method or static field, this is master copy difference betwixt static together with non static members.

Another substitution affair to banknote almost static members e.g. static variable together with static method is that they belong to shape instead of object, i.e. value of static variable would last same for all object of Counter class.

In this Java tutorial nosotros volition larn What is static keyword inward Java, What is static variable together with static method together with about of import features of static inward Java, which volition non alone assist to sympathise substitution programming concept inward Java but too helps inward diverse Java questions upwardly to two to iv years experience.




What Every Programmer Should Know almost Static inward Java

In this department nosotros volition larn about substitution things almost static keyword inward Java, including its usage on variable, methods together with classes. This is what every Java developer should know almost static earlier going into existent earth programming. So lets get-go with static variables inward Java.

1) You tin non access non static fellow member within static context e.g. static method or static block. Following code volition upshot inward compile fourth dimension error inward Java

public class Counter{  private int count;  public static void main(String args[]){    System.out.println(count); //compile fourth dimension error }  }
 This is 1 of the most mutual error made past times Java programmer especially 1 who simply started programming inward Java. Since main method inward Java is static together with count variable is non static inward this case, impress arguing within master copy method volition throw compile fourth dimension error. See Why non static members is non accessible within static context to know to a greater extent than almost this issue.


2) Unlike local variables,  Static variables together with methods are not thread-safe inward Java. They are genuinely a mutual crusade of diverse thread-safety issues inward Java application. Since every object of a shape has same re-create of static variable, it needs to last guarded past times shape lock. That's why if you lot are using static variables thence brand certain to properly synchronized its access to avoid thread-safety issues including race conditions.

 if a plain is static agency it belongs to shape 10 points almost Static inward Java3) Static methods has payoff inward damage of usability every bit you lot don't demand to do an object patch accessing those methods, You tin telephone yell upwardly whatsoever static method past times using Type of the class, which contains them. That's why they are best suited for creating instances every bit manufactory methods,  and  utility methods. java.lang.Math shape is a perfect representative where almost all methods are static, later utility classes are too declared in conclusion inward Java.

4) Another of import indicate almost static method is that, you lot can non override static method inward Java. If you lot declare same method inward sub shape i.e. static method with same elevate together with method signature
it volition alone cover super shape method, instead of overriding it. This is too known every bit method hiding inward Java. What this agency is, if you lot telephone yell upwardly a static method, which is declared inward both super shape together with sub class, method is ever resolved at compile fourth dimension past times using Type of reference variable. Unlike representative of method overriding they volition non resolved during runtime, every bit shown inward below representative :

class Vehicle{      public static void  kmToMiles(int km){           System.out.println("Inside raise class' static method");      }  }  class Car extends Vehicle{      public static void  kmToMiles(int km){           System.out.println("Inside Child class' static method");      }  }  public class Demo{        public static void main(String args[]){       Vehicle v = new Car();        v.kmToMiles(10);   } }  Output: Inside raise class' static method

As you lot tin encounter that, instead of object beingness of Car, static method from Vehicle is introduced, because method is resolved at compile time. Also at that topographic point is no compile timer error.

5) You tin too brand a shape static inward Java, except overstep degree classes. Those classes are known every bit nested static shape inward Java. nested static shape is peculiarly useful to furnish improved cohesion, 1 examples of nested static shape is HashMap.Entry, which stand upwardly for information structure, used to concur HashMap entries, See How acquire method of HashMap industrial plant inward Java for to a greater extent than details on working of HashMap inward Java. By the way similar whatsoever inner class, nested static shape too results inward a split .class file. Which means, if you lot receive got defined 5 nested classes inward your overstep degree class, you lot volition end-up with half dozen shape files. One for overstep degree shape together with 5 for nested static class. One to a greater extent than purpose representative of nested static shape is defining custom Comparator s e.g. AgeComparator in Employee class. See how to kind listing of Object using Comparator inward Java for mensuration past times mensuration guide of defining Comparator.

6) static keyword tin too last used to declare static block which is executed during shape loading. This is known every bit static initializer block inward Java. If you lot don't declare a static initializer block past times yourself thence Java combines all static fields into 1 block together with execute them during shape loading. Though static block tin non throw checked exception, they tin even thence throw unchecked exception, which if occurred may upshot inward ExceptionInitializerError.  Actually whatsoever runtime exception thrown during instantiation together with initialization of static fields, volition last wrapped past times Java runtime into this error. This is too 1 of the most mutual argue of  NoClassDefFoundError inward Java, because the shape inward interrogation was non nowadays inward retentiveness when its customer needed them.

7) One to a greater extent than affair to know almost static methods is that they are bonded during compile fourth dimension using static binding. This is dissimilar than binding of virtual or non static methods which are bonded during run-time based upon existent object. This agency static method tin non last overridden inward Java every bit  run-time polymorphism doesn't apply on them. This is an of import restriction, you lot should regard patch making a method static inward Java. You should alone brand a method static, if their is no possibility or demand of redefining its behavior for subclass is required. Usually manufactory methods together with utility methods are practiced candidate of beingness static. The cracking Joshua Bloch has highlighted several benefits of using static manufactory method with constructor inward his classic book Effective Java, a must read for every Java developer.

8) One of the of import belongings of static plain is initialization. Static fields or variables are initialized when shape is loaded into memory. They are initialized from overstep to bottom inward the gild they are declared inward Java rootage file. See When shape is loaded inward Java for to a greater extent than details. Since static fields are initialized inward thread-safe manner, this belongings is too used to implement Singleton blueprint inward Java together with if you lot are non using Enum every bit Singleton due to whatever reason, this is a practiced alternative. Only affair to regard is that its non a lazy initialization, which agency static plain volition last initialized fifty-fifty earlier anyone asked for it. If its an expensive object, which is rarely used thence initializing them inward static vogue volition non yield practiced results.

9) During Serialization, like transient variables, static variables are too non serialized. It means, if you lot shop whatsoever information inward static filed thence after de-serialization, novel object volition incorporate its default value e.g. if static plain was int then it volition incorporate zero, if float thence it should incorporate 0.0 together with if object thence it volition incorporate null.  In fact this is 1 of the oft asked  serialization related interrogation inward Java interviews. Make certain non to shop substitution land information of an object inward static field.

10) Another characteristic related to static keyword is called static import. This is similar to criterion import arguing inward Java, but it allows to import 1 or all static members of a class. By importing static method, you lot tin telephone yell upwardly them similar they are defined inward same class, similarly past times static importing fields, nosotros tin access them without specifying shape name. This characteristic was introduced inward Java 1.5, Tiger unloose together with if used properly, improves readability of Java application. One of the place, where you lot oft encounter purpose of static import is JUnit essay out cases because almost all essay out author static import those assert methods e.g. assertEquals() together with their overloaded counterpart. Check what is static import inward Java with Example for consummate details.


That's all on what is Static inward Java  and what every Java developer should know almost static fields, methods, classes together with keyword itself. We receive got basics of  static variables or static fields, static methods, static initializer block together with static import inward Java. We receive got too learned about of import properties of static keyword, which is critical to write together with sympathise Java program. I advise to acquire every Java developer of all sense to master copy static concept inward Java, its absolutely of import for serious programming inward Java.

Further Learning
How to write Java plan to impress Fibonacci series inward Java
Difference betwixt Hashtable together with HashMap inward Java
ArrayList vs Vector inward Java
Top 10 Java coding interview questions together with answers
How to uncovering palindrome inward Java using recursion 

Tuesday, December 10, 2019

How To Swap 2 Integers Without Using Temporary Variable Inwards Java?

One of the oldest flim-flam interrogation from programming interview is, How create y'all swap 2 integers without using temp variable? This was start asked to me on a C, C++ interview together with and thus several times on diverse Java interviews. Beauty of this interrogation lies both on flim-flam to think near how y'all tin swap 2 numbers alongside out tertiary variable, precisely also problems associated alongside each approach. If a programmer tin think near integer overflow together with consider that inwards its solution together with thus it creates a real skillful impression inwards the oculus of interviewers. Ok, thus let's come upward to the point, suppose y'all receive got tow integers i = 10 together with j = 20, how volition y'all swap them without using whatsoever variable thus that j = 10 together with i = 20? Though this is mag occupation together with solution operate to a greater extent than or less inwards every other programming language, y'all demand to create this using Java programming constructs. You tin swap numbers past times performing some mathematical operations e.g. add-on together with subtraction together with multiplication together with division, precisely they confront occupation of integer overflow.


There is a bang-up flim-flam of swapping number using XOR bitwise operator which proves to live on ultimate solution. We volition explore together with sympathize each of these iii solutions inwards particular here, together with if y'all are hungry for to a greater extent than programming questions together with solutions, y'all tin e'er accept a await at Cracking the Coding Interview: 150 Programming Questions together with Solutions, i of the best majority to create for programming undertaking interviews.




Solution 1 - Using Addition together with Subtraction

You tin use + together with - operator inwards Java to swap 2 integers equally shown below :
a = a + b; b = a - b;   // genuinely (a + b) - (b), thus at i time b is equal to a a = a - b;   // (a + b) -(a), at i time a is equal to b

You tin come across that its genuinely prissy flim-flam together with start fourth dimension it took sometime to think near this approach. I was genuinely happy to fifty-fifty think near this solution because its neat, precisely happiness was brusque lived because interviewer said that it volition non operate inwards all conditions. He said that integer volition overflow if add-on is to a greater extent than than maximum value of int primitive equally defined past times Integer.MAX_VALUE together with if subtraction is less than minimum value i.e. Integer.MIN_VALUE.

It confused me together with I conceded alone to abide by that the code is absolutely fine together with operate perfectly inwards Java, because overflows are clearly defined. Ofcourse same solution volition non operate inwards C or C++ precisely it volition operate absolutely fine inwards Java. Don't believe me? hither is the proof :

a = Integer.MAX_VALUE; b = 10;  System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);  a = (a + b) - (b = a);  System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);  Output : Before swap 'a': 2147483647, 'b': 10  After swapping, 'a': 10, 'b': 2147483647 

Here add-on of 2 numbers volition overflow, Integer.MAX_VALUE + 10 = -2147483639, but nosotros are also doing subtraction, which volition compensate this value, because b is at i time Integer.MAX_VALUE together with -2147483639 - 2147483647 volition i time again overflow to laissez passer on y'all 10 equally output.


Solution 2 - Using XOR trick

Second solution to swap 2 integer numbers inwards Java without using temp variable is widely recognized equally the best solution, equally it volition also operate inwards linguistic communication which doesn't grip integer overflow similar Java e.g. C together with C++. Java provides several bitwise together with bitshift operator, i of them is XOR which is denoted past times ^.

If y'all recollect XOR truth tabular array together with thus y'all know that Influenza A virus subtype H5N1 XOR B volition render 1 if Influenza A virus subtype H5N1 together with B are dissimilar together with 0 if Influenza A virus subtype H5N1 together with B are same. This holding gives nascency to next code, popularly know equally XOR trick:

x = x ^ y; y = x ^ y;   // at i time y = x x = x ^ y;  // at i time x = y

Let's come across these examples inwards activeness past times writing a elementary Java program, equally shown below.





Progarm to Swap Two Integers without tempoarry variable inwards Java 

In this Java program, I volition present y'all twain of ways to swap 2 integers without using whatsoever temporary or tertiary variable, together with what are problems comes alongside each approach together with which i volition operate inwards all conditions. Actually the 2 pop solution plant perfectly fine inwards Java precisely candidates, peculiarly those coming from C together with C++ background oftentimes think that start solution is broken together with volition neglect on integer boundaries, precisely that's non true. Integer overflows are clearly define inwards Java e.g. Integer.MAX_VALUE + 1 volition resultant inwards Integer.MIN_VALUE, which agency if y'all create both add-on together with subtraction inwards alongside same railroad train of numbers, your resultant volition live on fine, equally seen inwards higher upward example.

/** * Java programme to swap 2 integers without using temp variable * * @author java67 */ public class Problem {      public static void main(String args[]) {         int a = 10;         int b = 20;          // i way using arithmetics operator e.g. + or -         // won't operate if amount overflows         System.out.println("One way to swap 2 numbers without temp variable");         System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);         a = a + b;         b = a - b; // genuinely (a + b) - (b), thus at i time b is equal to a         a = a - b; // (a + b) -(a), at i time a is equal to b          System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);          // some other example         a = Integer.MIN_VALUE;         b = Integer.MAX_VALUE;          System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);          a = (a + b) - (b = a);          System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);          // Another way to swap integers without using temp variable is         // past times using XOR bitwise operator         // Known equally XOR trick         System.out.println("Swap 2 integers without tertiary variable                              using XOR bitwise Operator");          int x = 30;         int y = 60;          System.out.printf("Before swap 'x': %d, 'y': %d %n", x, y);         x = x ^ y;         y = x ^ y;         x = x ^ y;          System.out.printf("After swapping, 'x': %d, 'y': %d %n", x, y);     }  }  Output One way to swap 2 numbers without temp variable Before swap 'a': 10, 'b': 20 After swapping, 'a': 20, 'b': 10 Before swap 'a': -2147483648, 'b': 2147483647 After swapping, 'a': 2147483647, 'b': -2147483648 Swap 2 integers without tertiary variable using XOR bitwise Operator Before swap 'x': 30, 'y': 60 After swapping, 'x': 60, 'y': 30

That's all near how to swap 2 integers without using temporary variable inwards Java. Unlike pop belief that start solution volition non operate on integer boundaries i.e. approximately maximum together with minimum values, which is also truthful for languages similar C together with C++, it operate perfectly fine inwards Java. Why? because overflow is clearly define together with add-on together with subtraction together negate the number of overflow. There is no incertitude near minute solution equally it is the best solution together with non dependent area to whatsoever sign or overflow problem. It is also believed to live on fasted way to swap 2 numbers without using temp variable inwards Java.

together with how near this meme :)


If y'all are interested inwards solving some elementary together with some tricky programming questions, I advise y'all to accept a await at next railroad train of programming problems :
  • Top thirty Array based programming problems for Java programmers? [problems]
  • Top xx String based coding problems for Java programmers? [problems]
  • Top 10 Programming together with Coding exercises for Java programmers? [problems]
  • How to abide by overstep 2 numbers from integer array? [solution]
  • How to abide by duplicate characters inwards Java String? [solution]
  • How to abide by foursquare beginning of a number inwards Java? [solution]
  • How to impress Fibonacci serial inwards Java without using recursion? [solution]

If y'all are preparing for programming undertaking interviews together with looking for some skillful resources, together with thus y'all tin also accept aid from next books, 2 of the best resources of programming questions :
  • Programming Interviews Exposed: Secrets to Landing Your Next Job [see here]
  • Cracking the Coding Interview: 150 Programming Questions together with Solutions [see here]

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures together with Algorithms: Deep Dive Using Java
Algorithms together with Data Structures - Part 1 together with 2

Sunday, November 24, 2019

Factorial Inward Coffee Using Recursion Together With Loop

Problem : Write a plan to calculate factorial of a given reveal inwards Java, using both recursion too iteration.

Solution : If yous come upward from Maths background too so yous know that factorial of a reveal is number*(factorial of reveal -1). You volition run this formula to calculate factorial inwards this  Java tutorial. Since factorial is a naturally recursive operation, it brand feel to run recursion to solve this work precisely its non ever the best way. Iteration provides a to a greater extent than robust way, precisely don't worry yous volition larn how to calculate factorial amongst too without recursion inwards Java. By the way, factorial of numbers grows really chop-chop too fifty-fifty the largest integral information type inwards Java, long is non able to concur factorial of anything or to a higher house 50. In such cases yous tin run BigInteger, which has theoretically no boundary too tin live used to stand upward for really large integral numbers.


Solution 1 : Factorial using recursion

In companionship to practice a recursive solution yous necessitate a base of operations example where plan terminates too inwards this work base of operations example is factorial of 1, which is 1. So if given reveal is greater than 1, nosotros continue applying factorial formula too recursive telephone telephone this method amongst n - 1 equally shown below :
 public static long factorial(int number){                 //base example - factorial of 0 or 1 is 1         if(number <=1){             return 1;         }                 return number*factorial(number - 1);     }
Once input move yesteryear 1 the method stopped recursive telephone telephone too render 1. From at that spot onward stack started to curl downwards too lastly factorial of reveal is calculated.





Solution 2 : Factorial without Recursion

As I said instead of using recursion too calling factorial method ane time to a greater extent than yous tin likewise run for loop to calculate factorial because !n = n*(n-1)*(n-2).....*1 , which tin easily live implemented using loop equally shown below :
public static long factorial(long input){         long factorial = 1L;         for(long i= input; i > 0; i--){             factorial = factorial * i;         }                  return factorial;     }
You tin meet that nosotros outset amongst the reveal too multiply it amongst the factorial which is initialized amongst 1 too so nosotros cut the reveal yesteryear 1 until reveal becomes 1, which is nix but n*(n-1)*(n-2).....*1.

Write a plan to calculate factorial of a given reveal inwards Java Factorial inwards Java using Recursion too Loop



Java Program to calculate Factorial amongst too without Recursion

Here is our consummate solution of this problem. You tin meet that I receive got created two factorial() method, ane receive got int too render long e.g. long factorial(int number), piece other receive got a long too render a long factorial i.e. long factorial(long number). Since their parameter type is unlike they are 2 unlike method likewise known equally overloaded methods. First method uses recursion to calculate factorial piece minute method uses iteration to calculate factorial.

import java.math.BigInteger; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar;  /**  * Java Program to calculate factorial using iteration too recursion  *   * @author WINDOWS 8  *  */ public class FactorialTest {      public static void main(String args[]) {                 System.out.println("factorial of 1 using recursion : " + factorial(1));         System.out.println("factorial of 1 using iteration : " + factorial(1L));                  System.out.println("factorial of five using recursion : " + factorial(5));         System.out.println("factorial of five using loop : "   + factorial(5L));                         System.out.println("factorial of seven using recursive algorithm : " + factorial(7));         System.out.println("factorial of seven using iterative algorithm : " + factorial(7L));               }         /**      * Java method to calculate factorial of given integer using recursion.      * @param reveal      * @return factorial of reveal      */     public static long factorial(int number){                  //base example - factorial of 0 or 1 is 1         if(number <=1){             return 1;         }                  return number*factorial(number - 1);     }          /**      * Java method to calculate factorial of given reveal using iteration      * @param input      * @return factorial of input      */     public static long factorial(long input){         long factorial = 1L;         for(long i= input; i > 0; i--){             factorial = factorial * i;         }                  return factorial;     }      }  Output : factorial of 1 using recursion : 1 factorial of 1 using iteration : 1 factorial of 5 using recursion : 120 factorial of 5 using loop : 120 factorial of 7 using recursive algorithm : 5040 factorial of 7 using iterative algorithm : 5040


That's all most how to calculate factorial of a reveal inwards Java using both recursion too iteration. This work is oft used to instruct programming, especially recursion inwards schoolhouse too colleges too its proficient ane equally well. Just scream back that fifty-fifty though recursive solution are pocket-size too clear they are prone to throw StackOverFlowException, thence non suitable for production code. Iteration or run of for loop results inwards to a greater extent than robust solution.

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures too Algorithms: Deep Dive Using Java
solution)
  • How to respect if given String is palindrome inwards Java? (solution)
  • How to opposite an int variable inwards Java? (solution)
  • How practice yous swap 2 integers without using temporary variable? (solution)
  • Write a plan to depository fiscal establishment jibe if a reveal is ability of 2 or not? (solution)
  • How to opposite String inwards Java without using StringBuffer? (solution)
  • How practice yous opposite give-and-take of a judgement inwards Java? (solution)
  • How to respect a missing reveal inwards a sorted array? (solution)
  • How To Operate A Appall File From Ascendence Prompt - Windows Together With Unix

    So yous got a JAR file which contains your favorite Java game together with yous are wondering how to run Java plan from JAR  file? Or yous may hold out only trying your manus later running Java plan from the ascendance prompt together with Eclipse IDE. Anyway, it's practiced to know How to execute Java plan from JAR file, every bit JAR file is a almost pop way of transportation Java programs. JAR file ordinarily contains all rootage together with resources inwards the shape of degree files, images, audio files etc. In lodge to run Java plan from JAR file, it must hold out an executable JAR file i.e. it manifest file within META-INF folder must incorporate a Main-class entry similar Main-Class: Hello, which specify the refer of Java degree which contains measure main method inwards Java. Without Main-class entry, yous tin ship away non run a JAR file inwards Java together with if yous attempt to run such offend file using jar ascendance yous volition instruct the fault "Failed to charge Main-Class manifest attribute from HelloWorld.jar". If yous are non really much familiar amongst JAR file together with don't know How to create an executable JAR, See this measurement past times measurement tutorial on How to create executable JAR inwards Java. In this tutorial, nosotros volition exclusively focus on running Java plan from an executable JAR file.


    Running Java plan from JAR file inwards Java

     So yous got a JAR file which contains your favorite Java game together with yous are wondering how to How to Run a JAR file from Command Prompt - Windows together with UNIXmain method every bit an entry point. When nosotros run this JAR file using JAR command, JVM volition telephone telephone this primary method which is specified inwards its manifest file every bit shown below:

    Manifest-version: 1.0
    Main-Class: Hello

    By the way, don't forget to set PATH and  Classpath inwards Java earlier running Java program. If classpath is specified inwards the manifest file together with therefore that volition hold out used past times JVM together with it volition ignore CLASSPATH environs variable, If yous are non familiar amongst these details together with therefore come across How classpath plant inwards Java, must read for whatsoever beginner inwards Java.



    Once yous are certain that Java is installed inwards your machine, path together with classpath are proper, exactly execute the next ascendance together with it volition run your Java plan from the JAR file itself:

    $ coffee -jar Hello.jar


    If yous come across the fault "no primary manifest attribute, inwards Test.jar" it agency your JAR file is non a runnable JAR file i.e. it's manifest file doesn't incorporate Main-Class attribute.

    $ coffee -jar Test.jar
    no primary manifest attribute, inwards Test.jar

    In my example MANIFEST.MF file just contains ane line:

    Manifest-Version: 1.0

    Once  I added the Main-Class attribute it run exactly fine every bit shown below:

    $ coffee -jar Test.jar
    before swapping x: 3
    before swapping y: 3
    after swapping x: 3
    after swapping y: 3

    Here are prissy slides amongst all steps required to run a JAR file from ascendance prompt inwards Windows 8 together with UNIX:

     So yous got a JAR file which contains your favorite Java game together with yous are wondering how to How to Run a JAR file from Command Prompt - Windows together with UNIX


    If yous expression upward whatsoever effect related to Java, classpath together with path spell running your Java plan from JAR file, delight post service here. If yous don't know how to create executable JAR file together with therefore come across this tutorial. That tutorial gives yous measurement past times measurement conduct to making an executable JAR using Eclipse IDE. 


    Other Java programming tutorial yous may uncovering useful

    Saturday, November 23, 2019

    Java Programme To Honor Armstrong Numbers Amongst Example

    Armstrong number Example inwards Java
    How to cheque if a number is Armstrong number or not? or write a Java programme to notice Armstrong number? This is a mutual Java interview inquiry asked on campus interviews together with fresher marking interviews. This is likewise a pop Java programming exercise on diverse school, colleges together with figurer courses to gear upwardly programming logic amidst Students. An Armstrong number is a 3 digit number for which total of cube of its digits is equal to the number itself. An event of Armstrong number is 153 every bit 153= 1+ 125+27 which is equal to 1^3+5^3+3^3. One to a greater extent than event of the Armstrong number is 371 because it is the total of 27 + 343 + i which is equal to 3^3 + 7^3 + 1^3 . In this Java programme example, nosotros volition encounter consummate code event of Java programme to cheque if whatever 3 digit number is Armstrong number or not. If y'all are going for Java interview, together with hence live on develop for about follow-up questions e.g. finding prime numbers, or finding Armstrong number of to a greater extent than than 3 digits.


    By the way, this Java programme is inwards continuation of our before programming practise like




    How to cheque if number is Armstrong number inwards Java

     How to cheque if a number is Armstrong number or non Java Program to notice Armstrong numbers amongst Example
    Here is consummate code for checking if a number is Armstrong number or not. It uses a method called isArmstrong(int number) to implement logic for checking if a number is Armstrong nor not.

    Btw, this is non the same programme every bit impress all Armstrong number betwixt 0 together with 999 but y'all tin dismiss run this logic to solve that inquiry every bit well. All y'all demand to produce is loop till K together with cheque if the number is Armstrong or not. If aye together with hence impress otherwise motion to adjacent number.


    Java Program to Find Armstrong Number
    import java.util.Scanner;  /**  * Simple Java Program to cheque or notice if a number is Armstrong number or not.  * An Armstrong number of 3 digit is a number whose total of cubes of its digit is equal   * to its number. For event 153 is an Armstrong number of 3 digit because 1^3+5^3+3^3 or   1+125+27=153  * @author Javin  */ public class ArmstrongTest{           public static void main(String args[]) {              //input number to cheque if its Armstrong number         System.out.println("Please teach inwards a 3 digit number to notice if                                    its an Armstrong number:");         int number = new Scanner(System.in).nextInt();                //printing result         if(isArmStrong(number)){             System.out.println("Number : " + number + " is an Armstrong number");         }else{             System.out.println("Number : " + number + " is non an Armstrong number");         }           }      /*      * @return truthful if number is Armstrong number or provide false      */     private static boolean isArmStrong(int number) {         int number = 0;         int orig = number;         while(number != 0){             int residuum = number%10;             number = number + remainder*remainder*remainder;             number = number/10;         }         //number is Armstrong provide true         if(orig == result){             return true;         }                return false;     }     }  Output: Please teach inwards a 3 digit number to notice if its an Armstrong number: 153 Number : 153 is an Armstrong number Please teach inwards a 3 digit number to notice if its an Armstrong number: 153 Number : 153 is an Armstrong number Please teach inwards a 3 digit number to notice if its an Armstrong number: 371 Number : 371 is an Armstrong number


    That's all on How to cheque if a number is Armstrong inwards Java. It’s pretty elementary Java programme together with if y'all await closely it simply gets digit past times digit past times using residuum operator together with cut back number past times i digit later dividing it past times 10. Let me know if y'all notice whatever põrnikas on this Java programme for checking Armstrong number.

    Further Learning
    The Coding Interview Bootcamp: Algorithms + Data Structures
    Data Structures together with Algorithms: Deep Dive Using Java
    Java programme to contrary number inwards Java
  • Write a Java programme to cheque if number is palindrome or not
  • Write a Java programme to notice GCD of ii numbers inwards Java
  • Write a Java programme to read text file inwards Java
  • How to notice foursquare rootage of a number inwards Java
  • Fibonacci Serial Inwards Coffee Using Recursion

    Fibonacci serial inwards Java
    Write a Java programme to impress Fibonacci serial upwardly to a given set out or do uncomplicated Java programme to calculate Fibonacci set out is mutual Java questions on fresher interview together with homework. Fibonacci serial is equally good a pop topic on various programming exercises inwards schoolhouse together with colleges. Fibonacci serial is serial of natural set out where side past times side set out is equivalent to the amount of previous 2 set out e.g. fn = fn-1 + fn-2. The get-go 2 numbers of Fibonacci serial is ever 1, 1. In this Java programme instance for Fibonacci series, nosotros do a business office to calculate Fibonacci set out together with thence impress those numbers on Java console. Another twist inwards this questions is that sometime interviewer asks to write a Java programme for Fibonacci numbers using recursion, thence it's ameliorate yous ready for both iterative together with recursive version of Fibonacci number.

    One to a greater extent than coding interrogation which is quite pop is printing prime numbers inwards Java which I induce got discussed earlier. In this tutorial, nosotros volition encounter an instance of both recursive together with iterative algorithm for Fibonacci serial inwards Java.

    For to a greater extent than coding questions yous tin ever expect into Cracking the Code Interviews, ane of the finest collections of code based questions from programming interviews. You volition notice information construction together with algorithmic questions asked on companies similar Amazon, Google, Microsoft, together with Facebook on this book.



    Printing Fibonacci numbers inwards Java : Sample Code Example

    Here is consummate code instance of printing Fibonacci Series inwards Java. Fibonacci serial is calculated using both Iterative together with recursive method together with written inwards Java programming language. We induce got 2 functions inwards this example, fibonacci(int number)  together with  fibonacci2(int number).The get-go ane print Fibonacci serial using recursion together with the 2nd ane using for loop or iteration. 

    You tin evidence this code on your estimator equally well. One yous do your Java origin file, only compile together with run. It volition enquire yous to acquire into the set out till which yous desire to encounter the series. Once yous acquire into thence a number, it volition impress the Fibonacci series inwards the console.




    Java Program to impress Fibonacci Series

    import java.util.Scanner;  /**  * Java programme to calculate together with impress Fibonacci set out using both recursion  * together with Iteration.  * Fibonacci set out is amount of previous 2 Fibonacci numbers fn= fn-1+ fn-2  * get-go 10 Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55  *  * @author Javin  */ public class FibonacciCalculator {      public static void main(String args[]) {             //input to impress Fibonacci serial upto how many numbers         System.out.println("Enter set out upto which Fibonacci serial to print: ");         int set out = new Scanner(System.in).nextInt();                System.out.println("Fibonacci serial upto " + set out +" numbers : ");         //printing Fibonacci serial upto number         for(int i=1; i<=number; i++){             System.out.print(fibonacci2(i) +" ");         }             }          /*      * Java programme for Fibonacci set out using recursion.      * This programme uses tail recursion to calculate Fibonacci set out for a given set out      * @return Fibonacci set out      */     public static int fibonacci(int number){         if(number == 1 || set out == 2){             return 1;         }                return fibonacci(number-1) + fibonacci(number -2); //tail recursion     }          /*      * Java programme to calculate Fibonacci set out using loop or Iteration.      * @return Fibonacci set out      */     public static int fibonacci2(int number){         if(number == 1 || set out == 2){             return 1;         }         int fibo1=1, fibo2=1, fibonacci=1;         for(int i= 3; i<= number; i++){                         //Fibonacci set out is amount of previous 2 Fibonacci number             fibonacci = fibo1 + fibo2;                          fibo1 = fibo2;             fibo2 = fibonacci;                    }         return fibonacci; //Fibonacci number            }       }  Output: Enter set out upto which Fibonacci serial to print: 12 Fibonacci serial upto 12 numbers : 1 1 2 3 5 8 13 21 34 55 89 144

    After asking to write uncomplicated Java programme to impress Fibonacci serial together with afterwards asking for Fibonacci serial using recursion, around other of import interrogation interviewer enquire is how do yous improve your Fibonacci business office both iterative together with recursive one?

    Influenza A virus subtype H5N1 technique called memoization tin hold out used to drastically improve performance of method which calculates Fibonacci number. if yous expect at the method it repetitive creates same Fibonacci set out e.g. In guild to calculate tenth Fibonacci set out business office get-go do get-go ix Fibonacci number, this could hold out rattling fourth dimension consuming if yous only increase the upper boundary from 10 to 10K.

    In memoization programming technique, lawsuit of before calculation is cached together with reused. So yous don't demand to do same Fibonacci set out if yous already induce got calculated it. You tin larn to a greater extent than nearly improving the functioning of algorithms past times reading a skillful majority on information construction together with algorithms e.g. Introduction to Algorithms past times Thomas Cormen.

     Write a Java programme to impress Fibonacci serial upwardly to a given set out or do uncomplicated Java Fibonacci Series inwards Java Using Recursion


    You tin write code for Fibonacci serial amongst memoization past times only using a HashMap and checking if Fibonacci set out for a corresponding set out is already exits or non together with calculate entirely if it doesn't exist.


    Fibonacci Number inwards Java amongst Memoization

    Here is the code instance of printing Fibonacci set out amongst memoization technique :

        /*      * Java Program to calculate Fibonacci numbers amongst memorization      * This is quite fast equally compared to previous Fibonacci business office      * peculiarly for calculating factorial of large numbers.      */     public static int improvedFibo(int number){         Integer fibonacci = cache.get(number);         if(fibonacci != null){             return fibonacci; //fibonacci set out from cache         }         //fibonacci set out non inwards cache, calculating it         fibonacci = fibonacci2(number);                  //putting fibonacci set out inwards cache for time to come asking          cache.put(number, fibonacci);          return fibonacci;     }


    Here is diagram of how Fibonacci serial volition expect similar when yous depict :

     Write a Java programme to impress Fibonacci serial upwardly to a given set out or do uncomplicated Java Fibonacci Series inwards Java Using Recursion

    Performance Comparison Fibonacci business office amongst together with without memoization

    //comparison of functioning of Fibonacci set out amongst memoization int set out = 100000000; long startTime = System.nanoTime(); int lawsuit = fibonacci2(number); //fibonacci set out amongst memoization long elapsedTime = System.nanoTime() - startTime; System.out.println("Time taken to calculate Fibonacci set out upto 100M  without memorization:" + elapsedTime);        startTime = System.nanoTime(); lawsuit = improvedFibo(number); //Fibonacci set out amongst memoization elapsedTime = System.nanoTime() - startTime; System.out.println("Time taken to calculate Fibonacci set out upto 100M  amongst memorization:" + elapsedTime);  Output: Time taken to calculate Fibonacci set out upto 100M without memoization:149479613 Time taken to calculate Fibonacci set out upto 100M amongst memoization:118972384

    Interesting indicate is that improved method entirely shows ameliorate functioning for large numbers similar 100M otherwise iterative version of Fibonacci method is faster. That could hold out explained past times extra piece of employment done past times improved method inwards price of storing value inwards cache together with getting it from at that spot or am I missing something? For to a greater extent than such questions for interviews, yous tin refer majority similar Programming Interviews Exposed past times Wrox publication. 


    That's all on writing Java programme to calculate together with impress Fibonacci series. Fibonacci set out is skillful interrogation for programming practise but when asked equally interrogation in Java interview yous only demand to hold out to a greater extent than detailed together with precise nearly what yous are doing.


    Further Learning
    The Coding Interview Bootcamp: Algorithms + Data Structures
    Data Structures together with Algorithms: Deep Dive Using Java
    Write a Java programme to calculate factorial of a number
  • Write a Java programme to contrary a number
  • How to cheque if a set out is palindrome inwards Java
  • How to notice Armstrong set out inwards Java - Write a program
  • How to calculate GCD of 2 numbers inwards Java
  • How To Multiply 2 Matrices Inwards Java

    I outset learned almost matrix inwards degree twelfth together with I outset wrote the plan to multiply ii matrices on my outset semester of engineering, so, when I idea almost this program, It brings a lot of memories from the past. It's genuinely a beginner practise to prepare coding logic, much similar Fibonacci, prime, together with palindrome check, but what brand this plan interesting is the role of the two-dimensional array to stand upward for a matrix inwards Java.  Since matrix has both rows together with columns, two-dimensional array only naturally fits into the requirement. Another of import affair to solve this work is to retrieve the dominion of matrix multiplication inwards mathematics. If y'all don't retrieve the rule, only forget almost how to solve this problem, unless y'all conduct keep access to Google. So, first, we'll refresh the rules of multiplication together with so we'll await into coding aspect.

    H5N1 Matrix is nil but a two-dimensional array of numbers. It has rows together with columns, for instance next matrix has 2 rows together with three columns
    [2, 4, 6]
    [1, 3, 5]

    To multiply a matrix past times a unmarried release is easy, only multiply each chemical part of a matrix amongst that release is known a scalar multiplication.

    For example, if y'all multiple inwards a higher house matrix amongst 2 hither is how the matrix multiplication volition work

    Matrix Multiply Constant

    These are the calculations:
    2×2=8 2×4=8 2x6=12
    2×1=2 2×3=6 2x5=10

    We telephone squall upward the release ("2" inwards this case) a scalar, so this is called "scalar multiplication", but that's non what y'all volition larn here. In this program, y'all volition larn almost how to multiply i matrix to only about other using array inwards Java.




    Multiplying i matrix to only about other matrix

    In gild to multiply ii matrices, y'all take to calculate the point production or rows together with columns. The "Dot Product" is where nosotros multiply matching members, so amount up:

    (1, 2, 3) • (7, 9, 11) = 1×7 + 2×9 + 3×11 = 58

    We tally the 1st members (1 together with 7), multiply them, likewise for the 2nd members (2 together with 9) together with the third members (3 together with 11), together with lastly amount them up.

    There are likewise ii rules of matrix multiplication which y'all take to remember:
    • The release of columns of the outset matrix must live equal to the release of rows of the instant matrix. For example, if the outset matrix has 2 columns so y'all tin multiply it amongst only about other matrix which has 2 rows. 
    • The production matrix volition conduct keep the same release of rows equally the outset matrix, together with the same release of columns equally the instant matrix.

    Here is a prissy diagram which explains matrix multiplication beautifully amongst an example:

    th together with I outset wrote the plan to multiply ii matrices on my outset semester of engineer How to Multiply Two Matrices inwards Java



    Java Program to multiply ii matrices inwards Java

    Here is our consummate Java plan to multiply i matrix amongst only about other inwards Java. In this program, nosotros conduct keep a Matrix degree which has rows together with columns together with holds the matrix numbers into a two-dimensional array. The Matrix degree likewise conduct keep read() method to read user input using Scanner together with populate the matrix. It likewise has a multiply(Matrix other) method to perform the multiplication of this matrix amongst given matrix together with returns a novel Matrix whose values are equal to the production of ii matrices.  It likewise has a impress method to nicely impress the matrix into the ascendance prompt.

    The multiply(Matrix other) method likewise does only about pre-validation equally per the rules of matrix multiplication e.g. it checks if rows of given Matrix is equal to the column of this matrix or not, if they are non equal so matrix multiplication cannot live performed, thus it throw java.lang.IllegalArgumetnException.  See Clean Code to larn to a greater extent than almost pre-validation inwards methods.

    import java.util.Scanner;  /*  * Java Program to multiply ii matrices  */ public class MatricsMultiplicationProgram {    public static void main(String[] args) {      System.out         .println("Welcome to Java plan to calcualte multiplicate of ii matrices");     Scanner scnr = new Scanner(System.in);      System.out.println("Please come inwards details of outset matrix");     System.out.print("Please Enter release of rows: ");     int row1 = scnr.nextInt();     System.out.print("Please Enter release of columns: ");     int column1 = scnr.nextInt();     System.out.println();     System.out.println("Enter outset matrix elements");     Matrix first = new Matrix(row1, column1);     first.read();      System.out.println("Please come inwards details of instant matrix");     System.out.print("Please Enter release of rows: ");     int row2 = scnr.nextInt();     System.out.print("Please Enter release of columns: ");     int column2 = scnr.nextInt();     System.out.println();     System.out.println("Enter instant matrix elements");      Matrix instant = new Matrix(row2, column2);     second.read();      Matrix production = first.multiply(second);      System.out.println("first matrix: ");     first.print();     System.out.println("second matrix: ");     second.print();     System.out.println("product of ii matrices is:");     product.print();      scnr.close();    }  }  /*  * Java degree to stand upward for a Matrix. It uses a ii dimensional array to  * stand upward for a Matrix.  */ class Matrix {   private int rows;   private int columns;   private int[][] data;    public Matrix(int row, int column) {     this.rows = row;     this.columns = column;     data = new int[rows][columns];   }    public Matrix(int[][] data) {     this.data = data;     this.rows = data.length;     this.columns = data[0].length;   }    public int getRows() {     return rows;   }    public int getColumns() {     return columns;   }    /**    * fills matrix from information entered past times user inwards console    *     * @param rows    * @param columns    */   public void read() {     Scanner s = new Scanner(System.in);     for (int i = 0; i < rows; i++) {       for (int j = 0; j < columns; j++) {         data[i][j] = s.nextInt();       }     }    }    /**    *     * @param a    * @param b    * @return    */   public Matrix multiply(Matrix other) {     if (this.columns != other.rows) {       throw new IllegalArgumentException(           "column of this matrix is non equal to row "               + "of instant matrix, cannot multiply");     }      int[][] production = new int[this.rows][other.columns];     int amount = 0;     for (int i = 0; i < this.rows; i++) {       for (int j = 0; j < other.columns; j++) {         for (int k = 0; k < other.rows; k++) {           amount = amount + data[i][k] * other.data[k][j];         }         product[i][j] = sum;       }     }     return new Matrix(product);   }    /**    *     * @param matrix    */   public void print() {     for (int i = 0; i < rows; i++) {       for (int j = 0; j < columns; j++) {         System.out.print(data[i][j] + " ");       }       System.out.println();     }   }  }  Output: Welcome to Java plan to calculate multiplicate of ii matrices Please enter details of the first matrix Please Enter release of rows: 2 Please Enter release of columns: 2  Enter first matrix elements 1 2 3 4 Please enter details of the instant matrix Please Enter release of rows: 2 Please Enter release of columns: 2  Enter instant matrix elements 1 2 2 2 first matrix:  1 2  3 4  instant matrix:  1 2  2 2  production of ii matrices is: 5 11  22 36 


    That's all almost how to write a Java plan to multiply ii matrices. You tin role this plan for trying together with testing. You should fifty-fifty endeavour to write JUnit essay out for this plan to depository fiscal establishment check diverse boundary conditions. If y'all don't know how to write Junit essay out cases inwards Java so delight refer to JUnit inwards Action or Test Driven, a TDD together with credence TDD guide for Java developers. These exercises volition assistance y'all to cook your programming logic together with likewise assistance y'all to sympathize when together with how to role information construction land solving problems.


    Other Java Programming exercises for beginners
    • How to implement binary search using recursion inwards Java? (solution)
    • How to calculate the average of all numbers of an array inwards Java? (program)
    • How to implement Linear Search inwards Java? (solution)
    • How to calculate the foursquare origin of a given release inwards Java? (solution)
    • How to calculate Area of Triangle inwards Java? (program)
    • How to uncovering all permutations of a given String inwards Java? (solution)
    • How to remove duplicate elements from the array inwards Java? (solution)
    • How to depository fiscal establishment check if ii given Strings are Anagram inwards Java? (solution)
    • How to impress Fibonacci serial inwards Java (solution)
    • How to depository fiscal establishment check if a twelvemonth is a trammel twelvemonth inwards Java? (solution)
    • How to opposite a String inwards house inwards Java? (solution)
    • How to depository fiscal establishment check if given release is prime number inwards Java (solution)
    • How to uncovering the highest occurring give-and-take from a given file in Java? (solution)
    • How to count vowels together with consonants inwards given String inwards Java? (solution)
    • How to depository fiscal establishment check if given String is palindrome or non inwards Java? (solution)
    • How to take away duplicate characters from String inwards Java? (solution)
    • How to depository fiscal establishment check if a String contains duplicate characters inwards Java? (solution)
    • How to opposite words inwards a given String inwards Java? (solution)
    • How to calculate the amount of all elements of an array inwards Java? (program)
    • How to depository fiscal establishment check if ii rectangles intersect amongst each other inwards Java? (solution)
    • How to opposite an array inwards house inwards Java? (solution)
    • How to uncovering if given Integer is Palindrome inwards Java? (solution)

    Further Learning
    Data Structures together with Algorithms: Deep Dive Using Java
    Java Fundamentals: The Java Language
    Complete Java Masterclass