eramarswami.com

amar swami


Leave a comment

play with google

1. Google Gravity

Watch Google shattering itself under the effect of gravity. But the funny part is, you can still make a search by entering your query in the search box and it will display the results in gravity fashion.

LINK-1

gravity

2. Google Mirror

Watch google creating the mirror image every you type with google mirror.

mirroring

To do this :

Open google.com and type in google mirror and select I’m feeling lucky or the first link that comes up.

LINK-2


Leave a comment

file handling

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very basic functionality related to streams and I/O. We would see most commonly used example one by one:

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are , FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file:

import java.io.*;

public class CopyFile {
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream(“input.txt”);
out = new FileOutputStream(“output.txt”);

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let’s have a file input.txt with the following content:

This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let’s put above code in CopyFile.java file and do the following:

$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are , FileReader and FileWriter.. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

We can re-write above example which makes use of these two classes to copy an input file (having unicode characters) into an output file:

import java.io.*;

public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader(“input.txt”);
out = new FileWriter(“output.txt”);

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let’s have a file input.txt with the following content:

This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let’s put above code in CopyFile.java file and do the following:

$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where user’s program can take input from a keyboard and then produce output on the computer screen. If you are aware if C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similar way Java provides following three standard streams

Standard Input: This is used to feed the data to user’s program and usually a keyboard is used as standard input stream and represented as System.in.

Standard Output: This is used to output the data produced by the user’s program and usually a computer screen is used to standard output stream and represented as System.out.

Standard Error: This is used to output the error data produced by the user’s program and usually a computer screen is used to standard error stream and represented as System.err.

Following is a simple program which creates InputStreamReader to read standard input stream until the user types a “q”:

import java.io.*;

public class ReadConsole {
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;

try {
cin = new InputStreamReader(System.in);
System.out.println(“Enter characters, ‘q’ to quit.”);
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != ‘q’);
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let’s keep above code in ReadConsole.java file and try to compile and execute it as below. This program continues reading and outputting same character until we press ‘q’:

$javac ReadConsole.java
$java ReadConsole
Enter characters, ‘q’ to quit.
1
1
e
e
q
q
Reading and Writing Files:
As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams
file handling
The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial:

FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read the file.:

InputStream f = new FileInputStream(“C:/java/hello”);
Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows:

File f = new File(“C:/java/hello”);
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.

SN Methods with Description
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.
3 public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it’s end of file.
4 public int read(byte[] r) throws IOException{}
This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If end of file -1 will be returned.
5 public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream. Returns an int.
There are other important input streams available, for more detail you can refer to the following links:

ByteArrayInputStream

DataInputStream

FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn’t already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the file:

OutputStream f = new FileOutputStream(“C:/java/hello”)
Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows:

File f = new File(“C:/java/hello”);
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.

SN Methods with Description
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.
3 public void write(int w)throws IOException{}
This methods writes the specified byte to the output stream.
4 public void write(byte[] w)
Writes w.length bytes from the mentioned byte array to the OutputStream.
There are other important output streams available, for more detail you can refer to the following links:

ByteArrayOutputStream

DataOutputStream

Example:
Following is the example to demonstrate InputStream and OutputStream:

import java.io.*;

public class fileStreamTest{

public static void main(String args[]){

try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream(“test.txt”);
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();

InputStream is = new FileInputStream(“test.txt”);
int size = is.available();

for(int i=0; i< size; i++){
System.out.print((char)is.read() + ” “);
}
is.close();
}catch(IOException e){
System.out.print(“Exception”);
}
}
}
The above code would create file test.txt and would write given numbers in binary format. Same would be output on the stdout screen.

File Navigation and I/O:
There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.

File Class

FileReader Class

FileWriter Class

Directories in Java:
A directory is a File which can contains a list of other files and directories. You use File object to create directories, to list down files available in a directory. For complete detail check a list of all the methods which you can call on File object and what are related to directories.

Creating Directories:
There are two useful File utility methods, which can be used to create directories:

The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.

The mkdirs() method creates both a directory and all the parents of the directory.

Following example creates “/tmp/user/java/bin” directory:

import java.io.File;

public class CreateDir {
public static void main(String args[]) {
String dirname = “/tmp/user/java/bin”;
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}
Compile and execute above code to create “/tmp/user/java/bin”.

Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.

Listing Directories:
You can use list( ) method provided by File object to list down all the files and directories available in a directory as follows:

import java.io.File;

public class ReadDir {
public static void main(String[] args) {

File file = null;
String[] paths;

try{
// create new file object
file = new File(“/tmp”);

// array of files and directory
paths = file.list();

// for each name in the path array
for(String path:paths)
{
// prints filename and directory name
System.out.println(path);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
}
This would produce following result based on the directories and files available in your /tmp directory:

test1.txt
test2.txt
ReadDir.java
ReadDir.class

 


Leave a comment

String and operation on String in java

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings:

The most direct way to create a string is to write:

String greeting = “Hello world!”;
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, “Hello world!’.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.

public class StringDemo{

public static void main(String args[]){
char[] helloArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This would produce the following result:

hello.

Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.

String Length:

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

After the following two lines of code have been executed, len equals 17:

public class StringDemo {

public static void main(String args[]) {
String palindrome = “Dot saw I was Tod”;
int len = palindrome.length();
System.out.println( “String Length is : ” + len );
}
}
This would produce the following result:

String Length is : 17

Concatenating Strings:
The String class includes a method for concatenating two strings:

string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in:

“My name is “.concat(“Zara”);
Strings are more commonly concatenated with the + operator, as in:

“Hello,” + ” world” + “!”
which results in:

“Hello, world!”
Let us look at the following example:

public class StringDemo {

public static void main(String args[]) {
String string1 = “saw I was “;
System.out.println(“Dot ” + string1 + “Tod”);
}
}
This would produce the following result:

Dot saw I was Tod


Creating Format Strings:

You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.

Using String’s static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of:

System.out.printf(“The value of the float variable is ” +
“%f, while the value of the integer ” +
“variable is %d, and the string ” +
“is %s”, floatVar, intVar, stringVar);

you can write:

String fs;
fs = String.format(“The value of the float variable is ” +
“%f, while the value of the integer ” +
“variable is %d, and the string ” +
“is %s”, floatVar, intVar, stringVar);
System.out.println(fs);

ARRAY

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

Declaring Array Variables:

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:

dataType[] arrayRefVar; // preferred way.

or

dataType arrayRefVar[]; // works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

Example:

The following code snippets are examples of this syntax:

double[] myList; // preferred way.

or

double myList[]; // works but not preferred way.

Creating Arrays:

You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];
The above statement does two things:

It creates an array using new dataType[arraySize];

It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, …, valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.

Example:

Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList:

double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9

array
Processing Arrays:

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Example:

Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray {

public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + ” “);
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println(“Total is ” + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i];
}
System.out.println(“Max is ” + max);
}
}
This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops:

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.

Example:

The following code displays all the elements in the array myList:

public class TestArray {

public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
This would produce the following result:

1.9
2.9
3.4
3.5

Passing Arrays to Methods:

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:

public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + ” “);
}
}
You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:

printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method:

A method may also return an array. For example, the method shown below returns an array that is the reversal of another array:

public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length – 1; i < list.length; i++, j–) {
result[j] = list[i];
}
return result;
}

Date Function and use
Getting Current Date & Time:

This is very easy to get current date and time in Java. You can use a simple Date object with toString() method to print current date and time as follows:

import java.util.Date;

public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();

// display time and date using toString()
System.out.println(date.toString());
}
}
This would produce the following result:

Mon May 04 09:51:52 CDT 2009

Date Comparison:

There are following three ways to compare two dates:

You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values.

You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.

You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.

Date Formatting using SimpleDateFormat:

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. For example:

import java.util.*;
import java.text.*;

public class DateDemo {
public static void main(String args[]) {

Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat (“E yyyy.MM.dd ‘at’ hh:mm:ss a zzz”);

System.out.println(“Current Date: ” + ft.format(dNow));
}
}
This would produce the following result:
Current Date: Sun 2004.07.18 at 04:14:09 PM PDT


Leave a comment >

There are two types of decision making statements in Java. They are:

if statements

switch statements

The if Statement:

An if statement consists of a Boolean expression followed by one or more statements.

Syntax:
The syntax of an if statement is:

if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement (after the closing curly brace) will be executed.

Example:

public class Test {

public static void main(String args[]){
int x = 10;

if( x < 20 ){
System.out.print(“This is if statement”);
}
}
}
This would produce the following result:

This is if statement
The if…else Statement:

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax:
The syntax of an if…else is:

if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
Example:
public class Test {

public static void main(String args[]){
int x = 30;

if( x < 20 ){
System.out.print(“This is if statement”);
}else{
System.out.print(“This is else statement”);
}
}
}
This would produce the following result:

This is else statement
The if…else if…else Statement:
An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using single if…else if statement.

When using if , else if , else statements there are few points to keep in mind.

An if can have zero or one else’s and it must come after any else if’s.

An if can have zero to many else if’s and they must come before the else.

Once an else if succeeds, none of the remaining else if’s or else’s will be tested.

Syntax:
The syntax of an if…else is:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}

Example:

public class Test {

public static void main(String args[]){
int x = 30;

if( x == 10 ){
System.out.print(“Value of X is 10”);
}else if( x == 20 ){
System.out.print(“Value of X is 20”);
}else if( x == 30 ){
System.out.print(“Value of X is 30”);
}else{
System.out.print(“This is else statement”);
}
}
}
This would produce the following result:

Value of X is 30
Nested if…else Statement:

It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.

Syntax:
The syntax for a nested if…else is as follows:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if…else in the similar way as we have nested if statement.

Example:

public class Test {

public static void main(String args[]){
int x = 30;
int y = 10;

if( x == 30 ){
if( y == 10 ){
System.out.print(“X = 30 and Y = 10”);
}
}
}
}
This would produce the following result:

X = 30 and Y = 10
The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Syntax:
The syntax of enhanced for loop is:

switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The following rules apply to a switch statement:

The variable used in a switch statement can only be a byte, short, int, or char.

You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.

When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Example:

public class Test {

public static void main(String args[]){
//char grade = args[0].charAt(0);
char grade = ‘C’;

switch(grade)
{
case ‘A’ :
System.out.println(“Excellent!”);
break;
case ‘B’ :
case ‘C’ :
System.out.println(“Well done”);
break;
case ‘D’ :
System.out.println(“You passed”);
case ‘F’ :
System.out.println(“Better try again”);
break;
default :
System.out.println(“Invalid grade”);
}
System.out.println(“Your grade is ” + grade);
}
}
Compile and run above program using various command line arguments. This would produce the following result:

$ java Test
Well done
Your grade is a C
$

loops in java

Leave a comment

There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop.

Java has very flexible three looping mechanisms. You can use one of the following three loops:

1.while Loop

2.do…while Loop

3.for Loop

As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:

A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:
The syntax of a while loop is:

while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.

Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example:

public class Test {

public static void main(String args[]) {
int x = 10;

while( x < 20 ) {
System.out.print(“value of x : ” + x );
x++;
System.out.print(“\n”);
}
}
}
This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The do…while Loop:

A do…while loop is similar to a while loop, except that a do…while loop is guaranteed to execute at least one time.

Syntax:

The syntax of a do…while loop is:

do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

Example:

public class Test {

public static void main(String args[]){
int x = 10;

do{
System.out.print(“value of x : ” + x );
x++;
System.out.print(“\n”);
}while( x < 20 );
}
}
This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The for Loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:

The syntax of a for loop is:

for(initialization; Boolean_expression; update)
{
//Statements
}
Here is the flow of control in a for loop:

The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.

After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.

The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Example:

public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x+1) {
System.out.print(“value of x : ” + x );
System.out.print(“\n”);
}
}
}
This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Enhanced for loop in Java:

As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax:
The syntax of enhanced for loop is:

for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.

Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Example:

public class Test {

public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
System.out.print( x );
System.out.print(“,”);
}
System.out.print(“\n”);
String [] names ={“James”, “Larry”, “Tom”, “Lacy”};
for( String name : names ) {
System.out.print( name );
System.out.print(“,”);
}
}
}
This would produce the following result:

10,20,30,40,50,
James,Larry,Tom,Lacy,

The break Keyword:

The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.

The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax:
The syntax of a break is a single statement inside any loop:

break;

Example:

public class Test {

public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print(“\n”);
}
}
}
This would produce the following result:

10
20

The continue Keyword:

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.

In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax:
The syntax of a continue is a single statement inside any loop:

continue;
Example:
public class Test {

public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print(“\n”);
}
}
}
This would produce the following result:

10
20
40
50


Leave a comment >

Useful Programs:

1) Program of factorial number.

class Operation{

static int fact(int number){
int f=1;
for(int i=1;i<=number;i++){
f=f*i;
}
return f;
}

public static void main(String args[]){
int result=fact(5);
System.out.println(“Factorial of 5=”+result);
}
}

2) Program of fibonacci series.

class Fabnoci{

public static void main(String[] args)
{
int n=10,i,f0=1,f1=1,f2=0;
for(i=1;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
f2=f0;
System.out.println(f2);
}

}
}

3) Program of armstrong number.

class ArmStrong{
public static void main(String…args)
{
int n=153,c=0,a,d;
d=n;
while(n>0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(d==c)
System.out.println(“armstrong number”);
else
System.out.println(“it is not an armstrong number”);

}
}

Bitwise operator

public class Test {

public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */
System.out.println(“a & b = ” + c );

c = a | b; /* 61 = 0011 1101 */
System.out.println(“a | b = ” + c );

c = a ^ b; /* 49 = 0011 0001 */
System.out.println(“a ^ b = ” + c );

c = ~a; /*-61 = 1100 0011 */
System.out.println(“~a = ” + c );

c = a << 2; /* 240 = 1111 0000 */
System.out.println(“a << 2 = ” + c ); c = a >> 2; /* 215 = 1111 */
System.out.println(“a >> 2 = ” + c );

c = a >>> 2; /* 215 = 0000 1111 */
System.out.println(“a >>> 2 = ” + c );
}
}

program on logical operator

public class Test {

public static void main(String args[]) {
boolean a = true;
boolean b = false;

System.out.println(“a && b = ” + (a&&b));

System.out.println(“a || b = ” + (a||b) );

System.out.println(“!(a && b) = ” + !(a && b));
}
}


Leave a comment

java operator

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

  • Arithmetic Operators
  • Relational Operators
  • Bitwise Operators
  • Logical Operators
  • Assignment Operators
  • Misc Operators

The Arithmetic Operators:

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:

Assume integer variable A holds 10 and variable B holds 20, then:

 

Operator Description Example
+ Addition – Adds values on either side of the operator A + B will give 30
Subtraction – Subtracts right hand operand from left hand operand A – B will give -10
* Multiplication – Multiplies values on either side of the operator A * B will give 200
/ Division – Divides left hand operand by right hand operand B / A will give 2
% Modulus – Divides left hand operand by right hand operand and returns remainder B % A will give 0
++ Increment – Increases the value of operand by 1 B++ gives 21
Decrement – Decreases the value of operand by 1 B– gives 19

The Relational Operators:

There are following relational operators supported by Java language

Assume variable A holds 10 and variable B holds 20, then:

 

Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

The Bitwise Operators:

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in binary format they will be as follows:

a = 0011 1100

b = 0000 1101

—————–

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011

The following table lists the bitwise operators:

Assume integer variable A holds 60 and variable B holds 13 then:

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits. (~A ) will give -61 which is 1100 0011 in 2’s complement form due to a signed binary number.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 1111
>>> Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. A >>>2 will give 15 which is 0000 1111

The Logical Operators:

The following table lists the logical operators:

Assume Boolean variables A holds true and variable B holds false, then:

 

Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false.
|| Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true.

The Assignment Operators:

There are following assignment operators supported by Java language:

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C – A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Misc Operators

There are few other operators supported by Java Language.

Conditional Operator ( ? : ):

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as:

variable x = (expression) ? value if true : value if false

Following is the example:

public class Test {

   public static void main(String args[]){
      int a , b;
      a = 10;
      b = (a == 1) ? 20: 30;
      System.out.println( "Value of b is : " +  b );

      b = (a == 10) ? 20: 30;
      System.out.println( "Value of b is : " + b );
   }
}

This would produce the following result:

Value of b is : 30
Value of b is : 20

instanceof Operator:

This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceof operator is wriiten as:

( Object reference variable ) instanceof  (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is the example:

public class Test {

   public static void main(String args[]){
      String name = "James";
      // following will return true since name is type of String
      boolean result = name instanceof String;  
      System.out.println( result );
   }
}

This would produce the following result:

true

This operator will still return true if the object being compared is the assignment compatible with the type on the right. Following is one more example:

class Vehicle {}

public class Car extends Vehicle {
   public static void main(String args[]){
      Vehicle a = new Car();
      boolean result =  a instanceof Car;
      System.out.println( result );
   }
}

This would produce the following result:

true

Precedence of Java Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity
Postfix () [] . (dot operator) Left to
right
Unary ++ – – ! ~ Right to left
Multiplicative * / % Left to right
Additive + – Left to right
Shift >> >>> << Left
to right
Relational > >= < <= Left to right
Equality == != Left
to right
Bitwise AND & Left to right
Bitwise
XOR
^ Left to right
Bitwise OR | Left
to right
Logical AND && Left to right
Logical OR || Left to
right
Conditional ?: Right to left
Assignment = += -= *= /= %=
>>= <<= &= ^= |=
Right to left
Comma , Left to
right


Leave a comment

how to compile and run a java program

Understanding first java program

Let’s see what is the meaning of class, public, static, void, main, String[], System.out.println().

  • class keyword is used to declare a class in java.
  • public keyword is an access modifier which represents visibility, it means it is visible to all.
  • static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn’t require to create object to invoke the main method. So it saves memory.
  • void is the return type of the method, it means it doesn’t return any value.
  • main represents startup of the program.
  • String[] args is used for command line argument. We will learn it later.
  • System.out.println() is used print statement. We will learn about the internal working of System.out.println statement later.

To write the simple program, open notepad by start menu -> All Programs -> Accessories -> notepad and write simple program as displayed below:

javaprogramcompile

As displayed in the above diagram, write the simple program of java in notepad and saved it as Simple.java. To compile and run this program, you need to open command prompt by start menu -> All Programs -> Accessories -> command prompt.

javacompile

To compile and run the above program, go to your current directory first; my current directory is c:\new . Write here:
To compile: javac Simple.java
To execute: java Simple

Internal Details of Hello Java Program

In the previous page, we have learned about the first program, how to compile and how to run the first java program. Here, we are going to learn, what happens while compiling and running the java program. Moreover, we will see some question based on the first program.

What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not interact with OS) and converts the java code into bytecode

javaprogramcompile
What happens at runtime?

At runtime, following steps are performed:

program of java

Classloader: is the subsystem of JVM that is used to load class files.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.
Interpreter: read bytecode stream then execute the instructions.

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).

What is JVM?

It is:

A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created.

What it does?

  1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
  2. An implementation Its implementation is known as JRE (Java Runtime Environment).
  3. Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created.

What it does?

The JVM performs following operation:

  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

JVM provides definitions for the:

  • Memory area
  • Class file format
  • Register set
  • Garbage-collected heap
  • Fatal error reporting etc.

Internal Architecture of JVM

Let’s understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.

jjj

1) Classloader:

Classloader is a subsystem of JVM that is used to load class files.

 

2) Class(Method) Area:

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

 

3) Heap:

It is the runtime data area in which objects are allocated.

 

4) Stack:

Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

 

5) Program Counter Register:

PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.

 

6) Native Method Stack:

It contains all the native methods used in the application.

 

7) Execution Engine:

It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term ?compiler? refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.


Leave a comment

java class,variable declaration

Declaring Classes

You’ve seen classes defined in the following way:

class MyClass {
// field, constructor, and
// method declarations
}
This is a class declaration. The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects.

The preceding class declaration is a minimal one. It contains only those components of a class declaration that are required. You can provide more information about the class, such as the name of its superclass, whether it implements any interfaces, and so on, at the start of the class declaration. For example,

class MyClass extends MySuperClass implements YourInterface {
// field, constructor, and
// method declarations
}
means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.

You can also add modifiers like public or private at the very beginning—so you can see that the opening line of a class declaration can become quite complicated. The modifiers public and private, which determine what other classes can access MyClass, are discussed later in this lesson. The lesson on interfaces and inheritance will explain how and why you would use the extends and implements keywords in a class declaration. For the moment you do not need to worry about these extra complications.

In general, class declarations can include these components, in order:

Modifiers such as public, private, and a number of others that you will encounter later.
The class name, with the initial letter capitalized by convention.
The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
The class body, surrounded by braces, {}.

Declaring Member Variables

There are several kinds of variables:

Member variables in a class—these are called fields.
Variables in a method or block of code—these are called local variables.
Variables in method declarations—these are called parameters.
The Bicycle class uses the following lines of code to define its fields:

public int cadence;
public int gear;
public int speed;
Field declarations are composed of three components, in order:

Zero or more modifiers, such as public or private.
The field’s type.
The field’s name.
The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class.

Access Modifiers

The fi Continue reading


Leave a comment

Basic Rules and variables of java language

Basic Syntax:

About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity – Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
 Class Names – For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word’s first letter should be in Upper Case. Example class MyFirstJavaClass
 Method Names – All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word’s first letter should be in Upper Case. Example public void myMethodName()
 Program File Name – Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append ‘.java’ to the end of the name (if the file name and the class name do not match your program will not compile). Example : Assume ‘MyFirstJavaProgram’ is the class name, then the file should be saved as’MyFirstJavaProgram.java’
 public static void main(String args[]) – Java program processing starts from the main() method, which is a mandatory part of every Java program.

Java Identifiers:

All Java components require names. Names used for classes, variables and methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
 After the first character, identifiers can have any combination of characters.
 A keyword cannot be used as an identifier.  Most importantly identifiers are case sensitive.
 Examples of legal identifiers:age, $salary, _value, __1_value  Examples of illegal identifiers: 123abc, -salary

Java Modifiers:

Like other languages, it is possible to modify classes, methods, etc., by using modifiers.
There are two categories of modifiers:
 Access Modifiers: default, public, protected, private
 Non-access Modifiers: final, abstract, strictfp

Java Variables:

We would see following type of variables in Java:
 Local Variables
 Class Variables (Static Variables)
 Instance Variables (Non-static variables)

Java Arrays:

Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct and initialize in the upcoming chapters.

Java Enums:

Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums. With the use of enums, it is possible to reduce the number of bugs in your code. For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium and large. This would make sure that it would not allow anyone to order any size other than the small, medium or large.

Example:

Class FreshJuice{
enum FreshJuiceSize{ SMALL, MEDUIM, LARGE }
FreshJuiceSize size; }
public class FreshJuiceTest{
public static void main(String args[]){
FreshJuice juice =new FreshJuice();
juice.size =FreshJuice.FreshJuiceSize.MEDUIM ;
}
}

Note: enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.