Showing posts with label Sorting Algorithm. Show all posts
Showing posts with label Sorting Algorithm. Show all posts

Monday, March 30, 2020

Unix Ascendancy To Discovery Symbolic Link Or Soft Link Inwards Linux

There are 2 ways y'all tin detect a symbolic link or soft link inwards UNIX based operating organization e.g. Linux, Solaris, BSD or IBM AIX. The commencement way is yesteryear using ls ascendance inwards UNIX which displays files, directories, as well as links inwards whatever directory as well as other way is yesteryear using UNIX detect ascendance which has the mightiness to search whatever sort of files e.g. file, directory or link. In this UNIX ascendance tutorial, nosotros volition encounter examples both of these UNIX commands for finding a soft link inwards whatever directory. If y'all are novel to UNIX operating organization as well as non familiar alongside the concept of the soft link as well as difficult link, I would recommend getting a practiced manus on it, every bit it is i of the virtually powerful features of UNIX based system.


One to a greater extent than concept which is quite of import to larn is file as well as directory permissions because UNIX provides a unlike score of permissions as well as link inherit permission of finish folder where they are pointing out.

This is too a really popular Linux interview question asked on both organization admin every bit good every bit developer score interview. Anyways Let's start alongside the commencement instance of How to detect a symbolic link inwards UNIX using “ls” command:




ls ascendance to detect a symbolic link inwards UNIX systems

permission details of each file as well as directories, if y'all await carefully for links that String starts alongside modest  L ( 50 for the link).

If y'all combine the output of ls ascendance alongside grep as well as purpose a regular expression to detect all entries which start alongside modest L  than y'all tin easily detect all soft link on whatever directories.

Here is the sum UNIX ascendance instance of finding the symbolic link using ls as well as grep command:

java67@blogspot: ls -lrt
total 3.0K
-rw-r--r--  1 java67 Domain Users 79 Jul 19  2011 test.txt
drwxr-xr-x+ 1 java67 Domain Users  0 Jun fifteen 12:07 unix/
drwxr-xr-x+ 1 java67 Domain Users  0 Sep xix 12:30 java/
lrwxrwxrwx  1 java67 Domain Users  4 Sep xix 12:31 version_1.0 -> java/
lrwxrwxrwx  1 java67 Domain Users  4 Sep 21 13:59 os -> unix/


java67@blogspot: ls -lrt | grep ^l
lrwxrwxrwx  1 java67 Domain Users  4 Sep xix 12:31 version_1.0 -> java/
lrwxrwxrwx  1 java67 Domain Users  4 Sep 21 13:59 os -> unix/


The ^ grapheme is a exceptional regular facial expression which agency the start of the line. You tin farther check find ascendance inwards UNIX. Since all UNIX based operating organization e.g. Linux, Solaris or IBM AIX back upwards find, it's non solely available only virtually powerful way to detect a soft link inwards whatever directory or subdirectory.

When y'all purpose detect ascendance alongside option type as well as specify the type every bit modest L ( 50 for the link), it displays all soft link inwards the specified path.

For example, next the instance of detect ascendance volition demo all soft link inwards the electrical flow directory as well as its subdirectory :


java67@blogspot: find . -type l
./java/version_1.0
./os
./version_1.0

Here the dot (.) character denotes a electrical flow directory. 

Linux System Administration Fundamentals

Thanks for reading this UNIX tutorial, if y'all similar this instance as well as my explanation thus delight part alongside your friends as well as colleagues. If y'all bring whatever questions or feedback thus delight drib a note.

Sunday, March 29, 2020

Bubble Variety Out Inward Coffee - Plan To Variety Out Integer Array

Bubble form is 1 of the classic sorting algorithm which is used to explicate sorting during diverse estimator together with technology scientific discipline courses. Because of its algorithmic nature together with simplicity its oftentimes used inward diverse Java together with C++ programming exercises. You may aspect questions similar Write Java plan to form integer array using bubble sort during whatever programming interview. Since algorithmic questions are e'er tricky question together with non slowly to code. Even simplest of them tin Pb to confusion, specially if you lot are non gifted amongst a natural programming head. I accept seen many developers fumble if asked to code on the spot. That's why its advisable to create algorithmic together with logical programming during preparation together with learning programming together with OOPS to acquire this science of converting logic into code. Let's come upwardly dorsum to Bubble sort, In Bubble form algorithm nosotros form an unsorted array yesteryear starting from outset chemical gene together with comparing amongst side yesteryear side element. If erstwhile is greater than later therefore nosotros swap together with yesteryear doing this nosotros acquire the largest break at the halt after outset iteration. So inward gild to form n elements you lot require n-1 iteration together with nearly n-1 comparison. For recap hither is the logic for bubble form sorting algorithm :

1) start comparing a[0] to a[1]
2) if a[0] > a[1] therefore swap numbers e.g. a[0]=a[1] together with a[1]=a[0]
3) compare a[1] to a[2] together with repeat till you lot compare terminal pair
4) This is referred every bit 1 locomote yesteryear together with at the halt of outset locomote yesteryear largest break is at last
5) repeat this comparing 1 time to a greater extent than starting from a[0] but this fourth dimension going till minute terminal dyad only

Now let's encounter Java plan which implements this bubble form logic to form unsorted integer array.



How to form integer array using bubble form inward Java

Bubble form is 1 of the classic sorting algorithm which is used to explicate sorting durin Bubble form inward Java - plan to form integer arrayHere is consummate code illustration of bubble form inward Java. It uses same algorithm every bit explained inward outset pass, it uses 2 loops. Inner loop is used to compare side yesteryear side elements together with outer loop is used to perform Iteration. because of using 2 loops it trial inward gild of n^2 which is non swell inward damage of performance. If you lot are using Array List instead of array than you lot tin form them using Collections.sort method for amend performance, for details cheque How to form Array List inward ascending together with descending order.

package test;

import java.util.Arrays;

/**
 * Java plan to form integer array using bubble form sorting algorithm.
 * bubble form is 1 of the simplest sorting algorithm but performance
 * of bubble form is non good, its average together with worst illustration performance
 * ranges inward O(n2) together with that's why it is non used to form large ready of
 * unsorted data. Bubble form tin live used for educational together with testing
 * piece of employment to form small-scale break of information to avoid surgery penalty.
 * This plan is likewise a proficient illustration of how to impress contents of Array inward Java
 *
 * @author http://java67.blogspot.com
 */

public class BubbleSort {
 
 
    public static void main(String args[]) {
        //testing our bubble form method inward Java
        int[] unsorted = {32, 39,21, 45, 23, 3};
        bubbleSort(unsorted);
     
        //one to a greater extent than testing of our bubble form code logic inward Java
        int[] assay out = { 5, 3, 2, 1};
        bubbleSort(test);
     
    }  
 
    /*
     * In bubble form nosotros demand n-1 iteration to form n elements
     * at halt of outset iteration larget break is sorted together with later numbers smaller
     * than that.
     */

    public static void bubbleSort(int[] unsorted){
        System.out.println("unsorted array earlier sorting : " + Arrays.toString(unsorted));
     
        // Outer loop - demand n-1 iteration to form n elements
        for(int i=0; i<unsorted.length -1; i++){
         
            //Inner loop to perform comparision together with swapping betwixt side yesteryear side numbers
            //After each iteration 1 index from terminal is sorted
            for(int j= 1; j<unsorted.length -i; j++){
             
                //If electrical flow break is greater than swap those two
                if(unsorted[j-1] > unsorted[j]){
                    int temp = unsorted[j];
                    unsorted[j] = unsorted[j-1];
                    unsorted[j-1] = temp;
                }
            }
            System.out.printf("unsorted array after %d locomote yesteryear %s: %n", i+1, Arrays.toString(unsorted));
        }
    }

}

Output:
unsorted array earlier sorting : [32, 39, 21, 45, 23, 3]
unsorted array after 1 locomote yesteryear [32, 21, 39, 23, 3, 45]:
unsorted array after 2 locomote yesteryear [21, 32, 23, 3, 39, 45]:
unsorted array after 3 locomote yesteryear [21, 23, 3, 32, 39, 45]:
unsorted array after 4 locomote yesteryear [21, 3, 23, 32, 39, 45]:
unsorted array after 5 locomote yesteryear [3, 21, 23, 32, 39, 45]:
unsorted array earlier sorting : [5, 3, 2, 1]
unsorted array after 1 locomote yesteryear [3, 2, 1, 5]:
unsorted array after 2 locomote yesteryear [2, 1, 3, 5]:
unsorted array after 3 locomote yesteryear [1, 2, 3, 5]


That's all on How to form integer array using Bubble form inward Java. We accept seen a consummate Java plan for bubble form together with likewise printed output after each locomote yesteryear or iteration, if you lot aspect at carefully you lot volition honor that after each locomote yesteryear largest break gets sorted together with break of comparing decreased. As I said Bubble form is non a high surgery sorting algorithm together with you lot should yesteryear using Collection.sort() method from criterion Java library to form Collections or Arrays.sort() to form Array inward Java. Also this plan demonstrate How to impress contents of Array using Arrays.toString() every bit array inward Java doesn’t override toString together with but printing array using System.out.println(array) volition exclusively demo defulat toString from java.lang.Object shape instead of contents of array.

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures together with Algorithms: Deep Dive Using Java
Difference betwixt abstract shape together with interface inward Java

Saturday, March 28, 2020

10 Programming Questions In Addition To Exercises For Coffee Programmers

If yous convey simply started learning basics of Java programming linguistic communication or familiar amongst programming inwards either C or C++ hence these Java programming questions as well as exercises for you. It doesn't focus on detail percentage of Java but these coding exercises volition switch yous inwards programming mode.These are likewise neat way to master copy basic programming build similar if-else , loops similar for as well as while, break as well as croak on amongst loop,   Java operators e.g. arithmetics as well as logical operator, recursion, methods or functions as well as mutual Java API. You may likewise uncovering these Java programming questions inwards close of Java courses taught inwards school, colleges as well as diverse Java preparation courses. Even I convey started learning Java past times doing these exercises multiple times amongst dissimilar ways. They are interesting, gives feeling of accomplishment if yous consummate it. These Java programs looks uncomplicated but they are notwithstanding tricky for novice Java programmers. Try to solve these coding exercises past times yourself but if yous stuck yous tin forcefulness out depository fiscal establishment lucifer relevant links or of-course usage google to acquire to a greater extent than insight on them. You tin forcefulness out likewise see here to a greater extent than Java programming questions as well as exercises.


Java Programing Questions exercises for beginners to practices

Here is my listing of 10 Java programming questions or Java programs which tin forcefulness out assistance whatsoever beginner to acquire started inwards programming world. These are classics, pop as well as real effective. You tin forcefulness out usage either notepad or whatsoever Java IDE similar Eclipse or Netbeans for coding. See links for solution as well as hints.



1. Write a programme inwards Java to depository fiscal establishment lucifer if a release is fifty-fifty or strange inwards Java? (input 2 output true, input three : output false)
A release is called fifty-fifty if it is completely divisible past times 2 as well as strange if it’s non completely divisible past times two. For representative release four is fifty-fifty release because when yous create 4/2 , relaxation is 0 which agency four is completely divisible past times 2. On the other manus five is strange release because 5/2 volition resultant inwards relaxation equally 1. See here to uncovering how to depository fiscal establishment lucifer fifty-fifty as well as strange release inwards Java.

2. Write a programme inwards Java to uncovering out if a release is prime inwards Java? (input 7: output truthful , input nine : output false)
A release is called prime if it is divisible past times either itself or 1. There are many algorithm to uncovering prime numbers e.g. instead of dividing till number, partition upto foursquare origin of release may last enough. Start from simplest ane as well as than endeavor to solve this work amongst span of dissimilar ways. Here is ane way to check prime numbers inwards Java

3. Write Java programme to depository fiscal establishment lucifer if a release is palindrome inwards Java? ( 121 is palindrome, 321 is not)
A release is called a palindrome if release is equal to opposite of release e.g. 121 is palindrome because opposite of 121 is 121 itself. On the other manus 321 is non palindrome because opposite of 321 is 123 which is non equal to 321. See hither for solution of  checking if a release is palindrome or non inwards Java.

4. How to uncovering if a release is ability of 2 inwards Java? (1,2, four ability of 2, three is not)
This is unopen to other interesting Java programming exercise. This programme tin forcefulness out last solved using dissimilar ways e.g. using arithmetics operator or past times using flake shift operator.

5. Write programme to kind an integer array without using API methods?
If yous convey simply started learning basics of Java programming linguistic communication or familiar amongst pro 10 Programming questions as well as exercises for Java ProgrammersSorting questions are ane of the integral percentage of programming questions. There are many sorting algorithm out at that topographic point to kind whatsoever array inwards Java e.g. Bubble sort, Insertion sort, Selection kind or quick sort. Implementing sorting algorithm itself a expert programming exercise inwards Java. By the way hither is ane way to sort an integer array amongst Bubble kind algorithm inwards Java.

6. Write Java programme to depository fiscal establishment lucifer if a release is Armstrong release or not? (input 153 output true,  123 output false)
An Armstrong release of three digit is a release for which pith of cube of its digits are equal to release e.g. 371 is an Armstrong release because 3*3*3 + 7*7*7 + 1*1*1 = 371). See hither for sample Java program to check if a release is Armstrong release or not.

7. Write a programme inwards Java to opposite whatsoever String without using StringBuffer?
This is unopen to other classical Java programming question. You tin forcefulness out opposite String inwards diverse way inwards Java but 2 programming technique is used to create e.g. Iteration as well as Recursion. Try solving this work using Iteration kickoff past times using Java’s arithmetics operator as well as than expect to implement a recursive solution. Here is ane way to reverse String inwards Java without using StringBuffer.

8. Write a programme inwards Java to impress Fibonacci serial upwardly to given number? Write both iterative as well as recursive version.
Fibonacci serial a pop release serial as well as real pop programming enquiry inwards Java, inwards which release is equal to pith of previous 2 numbers, starting from third. Fibonacci serial is likewise a expert recursion exercise as well as ofttimes asked inwards Interviews equally well. Try doing this exercise past times using both Iteration e.g. loops as well as recursion. For assistance encounter How to impress Fibonacci serial inwards Java using recursion.

9. Write a Java programme to calculate factorial of an integer release ? Both iterative as well as recursive solution.
Calculating Factorial is likewise a classic recursion exercise inwards programming. Since factorial is a recursive function, recursion becomes natural selection to solve this problem. You simply demand to hollo upwardly formula for calculating factorial which is for n! its n*(n-1)*…1. hither is ane way to calculate Factorial inwards Java using recursion.


10. Print next construction inwards Java?
This programme is a expert exercise for mastering loops e.g. for loop as well as acre loop inwards Java. This likewise teaches you How to usage intermission as well as croak on tilt amongst loops inwards Java. By the way yous tin forcefulness out impress whatsoever graphic symbol as well as usage System.out.print() as well as System.out.println())
*
***
*****
***
*

These were unopen to programming questions as well as exercises for beginners learning Java programming language. This listing is uncomplicated as well as yous tin forcefulness out solve these coding exercises inwards whatsoever programming language. I am certain Java beginners volition uncovering these exercises interesting as well as useful. You tin forcefulness out likewise postal service whatsoever coding exercise which yous think tin forcefulness out assistance junior programmers to acquire programming as well as assistance converting logic to code.

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures as well as Algorithms: Deep Dive Using Java
How to gear upwardly PATH for Java inwards Windows as well as Linux

Helloworld Programme Inward Coffee Alongside Example

First of all, welcome to the exciting footing of Java programming. If you lot are gear upwards to write your outset Java programme i.e. HelloWorld inwards Java, it way you lot already crossed major hurdles to start Java programming, inwards price of installing JDK together with setting PATH for Java. If you lot haven't done hence together with then you lot tin plough over the sack follow those tutorials to install JDK inwards Windows vii together with 8 together with setting PATH for Java. Before nosotros start writing HelloWorld inwards Java, few notes nearly editors. Many Java beginners insist or endeavour to role Eclipse or Netbeans IDE from the rattling start of the outset program, which is non a proficient idea. In companionship to larn syntax together with semantics of Java programming, you lot should code inwards notepad, give-and-take pad or whatsoever other text editor. I started coding inwards DOS Editor, but I won't propose that to you. Notepad++ is best of both world, it back upwards Java syntax highlighting, which helps to sympathise keywords better, together with its too a pleasant coding experience. 

If you lot don't get got notepad++, you lot tin plough over the sack download it cast http://notepad-plus-plus.org/, its FREE. Once you lot get got JDK, PATH together with Notepad++ installed, it’s fourth dimension to code your outset Java program, HelloWorld.



HelloWorld inwards Java

Here is measuring past times measuring guide to coding, compile together with run HelloWorld inwards Java from the ascendance prompt. Yes, nosotros are going to run Java programme from ascendance prompt, if you lot are not  very familiar together with then run across that link.



1) Create a Java rootage file every bit HelloWorld.java inwards Notepad++. It's ruled inwards Java to mention rootage file on the mention of the populace cast within that file.

2) Create a class, HelloWorld every bit public cast HelloWorld{}. It's Java coding convention to start the mention of the cast amongst a upper-case alphabetic lineament letter.

3) Now, add together the main method within HelloWorld class. every bit public static void main(String args[]){}. Like C programming language, execution of Java programme from start method. There is the pregnant of every unmarried keyword used amongst the primary method, together with you lot tin plough over the sack depository fiscal establishment represent why primary is populace static together with void inwards Java to know this. By the way, at that spot are a twosome of syntaxes to declare a measure primary method, but nosotros volition stick amongst this every bit it's measure 1 together with simplest of all.

4) Now it's fourth dimension to write code to impress HelloWorld inwards the console. You tin plough over the sack write System.out.println("HelloWorld"); within primary to print HelloWorld inwards Java. Remember to position semi colon at the destination of the statement, every bit a tilt inwards Java ends amongst a semi colon. The System is an inbuilt cast which comes amongst JDK together with it’s business office of rich Java API. DOT operator is used to accessing champaign together with methods, which way out is a filed within System class, which has println() method, together with which does the chore of printing characters or string to the console.

5) If you lot await at println() method it  accepts a String literal, which is enclosed inwards double quotes inwards Java, together with prints it on the console together with too adds a novel line. hither is consummate code instance of HelloWorld programme inwards Java

public class HelloWorld {        public static void main(String args[]) {         System.out.println("HelloWorld Java");     }     }

6) Save your Java rootage file together with gear upwards to compile it.

7) Open ascendance prompt inwards Windows, past times typing cmd on run window together with type javac, if you lot see,  javac non recognized every bit an internal or external command, way PATH for Java is non laid together with nosotros ask to right that. See this tutorial laid Java Path on Windows. If you lot run across javac output together with options way nosotros are gear upwards to compile.

8) Now become to the directory, where you lot get got position your Java rootage file, HelloWorld.java together with type : javac HelloWorld.java , this ascendance volition learn Java compiler to compile Java rootage file together with practise cast files, which contains Java bytecode for execution inwards JVM. The compiler volition exhibit compilation fault if at that spot is whatsoever syntax, semantics the or compiler fault inwards Java rootage file. If you lot run across an error, together with then nosotros ask to resolve that. Just glue it hither together with nosotros tin plough over the sack operate it out.

9) If everything goes well, nosotros could see, HelloWorld.class file inwards electrical current directory. It way you lot are gear upwards to run your how-do-you-do footing programme inwards Java. Next measuring is to run Java program.

10) Type java HelloWorld on ascendance prompt, brand certain you lot run this ascendance from electrical current directory, where HelloWorld.class file is present. You run across simply mention of cast without extension, together with it volition learn JVM to find, charge together with execute HelloWorld class. If at that spot is no runtime exception, than you lot tin plough over the sack run across "HelloWorld Java" every bit output inwards console.

 welcome to the exciting footing of Java programming HelloWorld Program inwards Java amongst Example


That's all on How to create, compile together with run HelloWorld programme inwards Java. I highly recommend to role notepad++ for coding at to the lowest degree for few months, to larn Java programming. If you lot appear upwards whatsoever fault acre compiling or running this Java program, together with then delight post here. We volition endeavour to resolve together with explicate it here.

Further Learning
Complete Java Masterclass
Java ArrayList Tutorial together with Examples

Thursday, December 12, 2019

How To Banking Concern Lucifer If Given Publish Is Prime Number Inward Coffee - Amongst Example

One of the most mutual programming exercise for beginners is, write a programme to depository fiscal establishment stand upward for if given number is prime or not? There are many methods to depository fiscal establishment stand upward for if a number is prime or not, exactly most mutual of them is case division, which is what nosotros volition encounter inwards this tutorial. In my opinion, these form of programme is their commencement steps towards algorithmic understanding. You commencement come upward amongst a solution, which is driven yesteryear the fact that prime numbers are natural numbers, which are non divisible yesteryear whatever positive number other than 1 in addition to themselves. You write a for loop to depository fiscal establishment stand upward for every number, starting from 1 to given number, to encounter if given number is divisible yesteryear whatever positive number or not. This leads y'all to the solution. Then y'all abide by to a greater extent than or less to a greater extent than fact that at that topographic point is no demand to depository fiscal establishment stand upward for till N-1, where due north is the number nosotros are checking for primeness, in addition to checking till foursquare rootage of due north is enough. This reduces a lot of time, peculiarly piece checking a large number is prime or not.


Further, y'all come upward to know that if its non divisible yesteryear 2 in addition to then at that topographic point is no demand to checking for whatever other fifty-fifty number, in addition to y'all growth counter yesteryear 2, instead of 1. So inwards a way, y'all larn how to optimize your solution yesteryear taking wages of facts available.

After this y'all tin strength out endeavour something like Fibonacci series, or may be finding factorial of a number inwards Java to create to a greater extent than or less to a greater extent than exercise on programming. This volition non solely instruct y'all linguistic communication basics e.g. loops, command statements like if-else, usage of arithmetics in addition to relational operator exactly likewise helps to prepare programming logic.

By the way, y'all tin strength out fifty-fifty convey this work of checking if a number is prime or not, to adjacent degree yesteryear endeavour to implement unlike algorithms for finding primes e.g. sieve of Atkin or  sieve of Eratosthenes. In fact inwards programming challenges, y'all frequently demand to construct your prime cache up-to a for certain number to progress farther inwards finding solution.

This query is likewise asked on written exam in addition to interview equally  how to impress prime numbers from 1 to 100  or finding prime element of a number inwards Java.



Java Program to Check if an Integer is Prime or Not

 One of the most mutual programming exercise for beginners is How to Check if Given Number is Prime inwards Java - With Example
This is our Java programme to encounter if a given integer number is prime or not. As I said, a number is called a prime if its solely divisible yesteryear 1 or itself, which agency prime doesn't cause got whatever positive divisor other than itself. There are many ways to depository fiscal establishment stand upward for if number is prime or not, or generating listing of primes. Easiest of them is known equally trial division, which is a natural way of finding prime. In case division, y'all carve upward . It consists of testing whether n is a multiple of whatever integer between 2 in addition to sqrt{n}.  In this programme I cause got presented 3 solution or method to depository fiscal establishment stand upward for if number is prime. First solution is implementation of case division, where nosotros are checking from 2 to sqrt(n), nosotros are using java.lang.Math shape for calculating foursquare root. Since this purpose returns double, nosotros demand to cast number dorsum into integer. Our instant method of checking if a number is prime or not is piddling fleck optimized that this equally it doesn't depository fiscal establishment stand upward for partitioning yesteryear fifty-fifty numbers other than two.Third method is most optimized of all 3 methods of prime checking. By the way at that topographic point is to a greater extent than or less other exercise for y'all to create afterwards this is checking if a number is  Armstrong number  or not.


import java.util.Scanner; /**  * Java Program to depository fiscal establishment stand upward for if a number is Prime or Not. This programme accepts a  * number from command prompt in addition to depository fiscal establishment stand upward for if it is prime or not.   *  * @author  http://java67.blogspot.com  */ public class Testing {      public static void main(String args[]) {         Scanner scnr = new Scanner(System.in);         int number = Integer.MAX_VALUE;         System.out.println("Enter number to depository fiscal establishment stand upward for if prime or non ");         while (number != 0) {             number = scnr.nextInt();             System.out.printf("Does %d is prime? %s %s  %s %n", number,                     isPrime(number), isPrimeOrNot(number), isPrimeNumber(number));         }     }       /*      * Java method to depository fiscal establishment stand upward for if an integer number is prime or not.      * @return truthful if number is prime, else false      */     public static boolean isPrime(int number) {         int sqrt = (int) Math.sqrt(number) + 1;         for (int i = 2; i < sqrt; i++) {             if (number % i == 0) {                 // number is perfectly divisible - no prime                 return false;             }         }         return true;     }       /*      * Second version of isPrimeNumber method, amongst improvement similar not      * checking for partitioning yesteryear fifty-fifty number, if its non divisible yesteryear 2.      */     public static boolean isPrimeNumber(int number) {         if (number == 2 || number == 3) {             return true;         }         if (number % 2 == 0) {             return false;         }         int sqrt = (int) Math.sqrt(number) + 1;         for (int i = 3; i < sqrt; i += 2) {             if (number % i == 0) {                 return false;             }         }         return true;     }       /*      * Third way to depository fiscal establishment stand upward for if a number is prime or not.      */     public static String isPrimeOrNot(int num) {         if (num < 0) {             return "not valid";         }         if (num == 0 || num == 1) {             return "not prime";         }         if (num == 2 || num == 3) {             return "prime number";         }         if ((num * num - 1) % 24 == 0) {             return "prime";         } else {             return "not prime";         }     } }  Output Enter number to depository fiscal establishment stand upward for if prime or non 2? Does 2 is prime? true prime  true 3? Does 3 is prime? true prime  true 4? Does 4 is prime? false non prime  false 5? Does 5 is prime? true prime  true 6? Does 6 is prime? false non prime  false 7? Does 7 is prime? true prime  true 17? Does 17 is prime? true prime  true 21? Does 21 is prime? false non prime  false 131? Does 131 is prime? true prime  true 139? Does 139 is prime? true prime  true

That's all inwards this programme nearly how to depository fiscal establishment stand upward for if a number is prime or not. number must endure integer, equally concept of prime is solely for natural numbers in addition to non for floating betoken numbers. As I said at that topographic point are span of to a greater extent than algorithms for checking if a number is prime or not, in addition to to a greater extent than or less of the algorithm is optimized for finding prime numbers. It imperative to know at-least 1 fast way of finding prime number,as this case partitioning is non fast plenty for existent earth problems. I advise exploring sieve of Atkin and sieve of Eratosthenes way of finding prime numbers.

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures in addition to Algorithms: Deep Dive Using Java
Algorithms in addition to Data Structures - Part 1 in addition to 2

How To Honour Duplicate Characters On String - Coffee Programming Problems

Today's programming do is to write a plan to honour repeated characters inwards a String. For example, if given input to your plan is "Java", it should impress all duplicates characters, i.e. characters look to a greater extent than than 1 time inwards String together with their count e.g. a = 2 because grapheme 'a' has appeared twice inwards String "Java". This is too a really pop coding interrogation on the diverse score of Java interviews together with written test, where yous demand to write code. On difficulty level, this interrogation is at par amongst prime numbers or Fibonacci series. I personally similar this do because it gives beginners an chance to familiar amongst the concept of Map information structure, which allows yous shop mappings inwards the cast of fundamental together with value. Since Map is heavily used inwards whatever venture Java application, skilful noesis of this information construction is highly desirable amidst whatever score of Java programmers.


By the way, in that place are a twain of variants of this problem, which yous may desire to await earlier going for an interview. Sometimes an interviewer volition inquire yous to read a file together with impress all duplicate characters together with their count, substance logic volition stay same, all yous demand to create is demonstrate how much yous know virtually File IO inwards Java e.g. streaming file if it's really large rather than reading the whole file inwards memory.




Java Program to honour Repeated Characters of String

The measure means to solve this employment is to larn the grapheme array from String, iterate through that together with construct a Map amongst grapheme together with their count. Then iterate through that Map together with impress characters which accept appeared to a greater extent than than once. So yous truly demand 2 loops to create the job, the get-go loop to construct the map together with bit loop to impress characters together with counts.

If yous await at below example, in that place is entirely 1 static method called printDuplicateCharacters(), which does both this job. We get-go got the grapheme array from String past times calling toCharArray().

Next nosotros are using HashMap to shop characters together with their count. We use containsKey() method to depository fiscal establishment tally if key, which is a grapheme already exists or not, if already exists nosotros larn the former count from HashMap by calling get() method together with shop it dorsum subsequently incrementing it past times 1.

loop through Map together with depository fiscal establishment tally each entry, if count, which is the value of Entry is greater than 1, together with therefore that grapheme has occurred to a greater extent than than once. You tin directly impress duplicate characters or create whatever yous desire amongst them.

import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set;  /** * Java Program to honour duplicate characters inwards String. * * * @author http://java67.blogspot.com */ public class FindDuplicateCharacters{      public static void main(String args[]) {         printDuplicateCharacters("Programming");         printDuplicateCharacters("Combination");         printDuplicateCharacters("Java");     }      /*      * Find all duplicate characters inwards a String together with impress each of them.      */     public static void printDuplicateCharacters(String word) {         char[] characters = word.toCharArray();          // construct HashMap amongst grapheme together with set out of times they look inwards String         Map<Character, Integer> charMap = new HashMap<Character, Integer>();         for (Character ch : characters) {             if (charMap.containsKey(ch)) {                 charMap.put(ch, charMap.get(ch) + 1);             } else {                 charMap.put(ch, 1);             }         }          // Iterate through HashMap to impress all duplicate characters of String         Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();         System.out.printf("List of duplicate characters inwards String '%s' %n", word);         for (Map.Entry<Character, Integer> entry : entrySet) {             if (entry.getValue() > 1) {                 System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());             }         }     }  }  Output List of duplicate characters inwards String 'Programming' g : 2 r : 2 1000 : 2 List of duplicate characters inwards String 'Combination' n : 2 o : 2 i : 2 List of duplicate characters inwards String 'Java'


That's all on how to honour duplicate characters inwards a String. Next fourth dimension if this interrogation is asked to yous inwards a programming undertaking interview, yous tin confidently write a solution together with tin explicate them. Remember this interrogation is too asked equally write a Java plan to honour repeated characters of a given String, therefore don't larn confused yourself inwards wording, the algorithm volition stay same.

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

Wednesday, December 11, 2019

Top 21 Oftentimes Asked Coffee Interview Questions Answers

If yous convey been to couplet of Java interviews hence yous know that at that spot are roughly questions which choke on repeating e.g. difference betwixt == as well as equals() method and may of it's pop cousins similar HashMap vs Hashtable, ArrayList vs LinkedList, departure betwixt equals() as well as hashCode(), or departure betwixt Comparator as well as Comparable inward Java. I telephone telephone them often asked Java interview questions, as well as I propose every Java developer to brand a listing of them for their ain reference as well as revision. I am certain many Java programmer already has such listing of questions handy, if non this is a expert fourth dimension to honor as well as brand your ain list. These are the questions which yous precisely can't afford to miss, especially at freshers level. They seem at diverse phase of Java interviews. Most probable yous volition run across them on telephonic round, where Interviewer precisely desire to filter candidates betwixt who knows Java as well as who doesn't.

Good matter close them is that they are hence mutual that everyone knows close it. Though for freshers it could hold out picayune difficult. but equally your sense grows these often asked questions acquire much easier to answer.

Some programmers besides prefer to collect often asked Java questions based upon topics e.g. mutual questions from threads, strings, collections and other pop Java interview topics, roughly of them are already shared yesteryear me. In this list, I am sharing roughly of the most often asked questions from Java interviews.

By the way, when yous hold off the list, yous volition run across roughly of the classics are missing e.g. difference betwixt String as well as StringBuffer, but at that spot are many similar that, as well as that is job for yous to collect equally many equally possible as well as choke on them handy to avoid searching from them precisely earlier interview. I volition besides add together roughly to a greater extent than questions on this listing but for straightaway let's start alongside these 21 questions.




Frequently Asked Core Java Question as well as Answer

 If yous convey been to couplet of Java interviews hence yous know that at that spot are roughly questions Top 21 Frequently Asked Java Interview Questions AnswersHere is my listing of roughly of the most mutual questions from Java interviews. You volition mostly run across these questions on telephonic circular of your interview, but it is besides asked a lot of fourth dimension during confront to confront interviews. It's non express to whatever particular fellowship equally well, inward fact all major information technology companies inward Republic of Republic of India e.g. TCS, CTS, Infosys, Tech Mahindra, HCL, Oracle Financial Services, as well as major investment banks similar Barclays Capital, Morgan Stanley, Goldman Sachs, Credit Suisse asked these form of fact based query on their Java recruitment drives. By the way, roughly questions are actually easy, as well as roughly are existent tough, hence it's mixed of both, but 1 matter is common, they are the most often asked questions from Java interviews.


1)  How Java achieves platform independence?
Answer : When nosotros country Java is platform independent which agency Java programs are non theme on whatever platform, architecture or operating organization similar windows or Linux. Java arrive at this yesteryear using Java virtual machine, when Java programs are compiled they are converted to .class file which is collection of byte code as well as straight understandable  by JVM. So the same Java plan tin dismiss run on whatever operating organization alone JVM tin dismiss differ according to OS but all JVM tin dismiss sympathize converted byte code that's how Java arrive at platform independence. For a to a greater extent than detailed reply of this question, run across here.


2)  What is ClassLoader inward Java?
Answer : This was 1 of advanced query few years ago, but inward bridge of 2 to 3 years, this has acquire really common. When a Java plan is converted into .class file yesteryear Java compiler  which is collection of byte code  class loader is responsible to charge that degree file from file system,network or whatever other location. This degree loader is nix but besides a degree from which place they are loading the degree according to that degree loaders are 3 types :
  1.Bootstrap
  2.Extension
  3.System degree loader .
to larn to a greater extent than classloaders inward Java, run across my article how classloader industrial plant inward Java.


3)  Write a Java plan to depository fiscal establishment check if a pose out is Even or Odd?
Answer : This query is non especially related to Java as well as besides asked on other programming interviews e.g. C, C++ or C#. I convey included this inward my listing of often asked questions from Java interviews because I convey seen it to a greater extent than often than not.

import java.util.Scanner;  class TestEvenOdd {  public static void main(String arg[]){    int num;    //Read a number    Scanner input = new Scanner(System.in);    System.out.println("Enter a pose out to depository fiscal establishment check its Even or Odd");    num = input.nextInt();    // Conditional operator    System.out.println((num%2)==0 ? "even number":"odd number");   } }


4)  Difference betwixt ArrayList as well as HashSet inward Java?
Answer : If I country that this is 1 of the most most often asked query to Java programmers, hence it would non hold out wrong. Along alongside questions similar ArrayList vs LinkedList as well as ArrayList vs Vector, this query is most mutual on diverse Java interviews. Here are roughly of import differences betwixt these 2 classes :

  1. ArrayList implements List interface piece HashSet implements Set interface inward Java.
  2. ArrayList is an ordered collection as well as maintains insertion lodge of elements piece HashSet is an unordered collection as well as doesn't hold whatever order.
  3. ArrayList allow duplicates piece HashSet doesn't allow duplicates.
  4. ArrayList is backed yesteryear an Array piece HashSet is backed yesteryear an HashMap instance.
  5. One to a greater extent than departure betwixt HashSet as well as ArrayList is that its index based yous tin dismiss think object yesteryear calling get(index) or withdraw objects yesteryear calling remove(index) piece HashSet is completely object based. HashSet besides doesn't render get() method.



5)  What is double checked locking inward Singleton?
Answer : Interviewer volition never halt quest this question. It's woman nurture of all often asked query inward Java. Singleton agency nosotros tin dismiss exercise alone 1 instance of that class,in term of singleton DCL is the way to  ensure that at whatever toll alone  one instance is created inward multi-threaded surroundings its possible that simultaneously 2 thread trying to exercise instance of singleton degree inward that province of affairs nosotros cant certain that alone 1 instance is created hence avoid this province of affairs using double checked locking yesteryear using synchronized block where nosotros creating the object.

Code Example :
class SingletonClass {   private DCL dcl = null;   public DCL getDCL() {     if (dcl == null) {       synchronized {         if (dcl == null)           dcl = new DCL();       }     }     return dcl;   } }
To larn to a greater extent than close why double checked locking was broken earlier Java 1.5, run across this article.

6)  How exercise yous exercise thread-safe Singleton inward Java?
Answer : This is usually follow-up of previous Java question. There are to a greater extent than than 1 ways to exercise it. You tin dismiss  create thread security Singleton degree inward Java yesteryear creating the 1 as well as alone instance during degree loading. static fields are initialized during degree loading as well as Classloader volition guarantee that instance volition non hold out visible until its fully created.


7)  When to utilisation volatile variable inward Java?
Answer : Volatile keyword is used alongside alone variable  in Java as well as it guarantees that value of volatile variable volition ever hold out read from principal retentiveness as well as non from Thread's local cache. So nosotros tin dismiss utilisation volatile to arrive at synchronization because its guaranteed that all reader thread volition run across updated value of volatile variable 1 time write performance completed, without volatile keyword dissimilar reader thread may run across dissimilar values. Volatile modifier besides helps to preclude reordering of code yesteryear compiler as well as offering visibility guarantee yesteryear happens-before relationship. See this article to larn to a greater extent than close volatile inward Java.


8)  When to utilisation transient variable inward Java?
Answer : Transient inward Java is  used to betoken that the variable should non hold out serialized. Serialization is a procedure of saving an object's land inward Java. When nosotros desire to persist as well as object's land yesteryear default all instance variables inward the object is stored. In roughly cases, if yous desire to avoid persisting roughly variables because nosotros don’t convey the necessity to transfer across the network. So, declare those variables equally transient. If the variable is declared equally transient, hence it volition non hold out persisted. This is the principal purpose of the transient keyword, to larn to a greater extent than close transient variable inward Java, run across this tutorial.


9)  Difference betwixt transient as well as volatile variable inward Java?
Answer : This is 1 time again follow-up of previous 2 Java questions. You volition run across this query on laissez passer on 10 on whatever listing of Java often asked question. Here are roughly of the of import departure betwixt them.
Transient variable : transient keyword is used alongside those instance variable which volition non participate inward serialization process.we cannot utilisation static alongside transient variable equally they are purpose of instance variable.
Volatile variable : volatile keyword is used alongside alone variable  in Java as well as it guarantees that value of volatile variable volition ever hold out read from principal retentiveness as well as non from Thread's local cache, it tin dismiss hold out static.
to larn to a greater extent than differences as well as reply this query inward detail, run across here.


10) Difference betwixt Serializable as well as Externalizable inward Java?
Answer : If I country this is 1 of the most often asked Java query on both face-to-face as well as telephonic interview hence it would hold out an exaggeration. Serialization is a default procedure of  serializing or persisting  any object's land inward Java. It's triggered yesteryear implementing Serializable interface which is a mark interface (an interface without whatever method). While Externalizable is used to customize as well as command default serialization procedure which is implemented yesteryear application. Main departure betwixt these 2 is that Externalizable interface provides consummate command to the degree implementing the interface whereas Serializable interface unremarkably uses default implementation to grip the object serialization process.
Externalizable interface has 2 method writeExternal(ObjectOutput) as well as readExternal(ObjectInput) method which are used to grip customized object serialize procedure as well as inward damage of performance its expert because everything is nether control. to larn to a greater extent than close this classical question, run across this answer equally well.


11) Can nosotros override somebody method inward Java?
Answer : No, nosotros cannot override somebody methods inward Java equally if nosotros declare whatever variable ,method equally somebody that variable or method volition hold out visible for that degree alone as well as besides if nosotros declare whatever method equally somebody than they are bonded alongside degree at compile fourth dimension non inward run fourth dimension hence nosotros cant reference those method using whatever object hence nosotros cannot override somebody method inward Java.


12) Difference betwixt Hashtable as well as HashMap inward Java?
Answer : This is roughly other often asked query from Java interview. Main departure betwixt HaspMap as well as Hashtable are next :

  • HashMap allows zero values equally fundamental as well as value whereas Hashtable doesn't allow nulls.
  • Hashtable is thread-safe as well as tin dismiss hold out shared betwixt multiple threads whereas HashMap cannot hold out shared betwixt multiple threads without proper synchronization.
  • Because of synchronization, Hashtable is considerably slower than HashMap, fifty-fifty inward illustration of unmarried threaded application.
  • Hashtable is a legacy class, which was previously implemented Dictionary interface. It was afterwards retrofitted into Collection framework yesteryear implementing Map interface. On the other hand, HashMap was purpose of framework from it's inception.
  • You tin dismiss besides brand your HashMap thread-safe yesteryear using Collections.synchronizedMap() method. It's performance is similar to Hashtable.
See hither to larn to a greater extent than as well as sympathize when to utilisation Hashtable as well as HashMap inward Java. 



13) Difference betwixt List as well as Set inward Java?
Answer : One to a greater extent than classic often asked question. List as well as laid both are really useful interfaces of  collections inward Java as well as  difference betwixt these 2 is listing allows duplicate chemical cistron but laid don't allows duplicate elements roughly other departure is listing hold the insertion lodge of chemical cistron but laid is unordered collection .list tin dismiss convey many zero objects but laid permit alone 1 zero element. This query is roughly fourth dimension besides asked equally departure betwixt Map, List as well as Set to arrive to a greater extent than comprehensive equally those 3 are major information construction from Java's Collection framework. To reply that query run across this article.


14) Difference betwixt ArrayList as well as Vector inward Java
Answer : One to a greater extent than favourite of Java Interviewers, at that spot is hardly whatever interview of junior Java developers, on which this query doesn't appear. In 4 as well as v circular of interview, yous volition definitely going to run across this query inward roughly dot of time. Vector as well as ArrayList both implement the listing interface but principal departure betwixt these 2 is vector is synchronized as well as thread security but listing is non because of this listing is faster than vector.


15) Difference betwixt Hashtable as well as ConcurrentHashMap inward Java?
Answer : Both Hashtable as well as ConcurrentHashMap is used inward multi-threaded surroundings because both are therad-safe but principal departure is on performance Hashtable's performance acquire wretched if the size of Hashtable acquire large because it volition hold out locked for long fourth dimension during iteration but inward illustration of concurrent HaspMap  only specific purpose is locked because concurrent HaspMap industrial plant on sectionalisation as well as other thread tin dismiss access the chemical cistron without iteration to complete. To larn to a greater extent than close how ConcurrentHashMap achieves it's thread-safety, scalability using lock stripping as well as non blocking algorithm, run across this article equally well.


16) Which 2 methods yous volition override for an Object to hold out used equally Key inward HashMap?
Answer : equals() as well as hashCode() methods needs to hold out override for an object to hold out used equally fundamental inward HaspMap. In Map objects are stored equally fundamental as well as value.  put(key ,value) method is used to shop objects inward HashMap at this fourth dimension hashCode() method is used to calculate the hash-code of fundamental object as well as both fundamental as well as value object is stored equally map.entry.if 2 fundamental objects convey same hash-code hence alone value object is stored inward that same bucket place but equally a linked listing value is stored as well as if hash code is dissimilar hence roughly other bucket place is created. While retrieving get(key) method is used at this fourth dimension hash code of fundamental object is calculated as well as hence equals() method is called to compare value object. to larn to a greater extent than close how get() method of HashMap or Hashtable works, run across that article.


17) Difference betwixt hold off as well as slumber inward Java?
Answer:  Here are roughly of import differences betwixt hold off as well as slumber inward Java

  1. wait() method free the lock when thread is waiting but sleep() method concur the lock when thread is waiting.
  2. wait() is a instance method as well as slumber is a static method .
  3. wait method is ever called from synchronized block or method but for slumber at that spot is no such requirement.
  4. waiting thread tin dismiss hold out awake yesteryear calling notify() as well as notifyAll() piece sleeping thread tin dismiss non hold out awaken yesteryear calling notify method.
  5. wait method is status based piece sleep() method doesn't require whatever condition. It is precisely used to pose electrical current thread on sleep.
  6. wait() is defined inward java.lang.Object degree piece sleep() is defined inward java.lang.Thread class


18) Difference betwixt notify as well as notifyAll inward Java?
Answer : principal departure betwixt notify as well as notifyAll is notify method volition wake upwards  or notify alone 1 thread as well as notifyall volition notify all threads. If yous are certain that to a greater extent than than 1 thread is waiting on monitor as well as yous desire all of them to give equal lead chances to compete for CPU, utilisation notifyAll method. See here to a greater extent than differences betwixt notify vs notifyAll.


19) What is charge cistron of HashMap means?
Answer : HashMap's performance depends on 2 things offset initial capacity as well as minute charge cistron whenever nosotros exercise HashMap initial capacity pose out of bucket is created initially as well as charge cistron is criteria to determine when nosotros convey to increase the size of HashMap when its close to acquire full.


20) Difference betwixt PATH as well as Classpath inward Java?
Answer : PATH is a surroundings variable inward Java which is used to assist Java plan to compile as well as run.To laid the PATH variable nosotros convey to include JDK_HOME/bin directory inward PATH surroundings variable as well as besides nosotros cannot override this variable. On the other hand,  ClassPath variable is used yesteryear degree loader to locate as well as charge compiled Java codes stored inward .class file. We tin dismiss laid classpath nosotros demand to include all those directory where nosotros convey pose either our .class file or JAR file which is required yesteryear your Java application,also nosotros tin dismiss override this surroundings variable.


21) Difference betwixt extends Thread as well as implements Runnable inward Java
This is the 21st often asked query inward my list. You volition run across this query equally offset or minute on multi-threading topic. One of the principal dot to pose across piece answering this query is Java's multiple inheritance support. You cannot to a greater extent than than 1 class, but yous tin dismiss implement to a greater extent than than 1 interface. If yous extend Thread degree precisely to override run() method, yous lose might of extending roughly other class, piece inward illustration of Runnable, yous tin dismiss yet implement roughly other interface or roughly other class. One to a greater extent than departure is that Thread is abstraction of independent path of execution, piece Runnable is abstraction of independent task, which tin dismiss hold out executed yesteryear whatever thread. That's why it's ameliorate to implement Runnable than extending Thread degree inward Java. If yous similar to dig more, run across this answer.


That's all on this list of xx most often asked Java interview questions as well as answers. By the way, this is non precisely the alone listing yous got here, I convey shared a lot of interview questions on subject wise e.g. yous tin dismiss honor often asked questions from Thread, Collections, Strings as well as other of import Java classes. Apart from coding questions, these fact based Java programming linguistic communication questions are really of import to exercise good on whatever interview. It's fifty-fifty to a greater extent than of import for freshers as well as less experienced developer because they are usually asked these questions to a greater extent than often than experienced developers. By the way, yous are most welcome to contribute inward this list.