Monday, September 14, 2015

Java program print prime numbers


This java program prints prime numbers, number of prime numbers required is asked from the user. Remember that smallest prime number is 2.

Java programming code


import java.util.*;
 
class PrimeNumbers
{
 public static void main(String args[])
 {
 int n, status = 1, num = 3;
 
 Scanner in = new Scanner(System.in);
 System.out.println("Enter the number of prime numbers you want");
 n = in.nextInt();
 
 if (n >= 1)
 {
 System.out.println("First "+n+" prime numbers are :-");
 System.out.println(2);
 }
 
 for ( int count = 2 ; count <=n ; )
 {
 for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
 {
 if ( num%j == 0 )
 {
 status = 0;
 break;
 }
 }
 if ( status != 0 )
 {
 System.out.println(num);
 count++;
 }
 status = 1;
 num++;
 } 
 }
}

Output of program:


We have used sqrt method of Math package which find square root of a number. To check if an integer(say n) is prime you can check if it is divisible by any integer from 2 to (n-1) or check from 2 to sqrt(n), first one is less efficient and will take more time.

Thursday, September 10, 2015

Java program to find factorial

This java program finds factorial of a number. Entered number is checked first if its negative then an error message is printed.

Java programming code

import java.util.Scanner;
class Factorial { 
public static void main(String args[]) { 
int n, c, fact = 1;   
System.out.println("Enter an integer to calculate it's factorial"); 
Scanner in = new Scanner(System.in);   
n = in.nextInt();   
if ( n < 0 ) 
System.out.println("Number should be non-negative."); 
else { for ( c = 1 ; c <= n ; c++ ) 
fact = fact*c;   
System.out.println("Factorial of "+n+" is = "+fact); 
} 
} 
}
Output of program:


You can also find factorial using recursion, in the code fact is an integer variable so only factorial of small numbers will be correctly displayed or which fits in 4 bytes. For large numbers you can use long data type.

Java program for calculating factorial of large numbers


Above program does not give correct result for calculating factorial of say 20. Because 20! is a large number and cant be stored in integer data type which is of 4 bytes. To calculate factorial of say hundred we use BigInteger class of java.math package.

import java.util.Scanner; 
import java.math.BigInteger; 
class BigFactorial { 
public static void main(String args[]) { 
int n, c; 
BigInteger inc = new BigInteger("1"); 
BigInteger fact = new BigInteger("1"); 
Scanner input = new Scanner(System.in); 
System.out.println("Input an integer"); 
n = input.nextInt(); 
for (c = 1; c <= n; c++) { 
fact = fact.multiply(inc); 
inc = inc.add(BigInteger.ONE); 
} 
System.out.println(n + "! = " + fact); 
} 
}
We run the above java program to calculate 100 factorial and following output is obtained.
Input an integer
100
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Enhanced for loop java

Enhanced for loop java: Enhanced for loop is useful when scanning the array instead of using for loop. Syntax of enhanced for loop is:

for (data_type variable: array_name)

Here array_name is the name of array.

Java enhanced for loop integer array

class EnhancedForLoop { 
public static void main(String[] args) { 
int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; 
for (int t: primes) { 
System.out.println(t); 
} 
} 
}
Output of program:

Java enhanced for loop strings

class EnhancedForLoop { 
public static void main(String[] args) { 
String languages[] = { "C", "C++", "Java", "Python", "Ruby"}; 
for (String sample: languages) { 
System.out.println(sample); 
} 
} 
}

Wednesday, September 9, 2015

Java program to find largest of three numbers

This java program finds largest of three numbers and then prints it. If the entered numbers are unequal then "numbers are not distinct" is printed.

Java programming source code

import java.util.Scanner;
class LargestOfThreeNumbers { 
public static void main(String args[]) { 
int x, y, z; 
System.out.println("Enter three integers "); 
Scanner in = new Scanner(System.in);   
x = in.nextInt(); 
y = in.nextInt(); 
z = in.nextInt();   
if ( x > y && x > z ) 
System.out.println("First number is largest."); 
else if ( y > x && y > z ) 
System.out.println("Second number is largest."); 
else if ( z > x && z > y ) 
System.out.println("Third number is largest."); 
else System.out.println("Entered numbers are not distinct."); 
} 
}

Output of program:


If you want to find out largest of a list of numbers say 10 integers then using above approach is not easy, instead you can use array data structure.

Tuesday, September 8, 2015

Java program to swap two numbers

This java program swaps two numbers using a temporary variable. To swap numbers without using extra variable see another code below.

Swapping using temporary or third variable


import java.util.Scanner;   
class SwapNumbers { 
public static void main(String args[]) { 
int x, y, temp; 
System.out.println("Enter x and y"); 
Scanner in = new Scanner(System.in);   
x = in.nextInt(); 
y = in.nextInt();   
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);   
temp = x; 
x = y; 
y = temp;   
System.out.println("After Swapping\nx = "+x+"\ny = "+y); 
} 
}
Output of program:


Swapping without temporary variable

import java.util.Scanner;   
class SwapNumbers { 
public static void main(String args[]) { 
int x, y; 
System.out.println("Enter x and y"); 
Scanner in = new Scanner(System.in);   
x = in.nextInt(); 
y = in.nextInt();   
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);   
x = x + y; 
y = x - y; 
x = x - y;   
System.out.println("After Swapping\nx = "+x+"\ny = "+y); 
} 
}
Swapping is frequently used in sorting techniques such as bubble sort, quick sort etc.

Java exception handling tutorial with example programs

In this tutorial we will learn how to handle exception with the help of suitable examples. Exceptions are errors which occur when the program is executing. Consider the Java program below which divides two integers.


import java.util.Scanner;
 
class Division {
 public static void main(String[] args) {
 
 int a, b, result;
 
 Scanner input = new Scanner(System.in);
 System.out.println("Input two integers");
 
 a = input.nextInt();
 b = input.nextInt();
 
 result = a / b;
 
 System.out.println("Result = " + result);
 }
}

Now we compile and execute the above code two times, see the output of program in two cases:

Java program throwing Arithmetic exception (division by zero).

In the second case we are dividing a by zero which is not allowed in mathematics, so a run time error will occur i.e. an exception will occur. If we write programs in this way then they will be terminated abnormally and user who is executing our program or application will not be happy. This occurs because input of user is not valid so we have to take a preventive action and the best thing will be to notify the user that it is not allowed or any other meaningful message which is relevant according to context. You can see the information displayed when exception occurs it includes name of thread, file name, line of code (14 in this case) at which exception occurred, name of exception (ArithmeticException) and it's description('/ by zero'). Note that exceptions don't occur only because of invalid input only there are other reasons which are beyond of programmer control such as stack overflow exception, out of memory exception when an application requires memory larger than what is available.

Java provides a powerful way to handle such exceptions which is known as exception handling. In it we write vulnerable code i.e. code which can throw exception in a separate block called as try block and exception handling code in another block called catch block. Following modified code handles the exception.

Java exception handling example


class Division { 
public static void main(String[] args) { 
int a, b, result;   
Scanner input = new Scanner(System.in); 
System.out.println("Input two integers");   
a = input.nextInt(); 
b = input.nextInt();   
// try block   
try { 
result = a / b; 
System.out.println("Result = " + result); 
}   
// catch block   
catch (ArithmeticException e) { 
System.out.println("Exception caught: Division by zero."); 
} 
} 
}

Whenever an exception is caught corresponding catch block is executed, For example above code catches ArithmeticException only. If some other kind of exception is thrown it will not be caught so it's the programmer work to take care of all exceptions as in our try block we are performing arithmetic so we are capturing only arithmetic exceptions. A simple way to capture any exception is to use an object of Exception class as other classes inherit Exception class, see another example below:

class Exceptions { 
public static void main(String[] args) { 
String languages[] = { "C", "C++", "Java", "Perl", "Python" }; 
try { 
for (int c = 1; c <= 5; c++) { 
System.out.println(languages[c]); 
} 
} 
catch (Exception e) { 
System.out.println(e); 
} 
} 
}

Output of program:
C++
Java
Perl
Python
java.lang.ArrayIndexOutOfBoundsException: 5

Here our catch block capture an exception which occurs because we are trying to access an array element which does not exists (languages in this case). Once an exception is thrown control comes out of try block and remaining instructions of try block will not be executed. At compilation time syntax and semantics checking is done and code is not executed on machine so exceptions can only be detected at run time.

Finally block in Java


Finally block is always executed whether an exception is thrown or not.

class Allocate { 
public static void main(String[] args) {   
try { 
long data[] = new long[1000000000]; 
} 
catch (Exception e) { 
System.out.println(e); 
}   
finally { 
System.out.println("finally block will execute always."); 
} 
} 
}

Output of program:
finally block will execute always.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at Allocate.main(Allocate.java:5)
Exception occurred because we try to allocate a large amount of memory which is not available. This amount of memory may be available on your system if this is the case try increasing the amount of memory to allocate through the program.

Using multiple classes in Java program

Java program can contain more than one i.e. multiple classes. Following example Java program contain two classes: Computer and Laptop. Both classes have their own constructors and a method. In main method we create object of two classes and call their methods.

Using two classes in Java program


class Computer
{
Computer() { 
System.out.println("Constructor of Computer class."); 
}   
void computer_method() { 
System.out.println("Power gone! Shut down your PC soon..."); 
}   
public static void main(String[] args) { 
Computer my = new Computer(); 
Laptop your = new Laptop();   
my.computer_method(); 
your.laptop_method(); 
} 
}   
class Laptop { 
Laptop() { 
System.out.println("Constructor of Laptop class."); 
}   
void laptop_method() { 
System.out.println("99% Battery available."); 
} 
}
Output of program:


You can also create objects in method of Laptop class. When you compile above code two .class files will be created which are Computer.class and Laptop.class, this has the advantage that you can reuse your .class file somewhere in other projects without compiling the code again. In short number of .class files created will be equal to number of classes in code. You can create as many classes as you want but writing many classes in a single file is not recommended as it makes code difficult to read rather you can create single file for every class. You can also group classes in packages for easily managing your code.

Monday, September 7, 2015

Java constructor tutorial with code examples

Java constructors are the methods which are used to initialize objects. Constructor method has the same name as that of class, they are called or invoked when an object of class is created and can't be called explicitly. Attributes of an object may be available when creating objects if no attribute is available then default constructor is called, also some of the attributes may be known initially. It is optional to write constructor method in a class but due to their utility they are used.

Java constructor example



class Programming { 
//constructor method 
Programming() { 
System.out.println("Constructor method called."); 
} 
public static void main(String[] args) { 
Programming object = new Programming(); 
//creating object 
} 
}
Output of program:

This code is the simplest example of constructor, we create class Programming and create an object, constructor is called when object is created. As you can see in output "Constructor method called." is printed.

Java constructor overloading


Like other methods in java constructor can be overloaded i.e. we can create as many constructors in our class as desired. Number of constructors depends on the information about attributes of an object we have while creating objects. See constructor overloading example:

class Language {
 String name;
 
 Language() {
 System.out.println("Constructor method called.");
 }
 
 Language(String t) {
 name = t;
 }
 
 public static void main(String[] args) {
 Language cpp = new Language();
 Language java = new Language("Java");
 
 cpp.setName("C++");
 
 java.getName();
 cpp.getName();
 }
 
 void setName(String t) {
 name = t;
 }
 
 void getName() {
 System.out.println("Language name: " + name);
 }
}
Output of program:


When cpp object is created default constructor is called and when java object is created constructor with argument is called, setName method is used to set 'name' attribute of language, getName method prints language name.

Java constructor chaining


Constructor chaining occurs when a class inherits another class i.e. in inheritance, as in inheritance sub class inherits the properties of super class. Both the super and sub class may have constructor methods, when an object of sub class is created it's constructor is invoked it initializes sub class attributes, now super class constructor needs to be invoked, to achieve this java provides a super keyword through which we can pass arguments to super class constructor. For more understanding see constructor chaining example:

class GrandParent {
 int a;
 
 GrandParent(int a) {
 this.a = a;
 }
}
 
class Parent extends GrandParent {
 int b;
 
 Parent(int a, int b) {
 super(a);
 this.b = b;
 }
 
 void show() {
 System.out.println("GrandParent's a = " + a);
 System.out.println("Parent's b = " + b);
 }
}
 
class Child {
 public static void main(String[] args) {
 Parent object = new Parent(8, 9);
 object.show();
 }
}
Output of program:
Java constructor chaining program example

Constructor method doesn't specify a return type, they return instance of class itself.

Saturday, September 5, 2015

Java static method

Static methods in Java can be called without creating an object of class. Have you noticed why we write static keyword when defining main it's because program execution begins from main and no object has been created yet. Consider the example below to improve your understanding of static methods.

Java static method example program


class Languages { 
public static void main(String[] args) { 
display(); 
}
 static void display() {
 System.out.println("Java is my favorite programming language.");
 }
}

Output of program:


Java static method vs instance method


Instance method requires an object of its class to be created before it can be called while static method doesn't require object creation.

class Difference {
 public static void main(String[] args) {
 display(); //calling without object
 Difference t = new Difference();
 t.show(); //calling using object
 }
 
 static void display() {
 System.out.println("Programming is amazing.");
 }
 
 void show(){
 System.out.println("Java is awesome.");
 }
}
Output of code:


Using static method of another classes


If you wish to call static method of another class then you have to write class name while calling static method as shown in example below.

import java.lang.Math;
class Another {
 public static void main(String[] args) {
 int result;
 
 result = Math.min(10, 20); //calling static method min by writing class name
 
 System.out.println(result);
 System.out.println(Math.max(100, 200));
 }
}
Output of program:
10 200

Here we are using min and max methods of Math class, min returns minimum of two integers and max returns maximum of two integers. Following will produce an error:

min();

We need to write class name because many classes may have a method with same name which we are calling.

Java static block program

Java programming language offers a block known as static which is executed before main method executes. Below is the simplest example to understand functioning of static block later we see a practical use of static block.

Java static block program


class StaticBlock { 
public static void main(String[] args) { 
System.out.println("Main method is executed.");
} 
static { 
System.out.println("Static block is executed before main method."); 
} 
}

Output of progam:


Static block can be used to check conditions before execution of main begin, Suppose we have developed an application which runs only on Windows operating system then we need to check what operating system is installed on user machine. In our java code we check what operating system user is using if user is using operating system other than "Windows" then the program terminates.



class StaticBlock {
 public static void main(String[] args) {
 System.out.println("You are using Windows_NT operating system.");
 }
 
 static {
 String os = System.getenv("OS");
 if (os.equals("Windows_NT") != true) {
 System.exit(1);
 }
 }
}

We are using getenv method of System class which returns value of environment variable name of which is passed an as argument to it. Windows_NT is a family of operating systems which includes Windows XP, Vista, 7, 8 and others.

Output of program on Windows 7:





Tuesday, September 1, 2015

Java methods

Java program consists of one or more classes and a class may contain method(s). A class can do very little without methods. In this tutorial we will learn about Java methods.Methods are known as functions in C and C++ programming languages. A method has a name and return type. Main method is a must in a Java program as execution begins from it.

Syntax of methods

"Access specifier" "Keyword(s)" "return type" methodName(List of arguments) {
// Body of method
}
Access specifier can be public or private which decides whether other classes can call a method.
Kewords are used for some special methods such as static or synchronized.
Return type indicate return value which method returns.
Method name is a valid Java identifier name.
Access specifier, Keyword and arguments are optional.Examples of methods declaration:
public static void main(String[] args);
void myMethod();
private int maximum();
public synchronized int search(java.lang.Object);

Java Method example program


class Methods { 
// Constructor method
Methods() { 
System.out.println("Constructor method is called when an object of it's class is created");
} 
// Main method where program execution begins
public static void main(String[] args) { 
staticMethod(); 
Methods object = new Methods(); 
object.nonStaticMethod(); 
}  
// Static method  
static void staticMethod() { 
System.out.println("Static method can be called without creating object"); 
}  
// Non static method  
void nonStaticMethod() { 
System.out.println("Non static method must be called by creating an object"); 
} 
}

Output of program:



Java methods list


Java has a built in library of many useful classes and there are thousands of methods which can be used in your programs. Just call a method and get your work done :) . You can find list of methods in a class by typing following command on command prompt:

javap package.classname

For example


javap java.lang.String // list all methods and constants of String class.
javap java.math.BigInteger // list constants and methods of BigInteger class in java.math package

Java String methods


String class contains methods which are useful for performing operations on String(s). Below program illustrate how to use inbuilt methods of String class.

Java string class program


class StringMethods { 
public static void main(String args[]) { 
int n; 
String s = "Java programming", t = "", u = "";   
System.out.println(s);   
// Find length of string   
n = s.length(); 
System.out.println("Number of characters = " + n);   
// Replace characters in string   
t = s.replace("Java", "C++"); 
System.out.println(s); 
System.out.println(t);   
// Concatenating string with another string   
u = s.concat(" is fun"); 
System.out.println(s); 
System.out.println(u); 
} 
}
Output of program:

Java program to convert Fahrenheit to Celsius

Java program to convert Fahrenheit to Celsius: This code does temperature conversion from Fahrenheit scale to Celsius scale.

Java programming code


import java.util.*;

class FahrenheitToCelsius { 
public static void main(String[] args) { 
float temperatue; Scanner in = new Scanner(System.in);   
System.out.println("Enter temperatue in Fahrenheit"); 
temperatue = in.nextInt();   
temperatue = ((temperatue - 32)*5)/9;   
System.out.println("Temperatue in Celsius = " + temperatue); 
} 
}

Output of program:



For Celsius to Fahrenheit conversion use
T = 9*T/5 + 32
where T is temperature on Celsius scale. Create and test Fahrenheit to Celsius program yourself for practice.