Skip to main content

Posts

Showing posts from April, 2020

File copy

Write a program to copy a file a.txt to another file b.txt   In Java, IO is handled with IO streams. There are three types of streams - characters stream, byte stream and buffered stream. Byte stream is used for raw binary data. This stream reads and writes one byte at a time. If you need to read characters, you should use a character stream. A buffered stream reads multiple lines at a time and hence is more efficient. In this example we are using a FileInputStream for reading the file and  FileOutputStream for writing to a file. We read one byte at a time and write it back to the output file. Note the use of finally which ensures that we safely close both streams. File operations throw IOException if there is an error in opening/reading/writing. Instead of handling the exception, we are just throwing it. End of file :  When we reach the end of file, read() method returns a -1. -1 is the end of file character. So we continue reading the bytes until a -1 i...

Only digits

Write a program to find out if the string contains only digits. The long method would be to scan the string and determine whether each character is a digit.  The short but not so good method would be to convert this string to Integer object. If the string has non-digits, the method would throw an exception. The third method is using regular expression. Java String class has a method called matches() which checks for regular expressions.  String s1 = "123"; if (s1.matches("\\d+"){   /*****/ } Here \\d meta character indicates digit. + indicates one or more. So we are saying if the string is composed of 1 or more digits - but nothing else, return true. Here is the complete program to find if the given string contains only digits. import java.util.Scanner ; public class OnlyDigits { public static void main ( String args []) { System . out . println ( "Enter a string:" ); Scanner scanner = ne...

Binary numbers in Java

Write a program to add two binary numbers in Java. Before you start thinking about long binary arithmetic operation, be happy for the fact that Java has inbuilt mechanism for writing binary literals and displaying a number in binary. If we prefix a number with 0b, the number will be treated as binary literal.    e.g. int num1 = 0b1110;/* binary value*/ int num2 = 0b0001; To convert a number to binary - or to display a number in binary, we can use the method toBinaryString() in Integer class.  int a = 10; String st = Integer.toBinaryString(a);/*st is 1010*/ Now we just write a simple program to add two binary literals and display the answer in binary. public class Demo { public static void main ( String args []) { int m = 0 b110011 ; int n = 0 b101100 ; int ans = m + n ; System . out . println ( "The sum of two numbers is " + Integer . toBinaryString ( ans )); } } By the way, do y...

Reverse string using recursion

While we are at it, let us write another recursive function - a function to reverse the characters of a string. Write a recursive function to reverse a string  To reverse a string, we can use this algorithm If the string is not empty return substring of last n-1 characters +first character To reverse the string we need to move the characters from begining of string to end of string. We take the string, some how we reverse last n-1 characters and then add the first character to the end. Let us look at an example of reversing the 5 letter string Hello  Reverse Hello Reverse ello + H reverse llo+e reverse lo+l reverse o+l reverse ""+o The last call just returns the empty string. This returned value is available to previous call. This will return o. Then we go to the previous call of function which will add l to this and return lo. Then we move up the function stack and add l to this lo and return llo. And so on. Here is the code   ...

Recursion - factorial

Write a recursive function to find factorial of a number. According to definition,    n! = n*(n-1)! Yes, the definition is recursive. Which makes our coding easier. Recursive function A function which invokes or calls itself is called a recursive function. Just like the definition given above, you write factorial(n-1) within factorial(int n) function. Now you may wonder, won't this type of function cause an infinite loop? It does, unless you create a base condition in which there is no recursive call. In this example, n = 0 is the base condition. So 0! is 1 and if n is 0 we just return 1. Here is how we have to write our recursive function for factorial. if n >0 return n* factorial(n-1) if n =0 return 1 Wow, so concise! And recursive functions are often deceptively small. Here is our complete function in Java int factorial ( int n ){ if ( n == 0 ) return 1 ; return n * factorial ( n - 1 ); }

First non-repeating character in a string

Write a program to find the first non-repeating character of a string. The easiest solution to this would be to take each character and compare it with rest of the characters. If there is no match, then that is the first non-repeating character. But you realize the problem with this solution, right. It is very in-efficient. It takes n*n iteration. Another solution is - create a hashmap of characters and their frequencies       browse through all characters in the string       if the character is present in map, increment its count       if not present add it to map with count as 1 Next browse through characters of the string again if the count is >1, skip to next character if the count is 1, return that character - we have found our first non-repeating character.  Here is the complete program import java.util.HashMap ; import java.util.Scanner ; public class NonRepeating { char firstNonRepeating (...

Program to capitalize first letter of words

Write a Java program to find the capitalize first letter of each word in a string. This program is quite simple. We split to break the string into words.  Next we take one word at a time, capitalize first letter  by adding capital of first letter concatanated with sub-string of next letters. Now add this to a string buffer. Do not forget to add a space. Here is the complete program import java.util.Scanner ; public class ReverseWords {      String capitalizeFirstLetter ( String st ){ char ch = st . charAt ( 0 ); ch = Character . toUpperCase ( ch ); //first letter to capital String outStr = ch + st . substring ( 1 ); //first letter with substring of remaining return outStr ; }       String wordCapitalize ( String str ){ String arr [] = str . split ( " " ); //split into words StringBuffer buf = new StringBuffer (); for ( String st: arr ){ ...