Saturday, September 5, 2015

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.

Sunday, August 23, 2015

Java program to find odd or even

This java program finds if a number is odd or even. If the number is divisible by 2 then it will be even, otherwise it is odd. We use modulus operator to find remainder in our program.

Java programming source code


import java.util.Scanner;
 
class OddOrEven
{
 public static void main(String args[])
 {
 int x;
 System.out.println("Enter an integer to check if it is odd or even ");
 Scanner in = new Scanner(System.in);
 x = in.nextInt();
 
 if ( x % 2 == 0 )
 System.out.println("You entered an even number.");
 else
 System.out.println("You entered an odd number.");
 }
}

Output of program:


Another method to check odd or even

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.

import java.util.Scanner;
public class EvenOrOdd { 
public static void main(String args[]) { 
Scanner obj = new Scanner(System.in);
int no;
System.out.println("Enter any number to check if it is Even or Odd number:");
no = obj.nextInt();
isOddOrEven(no); 
}
public static void isOddOrEven(int number){ 
if((number & 1) == 0){ 
System.out.println("Using bitwise operator: " + number + " is Even number"); 
}
else{ 
System.out.println("Using bitwise operator: " + number + " is Odd number"); 
} 
} 
}

Output of 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.

Java programming source code


import java.util.Scanner;
 
class AddNumbers
{
 public static void main(String args[])
 {
 int x, y, z;
 System.out.println("Enter two integers to calculate their sum ");
 Scanner in = new Scanner(System.in);
 x = in.nextInt();
 y = in.nextInt();
 z = x + y;
 System.out.println("Sum of entered integers = "+z);
 }
}

Output of program:


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();
 
 System.out.println("Enter second large number");
 number2 = in.nextLine();
 
 BigInteger first = new BigInteger(number1);
 BigInteger second = new BigInteger(number2);
 BigInteger sum;
 
 sum = first.add(second);
 
 System.out.println("Result of addition = " + sum);
 }
}

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