Thursday, 12 March 2020

How to remove duplicate rows from a table in SQL

There are a couple of ways to remove duplicate rows from a table in SQL e.g. you can use a temp tables or a window function like row_number() to generate artificial ranking and remove the duplicates. By using a temp table, you can first copy all unique records into a temp table and then delete all data from the original table and then copy unique records again to the original table. This way, all duplicate rows will be removed, but with large tables, this solution will require additional space of the same magnitude of the original table. The second approach doesn't require extra space as it removes duplicate rows directly from the table. It uses a ranking function like row_number() to assign a row number to each row.

By using partition by clause you can reset the row numbers on a particular column. In this approach, all unique rows will have row number = 1 and duplicate row will have row_number > 1, which gives you an easy option to remove those duplicate rows. You can do that by using a common table expression (see T-SQL Fundamentals) or without it on Microsoft SQL Server.

No doubt that SQL queries are the integral part of any programming job interview which requires database and SQL knowledge. The queries are also very interesting to check candidate's logical reasoning ability.

Earlier, I have shared a list of frequently asked SQL queries from interviews and this article is an extension of that. I have shared lot of good SQL based problem on that article and users have also shared some excellent problems in the comments, which you should look.

Btw, this is the follow-up question of another popular SQL interview question, how do you find duplicate records in a table, which we have discussed earlier. This is an interesting question because many candidates confuse themselves easily.

Some candidate says that they will find duplicate by using group by and printing name which has counted more than 1, but when it comes to deleting this approach doesn't work, because if you delete using this logic both duplicate and unique row will get deleted.

This little bit of extra detail e.g. row_number makes this problem challenging for many programmers who don't use SQL on a daily basis. Now, let's see our solution to delete duplicate rows from a table in SQL Server.

Setup

Before exploring a solution, let's first create the table and populate with test data to understand both problem and solution better. I am using a temp table to avoid leaving test data into the database once we are done. Since temp tables are cleaned up once you close the connection to the database, they are best suited for testing.

In our table, I have just one column for simplicity, if you have multiple columns then the definition of duplicate depends whether all columns should be equal or some key columns e.g. name and city can be same for two unique persons. In such cases, you need to extend the solution by using those columns on key places e.g. on a distinct clause in the first solution and on the partition by in second solution.

Anyway, here is our temp table with test data, it is carefully constructed to have duplicates, you can see that C++ is repeated thrice while Java is repeated twice in the table.

-- create a temp table for testing
create table #programming (name varchar(10));

-- insert data with duplicate, C++ is repeated 3 times, while Java 2 times
insert into #programming values ('Java');
insert into #programming values ('C++');
insert into #programming values ('JavaScript');
insert into #programming values ('Python');
insert into #programming values ('C++');
insert into #programming values ('Java');
insert into #programming values ('C++');

-- cleanup
drop table #programming

Solution 1 - Use temp table

Yes, this is the most simple but logical way to remove duplicate elements from a table and it will work across database e.g. MySQL, Oracle or SQL Server. The idea is to copy unique rows into a temp table. You can find unique rows by using distinct clause. Once unique rows are copied, delete everything from the original table and then copy unique rows again. This way, all the duplicate rows have been removed as shown below.

-- removing duplicate using copy, delete and copy
select distinct name into #unique from #programming
delete from #programming;
insert into #programming select * from #unique

-- check after
select * from #programming

name
Java
C++
JavaScript
Python

You can see the duplicate occurrences of Java and C++ have been removed from the #programming temp table. This is by far the simplest solution and also quite easy to understand but it doesn't come to your mind without practicing. I suggest solving some SQL puzzles from Joe Celko's classic book, SQL Puzzles and Answers, Second Edition to develop your SQL sense. It's a great practice book to learn and master SQL logic.

How to remove duplicate rows from a table in SQL Server



Solution 2 - Using row_number() and derived table

The row_number() is one of several ranking functions provided by SQL Server, It also exists in Oracle database. You can use this function provide ranking to rows. You can further use partition by to tell SQL server that what would be the window. This way row number will restart as soon as a different name comes up but for the same name, all rows will get sequential numbers e.g. 1, 2, 3 etc. Now, it's easy to spot the duplicates in the derived table as shown in the following example:

select * from (select *, row_number() OVER ( partition by name order by name) as rn from #programming) dups 
name rn
C++ 1
C++ 2
C++ 3
Java 1
Java 2
JavaScript 1
Python 1

Now, you can remove all the duplicates which are nothing but rows with rn > 1 , as done by following SQL query:

delete dups 
from (select *, row_number() OVER ( partition by name order by name) as rn from #programming) 
dups 
WHERE rn > 1

(3 row(s) affected)

now, if you check the #programming table again there won't be any duplicates.

select * from #programming
name
Java
C++
JavaScript
Python

Here is a nice summary of all three ways to remove duplicates from a  table using SQL:

How to remove duplicate rows of  table in SQL


Solution 3 - using CTE

The CTE stands for common table expression, which is similar to derived table and used to the temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. Similar to derived table, CTE is also not stored as an object and lasts only for the duration of the query. You can rewrite the previous solution using CTE as shown below:

;with cte
as (select row_number() over (partition by name order by(select 0)) rn
from #programming)
delete from cte where rn > 1

The logic is exactly similar to the previous example and I am using select 0 because it's arbitrary which rows to preserve in the event of a tie as both contents same data. If you are new to CTE then I suggest reading T-SQL Fundamentals, one of the best books to learn SQL Server fundamentals.


That's all about how to remove duplicate rows from a table in SQL. As I said, this is one of the frequently asked SQL queries, so be prepare for that when you go for your programming job interview. I have tested the query in SQL Server 2008 and they work fine and you might need to tweak them a little bit depending upon the database you are going to use e.g. MySQL, Oracle or PostgreSQL. Feel free to post, if you face any issue while removing duplicates in Oracle, MySQL or any other database.


Other Frequently asked SQL queries from Interviews
  • How to find the 2nd highest salary of an employee in SQL? (answer)
  • How to join three tables in one SQL query? (solution)
  • How to find all table names in a database? (query)
  • How do you create backup of table or copy of table using SQL? (answer)
  • How do you find all customers who have never ordered? (solution)
  • Can you write pagination query for Oracle using row_number? (query)
  • How do you find Nth highest salary of an employee using the correlated query? (solution)
  • SQL Puzzles and Answers by Joe Celko (read)

10 Examples to read a text file in Java

The Java IO API provides two kinds of interfaces for reading files, streams and readers. The streams are used to read binary data and readers to read character data. Since a text file is full of characters, you should be using a Reader implementations to read it. There are several ways to read a plain text file in Java e.g. you can use FileReaderBufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability. You can also use both BufferedReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file.

The JDK 7 also introduces a couple of nice utility e.g. Files class and try-with-resourceconstruct which made reading a text file, even more, easier.

In this article, I am going to share a couple of examples of reading a text file in Java with their pros, cons, and important points about each approach. This will give you enough detail to choose the right tool for the job depending on the size of file, content of the file and how you want to read.


Reading a text file using FileReader

The FileReader is your general purpose Reader implementation to read a file. It accepts a String path to file or a java.io.File instance to start reading. It also provides a couple of overloaded read() methods to read a character, or read characters into an array or into a CharBuffer object. Here is an example of reading a text file using FileReader in Java:

public static void readTextFileUsingFileReader(String fileName) {
    try {
      FileReader textFileReader = new FileReader(fileName);
      char[] buffer = new char[8096];
      int numberOfCharsRead = textFileReader.read(buffer);
      while (numberOfCharsRead != -1) {
        System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));
        numberOfCharsRead = textFileReader.read(buffer);
      }
      textFileReader.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

Output
Once upon a time, we wrote a program to read data from a text file.
The program failed to read a large file but then Java 8 come to
rescue, which made reading file lazily using Streams. 

You can see that instead of reading one character at a time, I am reading characters into an array. This is more efficient because read() will access the file several times but read(char[]) will access the file just one time to read the same amount of data.

I am using an 8KB of the buffer, so in one call I am limited to read that much data only. You can have a bigger or smaller buffer depending upon your heap memory and file size. You should also notice that I am looping until read(char[]) returns -1 which signal the end of the file.

Another interesting thing to note is to call to String.valueOf(buffer, 0, numberOfCharsRead), which is required because you might not have 8KB of data in the file or even with a bigger file, the last call may not able to fill the char array and it could contain dirty data from the last read.


Reading a text file in Java using BufferedReader

The BufferedReader class is a Decorator which provides buffering functionality to FileReader or any other Reader. This class buffer input from source e.g. files into memory for efficient read. In the case of BufferedReader, the call to read() doesn't always goes to file if it can find the data in the internal buffer of BufferedReader.

The default size of the internal buffer is 8KB which is good enough for the most purpose, but you can also increase or decrease buffer size while creating BufferedReader object. The reading code is similar to the previous example.

public static void readTextFileUsingBufferdReader(String fileName) {
    try {
      FileReader textFileReader = new FileReader(fileName);
      BufferedReader bufReader = new BufferedReader(textFileReader);

      char[] buffer = new char[8096];

      int numberOfCharsRead = bufReader.read(buffer); // read will be from
      // memory
      while (numberOfCharsRead != -1) {
        System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));
        numberOfCharsRead = textFileReader.read(buffer);
      }

      bufReader.close();

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

Output
[From File] Java provides several ways to read file

In this example as well, I am reading the content of the file into an array. Instead of reading one character at a time, this is more efficient. The only difference between the previous examples and this one is that the read() method of BufferedReader is faster than read() method of FileReader because read can happen from memory itself.

In order to read the full-text file, you loop until read(char[]) method returns -1, which signals the end of the file. See Core Java Volume 1 - Fundamentals to learn more about how BufferedReader class works in Java.

How to read a text file in Java




Reading a text file in Java using Scanner

The third tool or class to read a text file in Java is the Scanner, which was added on JDK 1.5 release. The other two FileReader and BufferedReader are present from JDK 1.0 and JDK 1.1 version. The Scanner is much more feature rich and versatile class. It does not just provide reading but parsing of data as well. You can not only read text data but you can also read text as number or float using nextInt() and nextFloat() methods.

The class uses regular expression pattern to determine token, which could be tricky for newcomers. The two main method to read text data from Scanner is next() and nextLine(), former one read words separated by space while later one can be used to read a text file line by line in Java. In most cases, you would use the nextLine() method as shown below:

public static void readTextFileUsingScanner(String fileName) {
    try {
      Scanner sc = new Scanner(new File(fileName));
      while (sc.hasNext()) {
        String str = sc.nextLine();
        System.out.println(str);
      }
      sc.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Output
[From File] Java provides several ways to read the file.

You can use the hasNext() method to determine if there is any more token left to read in the file and loop until it returns false. Though you should remember that next() or nextLine()may block until data is available even if hasNext() return true. This code is reading the content of "file.txt" line by line. See this tutorial to learn more about Scanner class and file reading in Java.

Reading a text file using Stream in Java 8

The JDK 8 release has brought some cool new features e.g. lambda expression and streamswhich make file reading even smoother in Java. Since streams are lazy, you can use them to read only lines you want from the file e.g. you can read all non-empty lines by filtering empty lines. The use of method reference also makes the file reading code much more simple and concise, so much so that you can read a file in just one line as shown below:

Files.lines(Paths.get("newfile.txt")).forEach(System.out::println);

Output
This is the first line of file

something is better than nothing

this is the last line of the file

Now, if you want to do some pre-processing, here is code to trim each line, filter empty lines to only read non-empty ones, and remember, this is lazy because Files.lines() method return a stream of String and Streams are lazy in JDK 8 (see Java 8 in Action).

Files.lines(new File("newfile.txt").toPath())
.map(s -> s.trim()) 
.filter(s -> !s.isEmpty()) 
.forEach(System.out::println);


We'll use this code to read a file which contains a line which is full of whitespace and an empty line, the same one which we have used in the previous example, but this time, output will not contain 5 line but just three lines because empty lines are already filtered, as shown below:

Output
This is the first line of file
something is better than nothing
this is the last line of the file

You can see only three out of five lines appeared because other two got filtered. This is just tip of the iceberg on what you can do with Java SE 8, See Java SE 8 for Really Impatient  to learn more about Java 8 features.

Reading text file in Java 8 example



How to read a text file as String in Java

Sometimes you to read the full content of a text file as String in Java. This is mostly the case with small text files as for large file you will face java.lang.OutOfMemoryError: java heap spaceerror. Prior to Java 7, this requires a lot of boiler code because you need to use a BufferedReader to read a text file line by line and then add all those lines into a StringBuilder and finally return the String generated from that.

Now you don't need to do all that, you can use the Files.readAllBytes() method to read all bytes of the file in one shot. Once done that you can convert that byte array into String. as shown in the following example:

public static String readFileAsString(String fileName) {
    String data = "";
    try {
      data = new String(Files.readAllBytes(Paths.get("file.txt")));
    } catch (IOException e) {
      e.printStackTrace();
    }

    return data;
  }
Output
[From File] Java provides several ways to read file

This was a rather small file so it was pretty easy. Though, while using readAllBytes() you should remember character encoding. If your file is not in platform's default character encodingthen you must specify the character doing explicitly both while reading and converting to String. Use the overloaded version of readAllBytes() which accepts character encoding. You can also see how I read XML as String in Java here.

Reading the whole file in a List

Similar to the last example, sometimes you need all lines of the text file into an ArrayList or Vector or simply on a List. Prior to Java 7, this task also involves boilerplate e.g. reading file line by line, adding them into a list and finally returning the list to the caller, but after Java 7, it's very simple now. You just need to use the Files.readAllLines() method, which return all lines of the text file into a List, as shown below:

public static List<String> readFileInList(String fileName) {
    List<String> lines = Collections.emptyList();
    try {
      lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return lines;
}

Similar to the last example, you should specify character encoding if it's different than platform's default encoding. You can use see I have specified UTF-8 here. Again, use this trick only if you know that file is small and you have enough memory to hold a List containing all line of the text file, otherwise your Java program will crash with OutOfMemoryError.

10 Examples to read text file in Java




How to read a text file in Java into an array

This example is also very similar to last two example, this time, we are reading contents of the file into a String array. I have used a shortcut here, first, I have read all the lines as List and then converted the list to array. This result in simple and elegant code, but you can also read data into character array as shown in the first example. Use the read(char[] data) method while reading data into a character array.

Here is an example of reading a text file into String array in Java:

public static String[] readFileIntoArray(String fileName) {
    List<String> list = readFileInList(fileName);
    return list.toArray(new String[list.size()]);
}

This method leverage our existing method which read the file into a List and the code here is only to convert a list to array in Java.


How to read a file line by line in Java

This is one of the interesting examples of reading a text file in Java. You often need file data as line by line. Fortunately, both BufferedReader and Scanner provides convenient utility method to read line by line. If you are using BufferedReader then you can use readLine() and if you are using Scanner then you can use nextLine() to read file contents line by line. In our example, I have used BufferedReader as shown below:

public static void readFileLineByLine(String fileName) {
    try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
      String line = br.readLine();
      while (line != null) {
        System.out.println(line);
        line = br.readLine();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

Just remember that A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

How to read a file line by line in Java


Java Program to read a text file in Java

Here is the complete Java program to read a plain text file in Java. You can run this program in Eclipse provided you create the files used in this program e.g. "sample.txt""file.txt", and "newfile.txt". Since I am using a relative path, you must ensure that files are in the classpath. If you are running this program in Eclipse, you can just create these files in the root of the project directory. The program will throw FileNotFoundException or NoSuchFileExcpetion if it is not able to find the files.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

/*
 * Java Program read a text file in multiple way.
 * This program demonstrate how you can use FileReader,
 * BufferedReader, and Scanner to read text file,
 * along with newer utility methods added in JDK 7
 * and 8. 
 */

public class FileReadingDemo {

  public static void main(String[] args) throws Exception {

    // Example 1 - reading a text file using FileReader in Java
    readTextFileUsingFileReader("sample.txt");
    
    // Example 2 - reading a text file in Java using BufferedReader
    readTextFileUsingBufferdReader("file.txt");
    
    // Example 3 - reading a text file in Java using Scanner
    readTextFileUsingScanner("file.txt");
    
    // Example 4 - reading a text file using Stream in Java 8
    Files.lines(Paths.get("newfile.txt")).forEach(System.out::println);    
    
    // Example 5 - filtering empty lines from a file in Java 8
    Files.lines(new File("newfile.txt").toPath())
    .map(s -> s.trim()) 
    .filter(s -> !s.isEmpty()) 
    .forEach(System.out::println);
    
    
    // Example 6 - reading a text file as String in Java
    readFileAsString("file.txt");
    
    
    // Example 7 - reading whole file in a List
    List<String> lines = readFileInList("newfile.txt");
    System.out.println("Total number of lines in file: " + lines.size());
    
    // Example 8 - how to read a text file in java into an array
    String[] arrayOfString = readFileIntoArray("newFile.txt");
    for(String line: arrayOfString){
    System.out.println(line);
    }
    
    // Example 9 - how to read a text file in java line by line
    readFileLineByLine("newFile.txt");
    
    // Example 10 - how to read a text file in java using eclipse
    // all examples you can run in Eclipse, there is nothing special about it. 
    
  }

  public static void readTextFileUsingFileReader(String fileName) {
    try {
      FileReader textFileReader = new FileReader(fileName);
      char[] buffer = new char[8096];
      int numberOfCharsRead = textFileReader.read(buffer);
      while (numberOfCharsRead != -1) {
        System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));
        numberOfCharsRead = textFileReader.read(buffer);
      }
      textFileReader.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public static void readTextFileUsingBufferdReader(String fileName) {
    try {
      FileReader textFileReader = new FileReader(fileName);
      BufferedReader bufReader = new BufferedReader(textFileReader);

      char[] buffer = new char[8096];

      int numberOfCharsRead = bufReader.read(buffer); // read will be from
      // memory
      while (numberOfCharsRead != -1) {
        System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));
        numberOfCharsRead = textFileReader.read(buffer);
      }

      bufReader.close();

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public static void readTextFileUsingScanner(String fileName) {
    try {
      Scanner sc = new Scanner(new File(fileName));
      while (sc.hasNext()) {
        String str = sc.nextLine();
        System.out.println(str);
      }
      sc.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public static String readFileAsString(String fileName) {
    String data = "";
    try {
      data = new String(Files.readAllBytes(Paths.get("file.txt")));
    } catch (IOException e) {
      e.printStackTrace();
    }

    return data;
  }

  public static List<String> readFileInList(String fileName) {
    List<String> lines = Collections.emptyList();
    try {
      lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return lines;
  }

  public static String[] readFileIntoArray(String fileName) {
    List<String> list = readFileInList(fileName);
    return list.toArray(new String[list.size()]);

  }

  public static void readFileLineByLine(String fileName) {
    try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
      String line = br.readLine();
      while (line != null) {
        System.out.println(line);
        line = br.readLine();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

I have not printed the output here because we have already gone through that and discuss in respective examples, but you need Java 8 to compile and run this program. If you are running on Java 7, then just remove the example 4 and 5 which uses Java 8 syntax and features and the program should run fine.


That's all about how to read a text file in Java. We have looked at all major utilities and classes which you can use to read a file in Java e.g. FileReaderBufferedReader, and Scanner. We have also looked at utility methods added on Java NIO 2 on JDK 7 e.g. Files.readAllLines() and Files.readAllBytes() to read the file in List and String respectively. Finally, we have also touched new way of file reading with Java 8 Stream, which provides lazy reading and the useful pre-processing option to filter unnecessary lines.


Other Java File tutorials for beginners
  • How to check if a File is hidden in Java? (solution)
  • How to read an XML file in Java? (guide)
  • How to read an Excel file in Java? (guide)
  • How to read an XML file as String in Java? (example)
  • How to copy non-empty directory in Java? (example)
  • How to read/write from/to RandomAccessFile in Java? (tutorial)
  • How to append text to a File in Java? (solution)
  • How to read a ZIP file in Java? (tutorial)
  • How to read from a Memory Mapped file in Java? (example)

Printing Largest and Smallest of N numbers without using Array in Java

One of the common programming questions is, how do you find the largest and smallest number in N numbers without using arrays in Java? Can you write a program to solve this problem? Well, it's very similar to the problem we have seen before, find the largest and smallest of 3 integers. You can use the same approach and generalize it for N numbers. All you need to do is start with largest as Integer.MIN_VALUE and smallest number as Integer.MAX_VALUE and loop through N numbers. At each iteration, compare the number with the largest and smallest number, if the current number is larger than largest than its a new largest and if the current number is smaller than smallest than its a new smallest number.

Once you finish the iteration, you have the largest and smallest number without using an array. You can also assign the largest number as zero if there is no negative number in your input, but it won't work if the user can enter both negative and positive integers.

To make this program more interactive, you can accept all N numbers from the user from the command line by using Scanner. The user will keep entering an integer number on each iteration and you would be printing the largest and smallest number.

Alternatively, you can get all N numbers in a List and loop through that list to display largest and smallest number.

Java Program to find largest and smallest of N numbers without arrays

Here is our sample program to find the smallest and largest of N integers without using an array. This program handles both positive and negative number, hence largest value is initialized with Integer.MIN_VALUE and smallest number are initialized with Integer.MAX_VALUE.

If you are sure that your input will only be a positive number then you can initialize the largest with zero instead of Integer.MIN_VALUE.  The program is simple, just take input from the user about how many numbers and then uses a for loop to get that many numbers as input by using Scanner.nextInt() method.

At the same time, we also keep comparing the largest and smallest numbers with the value entered by the user, so that at the end of the loop we have the largest and smallest number from the set of values entered by users.

Btw, if you are preparing coding problems for interviews, to get your first job or looking for a new job, you should check out the Cracking the Code Interview, it contains around 190 programming questions and their solution from various tech interviews. It will give you both common questions and experience on how to solve them.

How to find Largest and Smallest of N numbers without using Array in Java



Program to print largest and smallest of N numbers
import java.util.Scanner;

/*
 * Java Program to find the largest and smallest of N numbers
 * without using arrays. 
 */

public class LargestOfN {

  public static void main(String[] args) {

    System.out.println("Welcome to Java Program to find "
        + "largest and smallest number without using array");
    
    System.out.println("Please enter value of N: ");

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int largest = Integer.MIN_VALUE;
    int smallest = Integer.MAX_VALUE;

    System.out.printf("Please enter %d numbers %n", n);
    for (int i = 0; i < n; i++) {

      int current = sc.nextInt();
      if (current > largest) {
        largest = current;
      } 
      if (current < smallest) {
        smallest = current;

      }
    }

    System.out.println("largest of N number is : " + largest);
    System.out.println("smallest of N number is : " + smallest);
  }

}

You can see that our program has correctly printed the largest and smallest number from the 10 numbers entered by the user. You can also run this program and further check with 20, 30 or any value of N. You can also enter negative numbers to verify if its is calculating largest and smallest correctly with negative values or not.

That's all about how to calculate largest and smallest value in N numbers without using arrays. It's an interesting exercise and teaches you how to use the if-else statements to solve the problem. If you are a beginner programmer and doing these exercise to build your code sense and programming logic, you can also check out following problems for further practice.


Some more array based coding problems for Programmers
  • How to find the missing number in an array of 1 to 100? (solution)
  • How to find duplicate numbers on  integer array? (solution)
  • How to find largest and smallest number in the unsorted array? (solution)
  • How to reverse an array in place in Java? (solution)
  • How to find all pairs in integer array whose sum is equal to given number? (solution)
  • How to find duplicates if an array contains multiple duplicate elements? (solution)
  • How to remove duplicate elements from the array in Java? (solution)
  • How to find the top two numbers from an int array? (solution)
  • How to remove duplicate elements from the array in place? (solution)
  • How to sort an array using Quicksort algorithm? (solution)