Java Program
Java Program
Java program to add two numbers :- Given below is the code of java program that adds two numbers
which are entered by the user.
Above code can add only numbers in range of integers(4 bytes), if you wish to add very large
numbers then you can use BigInteger class. Code to add very large numbers:
import java.util.Scanner;
import java.math.BigInteger;
class AddingLargeNumbers {
public static void main(String[] args) {
String number1, number2;
Scanner in = new Scanner(System.in);
System.out.println("Enter first large number");
number1 = in.nextLine();
In our code we create two objects of BigInteger class in java.math package. Input should be digit
strings otherwise an exception will be raised, also you cannot simply use '+' operator to add objects
of BigInteger class, you have to use add method for addition of two objects.
Output of program:
Enter first large number
11111111111111
Enter second large number
99999999999999
Result of addition = 111111111111110
Output of program:
Output of program:
Above program ask the user to enter marks obtained in exam and the input marks are compared
against minimum passing marks. Appropriate message is printed on screen based on whether user
passed the exam or not. In the above code both if and else block contain only one statement but we
can execute as many statements as required.
You can initialize multiple variables, test many conditions and perform increments or decrements on
many variables according to requirement. Please note that all three components of for loop are
optional. For example following for loop prints "Java programmer" indefinitely.
// Infinite for loop
for (;;) {
System.out.println("Java programmer");
}
Example program below uses for loop to print first 10 natural numbers i.e. from 1 to 10.
//Java for loop program
class ForLoop {
public static void main(String[] args) {
int c;
Output of program:
Above program uses nested for loops (for loop inside a for loop) to print stars. You can also use
spaces to create another pattern, It is left for you as an exercise.
Output of program:
Loop body is executed till value of a is greater than value of b and c is not equal to zero.
3. Body of loop can contain more than one statement. For multiple statements you need to place
them in a block using {} and if body of loop contain only single statement you can optionally use {}.
It is recommended to use braces always to make your program easily readable and understandable.
System.out.println("Out of loop");
Output of program:
import java.util.Scanner;
class WhileLoop {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
System.out.println("Input an integer");
}
}
Whatever you can do with while loop can be done with for and do while loop.
You can easily modify the above java program to print alphabets in upper case.
Download Alphabets program class file.
Output of program:
Printing alphabets using while loop (only body of main method is shown):
char c = 'a';
while (c <= 'z') {
System.out.println(c);
c++;
}
Using nested loops we can print tables of number between a given range say a to b, For example if
the input numbers are 3 and 6 then tables of 3, 4, 5 and 6 will be printed. Code:
import java.util.Scanner;
class Tables
{
}
}
Here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory
and System.in is the input stream. Following methods of Scanner class are used in the program
below :1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer "+a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float "+b);
}
There are other classes which can be used for getting input from user and you can also take input
from other devices.
Another method to check odd or even, for explanation see: c program to check odd or even. Code:
import java.util.Scanner;
class EvenOdd
{
public static void main(String args[])
{
int c;
System.out.println("Input an integer");
Scanner in = new Scanner(System.in);
c = in.nextInt();
if ( (c/2)*2 == c )
System.out.println("Even");
else
System.out.println("Odd");
}
There are other methods for checking odd/even one such method is using bitwise operator.
Java methods
Java methods tutorial: 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);
Output of program:
Output of program:
static {
System.out.println("Static block is executed before main method.");
}
Output of program:
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:
begins from main and no object has been created yet. Consider the example below to improve your
understanding of static methods.
Output of program:
Output of code:
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.
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.
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.
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.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.
GrandParent(int a) {
this.a = a;
}
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:
Constructor method doesn't specify a return type, they return instance of class itself.
Now we compile and execute the above code two times, see the output of program in two cases:
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.
// 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[5] 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.
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.
Output of program:
For other methods to swap: C programming code to swap using bitwise XOR. Swapping is frequently
used in sorting techniques such as bubble sort, quick sort etc.
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.
class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
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);
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.
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
count++;
}
status = 1;
num++;
}
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.
return p;
Output of program:
Using one more loop in the above code you can generate Armstrong numbers from 1 to n(say) or
between two integers (a to b).
Output of program:
In Floyd triangle there are n integers in the nth row and a total of (n(n+1))/2 integers in n rows. This
is a simple pattern to print but helpful in learning how to create other patterns. Key to develop
pattern is using nested loops appropriately.
Output of program:
StringBuffer class contains a method reverse which can be used to reverse or invert an object of this
class.
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
System.out.println("Palindrome");
}
else {
System.out.println("Not a palindrome");
}
Both the above codes consider string as case sensitive, you can modify them so that they ignore the
case of string. You can either convert both strings to lower or upper case for this. But do not modify
original strings as they may be further required in program.
Interface in Java
Interface in Java: Java interfaces are like Java classes but they contain only static final constants and
declaration of methods. Methods are not defined and classes which implements an interface must
define the body of method(s) of interface(s). Final constants can't be modified once they are
initialized; final, interface, extend and implements are Java keywords.
Declaration of interface:
interface InterfaceName {
// constants declaration
// methods declaration
}
if ( s1.compareTo(s2) > 0 )
System.out.println("First string is greater than second.");
else if ( s1.compareTo(s2) < 0 )
System.out.println("First string is smaller than second.");
else
System.out.println("Both strings are equal.");
Output of program:
String 'hello' is greater than 'Hello' as ASCII value of 'h' is greater than 'H'. To check two strings for
equality you can use equals method which returns true if strings are equal otherwise false.
Above code locate first instance of element to found, you can modify it for multiple occurrence of
same element and count how many times it occur in the list. Similarly you can find if an alphabet is
present in a string.
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last
= n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) +
".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
Output of program:
Other methods of searching are Linear search and Hashing. There is a binarySearch method in
Arrays class which can also be used.
import java.util.Arrays;
class BS
{
public static void main(String args[])
{
char characters[] = { 'a', 'b', 'c', 'd', 'e' };
System.out.println(Arrays.binarySearch(characters, 'a'));
System.out.println(Arrays.binarySearch(characters, 'p'));
}
binarySearch method returns the location if a match occurs otherwise -(x+1) where x is the no. of
elements in the array, For example in the second case above when p is not present in characters array
the returned value will be -6.
import java.util.Scanner;
class SubstringsOfAString
{
public static void main(String args[])
{
String string, sub;
int i, c, length;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to print it's all substrings");
string = in.nextLine();
length = string.length();
System.out.println("Substrings of \""+string+"\" are :-");
For a string of length n there will be (n(n+1))/2 non empty substrings and one more which is empty
string. Empty string is considered to be substring of every string also known as NULL string.
System.out.println("Current date is
System.out.println("Current time is
"+day+"/"+(month+1)+"/"+year);
"+hour+" : "+minute+" : "+second);
Don't use Date and Time class of java.util package as their methods are deprecated means they may
not be supported in future versions of JDK. As an alternative of GregorianCalendar class you can use
Calendar class.
nextInt(c) method returns next integer in 0 to c (both inclusive), c must be positive. To generate
random float's use nextFloat which returns float between 0.0 to 1.0.
Obviously the amount of available after garbage collection will be different on your computer.
Numbers are not important, what is important is that amount of memory available is more than
before. You can use this code in your program or projects which uses large amount of memory or
where frequently new objects are created but are required for a short span of time.
This program prints IP or internet protocol address of your computer system. InetAddress class of
java.net package is used, getLocalHost method returns InetAddress object which represents local
host.
Output of code prints computer name/ IP address of computer. Java has a very vast Networking API
and can be used to develop network applications.
You can also reverse or invert a number using recursion. You can use this code to check if a number
is palindrome or not, if the reverse of an integer is equal to integer then it's a palindrome number
else not.
This code adds two matrix, you can modify it to add any number of matrices. You can create a Matrix
class and create it's objects and then create an add method which sum the objects, then you can add
any number of matrices by repeatedly calling the method using a loop.
System.out.print("\n");
Output of program:
This code can be used to check if a matrix symmetric or not, just compare the matrix with it's
transpose if they are same then it's symmetric otherwise non symmetric, also it's useful for
calculating orthogonality of a matrix.
p = in.nextInt();
q = in.nextInt();
if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied
with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
second[c][d] = in.nextInt();
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
System.out.print("\n");
Output of program:
This is a basic method of multiplication, there are more efficient algorithms available. Also this
approach is not recommended for sparse matrices which contains a large number of elements as
zero.
Complexity of bubble sort is O(n2) which makes it a less frequent option for arranging in sorted order
when quantity of numbers is high.
Download Bubble sort Java program.
Output of program:
You can also use sort method of Arrays class to sort integers in ascending order but remember that
sort method uses a variation of Quick sort algorithm.
import java.util.Arrays;
class Sort
{
public static void main(String args[])