Search Java Programs

Thursday, January 28, 2010

Java FAQs and tutorials

Java FAQ's

Path and ClassPath:

PATH

In Windows 9x you would set it up in the autoexec.bat file
ie.
SET PATH=%PATH%;c:\jdk1.4.2\bin\;

where c:\jdk1.4.2\ is the path where you installed Java.

In Windows 2000 and XP
Right click on My Computer->Properties->Advanced Tab->Environment Variables... Button.

If you see a PATH in System Variables, click that and edit it. If you don't, you will need to create a new System variable.

It should look something like this:
%SystemRoot%\system32;%SystemRoot%;c:\jdk1.4.2\bin\;

NOTE: There may be other paths in the PATH variable, leave them there!

CLASSPATH

Eventually you will need to add pre-packaged software to your project.
The way to do this is to set up an environment variable called classpath.

In Windows 9x you would set it up in the autoexec.bat file
ie.
SET CLASSPATH=%CLASSPATH%;c:\MyPackage1.jar;c:\MyPackage2.jar

In Windows 2000 and XP
Right click on My Computer->Properties->Advanced Tab->Environment Variables... Button.

If you see a CLASSPATH in System Variables, click that and edit it. If you don't, you will need to create a new System variable.

In Linux, from my understanding, there are a few ways to do this, but I set up mine in the /etc/profile file:

# Taken directly from /etc/profile in RedHat Linux 8.0
JAVA_HOME="/usr/java/jdk1.3.1_06"
J2EE_HOME="/usr/local/etc/java/j2sdkee1.3.1"
PATH="/usr/java/jwsdp1_0_0_1/bin":$JAVA_HOME:$J2EE_HOME/bin:$J2EE_HOME:$J2EE_HOME/bin:$PATH
JAR_PATH="/usr/local/Jars"
CLASSPATH=$JAR_PATH/jcert.jar:$JAR_PATH/jnet.jar:$JAR_PATH/jsse.jar:$CLASSPATH
export PATH JAVA_HOME J2EE_HOME
export CLASSPATH

What is an IDE?

An IDE(Integrated Development Environment) is a development tool used to make programming easier.

What is a good IDE?

Borland JBuilder
Eclipse
Intellij
JCreator
Macromedia JRun
Sun One Studio

JARS the basics

Basically all a JAR is, is a ZIP file that contains the necessary classes to execute your program.
A Jar is a way to package your classes in one convenient file.

To learn more, follow this link


Eliminate Prompt and Executable Jars

Javaw.exe is intended to run Java programs, just like java.exe, but without the Consol Window.
Suppose you wanted to run a Java program in a Windows Environment, you could create a shortcut to
your program, and the command to run your program would be "javaw myProject.MyProgram"

An Executable JAR is a jar file that has the class with the main method specified in the Manifest.mf file
located in the directory meta-inf/ directory of your JAR.

In a Windows environment, Windows looks in the registry for the associated program to open the JAR file.
In this case javaw.exe. Java looks in the Manifest file for the main method and executes that class.
On other platforms the command to execute a jar would be "javaw -jar myprogram.jar"

A simple example of a manifest would be:

Manifest-Version: 1.0
Main-Class: myProject.MyClassWithMain

My Applet doesn't work and the Java Plugin.

Most browsers have the plugin for Java 1.1, but with the introduction of Swing in Java 1.2, your program
might need a newer plugin for the browser. SUN has come up with a handy little converter that will
change your HTML code to detect and download the newer plugin. It can be found here

Links in an Applet

In a click event for some Component, you could use the following code:

Code:
//To send the current page to a new location, the code would be:
this.getAppletContext().showDocument(new URL("http://www.google.com"));

//To open a new Browser Window: 
this.getAppletContext().showDocument(new URL("http://www.google.com"),"_blank");
I apologize that it took so long for me to get this up. It isn't finished yet, and if you have any suggestions, you may contact me here.

Click here for more CodeGuru Java FAQ's

Tuesday, January 26, 2010

How to Sort of Array integer and String

import java.util.Arrays;

/**
 *
 * @author javadb.com
 */
public class testing {

    /**
     * Example method for sorting an int array
     */
    public void sortIntArray() {

        int[] arrayToSort = new int[] {48, 5, 89, 80, 81, 23, 45, 16, 2};

        Arrays.sort(arrayToSort);

        for (int i = 0; i < arrayToSort.length; i++)
        {
            System.out.print(arrayToSort[i] + " ");
        }
        System.out.println("\n");
    }
    

    /**
     * Example method for sorting a String array
     */
    public void sortStringArray() {

        String[] arrayToSort = new String[] {"Oscar", "Charlie", "Ryan", "Adam", "David"};

        Arrays.sort(arrayToSort);

        for (int i = 0; i < arrayToSort.length; i++)
        {
            System.out.print(arrayToSort[i] + " ");
        
        }
        System.out.println("\n");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        testing main = new testing();
        main.sortIntArray();
        main.sortStringArray();
    }
}

How to use ArrayList in Java

// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add("H");
al.add(2, "A2");

System.out.println("Size of al after additions: " + al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(6);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}

Wednesday, January 20, 2010

Java String valueOf Example

String class valueOf method example.


String class valueOf method example:- This example demonstrates the working of valueOf method. this method returns String representations of all data types values

Syntax:-valueOf(boolean b)

Here is the code:-

 /**
* @(#) ValueOfString.java
* ValueOfString class demonstrates the working of valueOf() method of String class of lang package
* @version 16-May-2008
* @author Rose India Team
*/



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

// method converts any data type value in to String type
boolean result = true;
int in = 234;
char ch = 'u';
double dou = 34.86;
float flt = 54.889f;

System.out.println("String represented boolean value: "
+ String.valueOf(result)
+ "\nString represented integer value: " + String.valueOf(in)
+ "\nString represented char value: " + "'"
+ String.valueOf(ch) + "'"
+ "\nString represented double value: " + String.valueOf(dou)
+ "\nString represented float value: " + String.valueOf(flt));

}
}
Output of the program:-
String represented boolean value: true
String represented integer value: 234
String represented char value: 'u'
String represented double value: 34.86
String represented float value: 54.889

Java String lastIndexOf Example

String class lastIndexOf method example.


String class lastIndexOf method examle:- This example demonstrates the working of lastIndexOf method. This method returns the index or number location of letter from last of the statement.

Syntax:-lastIndexOf(String str)

Here is the code:-

 /**
* @(#) LastIndexOfString.java
* LastIndexOfString class demonstrates the working of lastIndexOf() method of String class of lang package
* @version 16-May-2008
* @author Rose India Team
*/


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

String prabhu = "o paalan haari", bholenaath;
// double quotes as arguments inside parentheses
// Method returns last index of letter or word passes in single ang
System.out.println("last index of letter 'i': "
+ prabhu.lastIndexOf('i'));

bholenaath = "bam bolo bam bolo bam bam bam";
// here instead of index of word 'bolo', the letter which word stats
// that is 'b', is returned and same happens every time for every word
// or statement
System.out.println("Index of letter 'b' is returned: "
+ bholenaath.lastIndexOf("bolo"));
// here were complete statement is passed in the arguments but still
// methos returns the index of first letter only
System.out.println("Index of letter 'o' is returned: "
+ prabhu.lastIndexOf("o paalan haari"));
}
}
Output of the program:-
last index of letter ' i ': 13
Index of letter 'b' is returned: 13
Index of letter 'o' is returned: 0

Java String equalsIgnoreCase Example

String class equalsIgnoreCase method example


String class equalsIgnoreCase method example:- This method demonstrates the working of equalsIgnoreCase method. this method returns a boolean value after examining the two String. this method's examines without considering case senstivity

Syntax:-equalsIgnoreCase(String anotherString)

Here is the code:-

/**
* @(#) EqualsIgnoreCaseString.java
* EqualsIgnoreCaseString class demonstrates the working of equalsIgnoreCase() method of String class of lang package
* @version 15-May-2008
* @author Rose India Team
*/



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

String str = "koi mil gaya", str1 = "Koi mil gaya", str2 = "";
boolean result = str.equalsIgnoreCase(str1);
// Method compares two String leaving case Senstivity behind
//Strings str and str1 are equal therefore method here returns true
System.out.println("method returns true: " + result);

String str3 = new String("12234");

result = str.equalsIgnoreCase(str3);
//Strings str and str3 are not equal
System.out.println("false is returned: " + result);
}
}
Output of the program:-
method returns true: true
false is returned: false

Java String startsWith Example

String class startsWith method example.


String class startsWith method example:- This method demonstrates the working of startsWith method. this method returns boolean value on the basis of matching starting value and objects name with arguments.

Syntax:-startsWith(String prefix)

Here is the code:-

/**
* @(#) StartsWithString.java
* StartsWithString class demonstrates the working of startsWith() method of String class of lang package
* @version 16-May-2008
* @author Rose India Team
*/



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

String str = "he ram";
// method returns true if passed argument in quotes matches first the
// word of object value
boolean result = str.startsWith("he");
System.out.println("Method returns 'true': " + result);

// method returns true if passed argument not in quotes matches the
// object name
result = str.startsWith(str);
System.out.println("Method returns 'true': " +result);
}
}
Output of the program:-
Method returns 'true': true
Method returns 'true': true

Java String isEmpty Example

String class isEmpty method example


String class isEmpty method example:- This method returns boolean value true if and only if .length methodreturns for the object taken under process and returns false if object chosen is not empty that means it has .length() method value greater than zero.

Syntax:- isEmpty()

Here is the code:-

 /**
* @ # StringArray3.java
* A class repersenting how Convert
* string array to a collection
* version 04 June 2008
* author Rose India
*/

import java.util.*;
public class StringArray3 {
public static void main(String args[]){
String arr[] = {"Zero", "One", "Two"};

//Convert string array to a collection
Collection l = Arrays.asList(arr);
ArrayList list = new ArrayList(l);

System.out.println("list = " + list);
}
}
Output of the program:-
length of the method is returned: 5
Method returns false here: false

String Array to Collection Example

Array to Collection example.This example shows you how to Convert string array to Collection.


This example shows you how to Convert string array to an Collection.

Here is the code

 /**
* @ # StringArray3.java
* A class repersenting how Convert
* string array to a collection
* version 04 June 2008
* author Rose India
*/

import java.util.*;
public class StringArray3 {
public static void main(String args[]){
String arr[] = {"Zero", "One", "Two"};

//Convert string array to a collection
Collection l = Arrays.asList(arr);
ArrayList list = new ArrayList(l);

System.out.println("list = " + list);
}
}
Output
list = [Zero, One, Two]

Java String length Example

String class length method example


String class length method example:- This example demonstrates the working .length method. this method returns total indexes that is what called length of the object .

Syntax:-length()

Here is the code:-

 /**
* @(#) LengthString.java
* LengthString class demonstrates the working of .length() method of String class of lang package
* @version 16-May-2008
* @author Rose India Team
*/


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

String heram = new String("Maryada"), prabhu = "purushottam", o_paalan_haari = "ram", bharat = heram
+ prabhu + o_paalan_haari,
// .length method generates the number total of indexes available or in
// use by the object value
rawan = "lenth of String 'heram': " + heram.length()
+ "\nlength of String 'prabhu': " + prabhu.length()
+ "\nlength of String 'o_paalan_haari': "
+ o_paalan_haari.length();

System.out.println(rawan);

int hanuman = bharat.length(), Sita_Mayya = rawan.length();
System.out.println("length of hanuman: " + hanuman);
System.out.println("length of Sita_mayya: " + Sita_Mayya);
String baadshah = Integer.toString(hanuman), begum = Integer
.toString(Sita_Mayya);

}

}
Output of the program:-
lenth of String 'heram': 7
length of String 'prabhu': 11
length of String 'o_paalan_haari': 3
length of hanuman: 21
length of Sita_mayya: 98

Java String toCharArray Example

String class toCharArray method example.


String class toCharArray method example:- This example demonstrates the working of toCharArray method. this method converts complete String value in to a char array type value.

Syntax:- toCharArray()

Here is the code:-

 /**
* @(#) ToCharArrayString.java
* ToCharArrayString class demonstrates the working of toCharArray() method of String class of lang package
* @version 16-May-2008
* @author Rose India Team
*/



public class ToCharArrayString {
public static void main(String args[]) {
//method converts complete String value to char array type value
String str = " einstein relativity concept is still a concept of great discussion";
char heram[] = str.toCharArray();
// complete String str value is been converted in to char array data by
// the method
System.out.print("Converted value from String to char array is: ");
System.out.println(heram);
}
}
Output of the program:-
Converted value from String to char array is: einstein relativity concept is still a concept of great discussion

Java String hashCode Example

String class hashCode method example


String class hashCode method example:- This example demonstrates the working of hashCode method. this method returns corresponding hashCodes of objects value passed.

Syntax:-hashCode()

Here is the code:-

 /**
* @(#) HashCodeString.java
* HashCodeString class demonstrates the working of hashCode() method of String class of lang package
* @version 16-May-2008
* @author Rose India Team
*/



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

// hashCode method generates hash codes repersentations of only objects
// values
// arithmetically hash Codes of numbers are generated as follows
// s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
// here i is any character value or number value of the object,
// n is .length method value of the object say String, and ^ denotes
// exponentiation.
// The hash value of the empty string is zero
Integer j = new Integer(10);
Long k = new Long(10);
Integer v = new Integer(0);
// here value types don't match therefore methos returns false
System.out.println("false is returned: " + j.equals(k));
// hash codes of different objects with same value are always same
System.out.println("Hash code of number 10 is: " + j.hashCode()
+ "\nHash code of number 10 is: " + k.hashCode());
// corresponding hash code value of number zero(0) is zero(0)
System.out.println("Method returns zero: " + v.hashCode());

String baadshah = "latter in time there will be my empire every where";
// hashCode representation of the value ofobject 'baadshah'
// every object has its own hash code representation of their values
// every value of any object consists of unique hash codes
System.out.println("Corresponding hash code value returned is: "
+ baadshah.hashCode());
}

}
Output of the program:-
false is returned: false
Hash code of number 10 is: 10
Hash code of number 10 is: 10
Method returns zero: 0
Corresponding hash code value returned is: 342164105

Java String toLowerCase Example

String class toLowerCase method example


String class toLowerCase method example:- This example demonstrates the working of toLowerCase method example. this method returns completly formated data from uppercase to lower case.

Syntax:-toLowerCase()

Here is the code:-

 /**
* @(#) ToLowerCaseString.java
* ToLowerCaseString class demonstrates the working of toLowerCase() method of String class of lang package
* @version 16-May-2008
* @author Rose India Team
*/



public class ToLowerCaseString {
public static void main(String args[]) {
//method converts all letters of String in to lower case letters
//method cannot be invoked while working with CharSequence interfaces
String heram = "MARYADA PURUSHOTTAM RAM";
System.out.println(" formatted value of string 'heram' is: "
+ heram.toLowerCase());

String krishna = new String("JAI_MAHA_KAAL"), meghnaath = "";
meghnaath = krishna.toLowerCase();
System.out.println(" formatted value of string 'krishna' is: "
+ meghnaath);

}
}
Output of the program:-
formatted value of string 'heram' is: maryada purushottam ram
formatted value of string 'krishna' is: jai_maha_kaal

Java String equals Example

String class equals method example


String class equals method example:- This method demonstrates the working of equals() method. it returns boolean values true and false after examining the two objects taken under checking process

Syntax:-equals(Object anObject)

Here is the code:-

/**
* @(#) EqualsString.java
* EqualsStringString class demonstrates the working of equals() method of String class of lang package
* @version 15-May-2008
* @author Rose India Team
*/





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

Integer in = new Integer(12234);
String str = new String("12234");

// since both objects posses same value but the type of value is
// different. Here there are two types of objects compared one is
// Integer type and the other one is String type so the method returns
// false as values types didnot match

System.out.println( "value types don't matches: " + in.equals(str));


// method returns true if and only if none of the Strings compared
// posses null value and also must that there value matches each other
// in sequence, cases and all aspects of equality including value types
String str1 = new String(" hare krishna hare rama! rama rama hare hare");
String str2 = str1.substring(0);
String str3 = " ", str4 = " ";
String str5 = "heram", str6 = "Heram";
//Method returns true here as both Strings str1 and str2 posses same values
System.out.println(" 'true' is returned: " + str1.equals(str2));
//Both the String mentioned above don't have any value but still Strings are equal as both are null type objects compared"
System.out.println("Method returns true here: " + str3.equals(str4));
//Method here returns false because values of Strings did not match when their respective letters case are concerned
System.out.println(" 'false' is returned: " + str5.equals(str6));

}
}
Output of the program:-
value types don't matches: false

'true' is returned: true

Method returns true here: true

'false' is returned: false

Java String contains Example

String class Contains method example


String class Contains method example:- This example demonstrates the working of contains() method. this method generates boolean value true if and only if it finds the same sequence of data in the called String.

Syntax:-contains(CharSequence s)

Here is the code:-

/**
* @(#) ContainsString.java
* ContainsString class demonstrates the working of contains() method of String class of lang package
* @version 14-May-2008
* @author Rose India Team
*/



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

// contains() method checks the sequence characters and
// number or both characters and numbers together passed in parentheses
// into the called String
String str = "om namah shivaya", str1 = "420_9211", str2, str3;

CharSequence char0 = "am", char1 = "_";
boolean result = str.contains(char0);

// Method ables to find the sequence of characters(am) therefore it
// generates boolean type true
System.out.println("Method returns true here: " + "'" + result + "'");
result = str1.contains(char1);
System.out.println();
// Method ables to fing the symbol underscore(_) therefore it generates
// boolean type true"
System.out.println("'true' is returned: " + "'" + result + "'");

System.out.println();
str2 = " hare ram1 hare ram, hare krishna hare ram ";
System.out.println("'false' is returned: " + "'"
+ str2.contains("krishna ram1") + "'");

}

}
Output of the program:-
Method returns true here: 'true'

'true' is returned: 'true'

'false' is returned: 'false'

Java String matches Example

String class matches method example


String class matches method example:- This example demonstrates the working of matches() method. this method returns boolean values if it gets same match of object value to the passes argument value in the parentheses.

Syntax:-matches(String regex)

Here is the code:-

 /**
* @(#) MatchesString.java
* MatchesString class demonstrates the working of matches() method of String class of lang package
* @version 16-May-2008
* @author Rose India Team
*/



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

// method just matches the String value to the specified value in the
// parentheses and generates boolean values
String str = " heram", str1 = "xaaaaa";
boolean result = str1.matches("aaaaa");
// method not get the same values therefore it returns false
System.out.println("Method returns 'false': " + result);

// method gets the same values but not able to match there allignments
// therefore it returns false
result = str.matches("heram");
System.out.println("Method returns 'false': " + result);

// method gets the same values with precise allignments therefore it
// returns true
result = str.matches(" heram");
System.out.println("Method returns 'true': " + result);
}
}
Output of the program:-
Method returns 'false': false
Method returns 'false': false
Method returns 'true': true

String Array Example

String Array example. This example shows you how to initialize String Array


This example shows you how to initialize String Array.

Here is the code

/**
* @ # StringArray.java
* A class repersenting how initialization String Arrays
* version 04 June 2008
* author Rose India
*/

public class StringArray {

public static void main(String args[]) {

//initialization String Arrays
String arr[] = {"Zero", "One", "Three"};

System.out.println("String Array arr ...");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}

String arr1[] = new String[]{"Zero", "One", "Two"};
System.out.println("\nString Array arr1...");
for (int i = 0; i < arr1.length; i++) {
System.out.println(arr1[i]);
}

// This allocates the array but they are all null
String arr2[] = new String[3];

// here you start to stuff in the values.
arr2[0] = "Zero";
arr2[1] = "One";
arr2[2] = "Two";

System.out.println("\nString Array arr2...");
for (int i = 0; i < arr2.length; i++) {
System.out.println(arr2[i]);
}
}
}
Output
String Array arr ...
Zero
One
Three

String Array arr1...
Zero
One
Two

String Array arr2...
Zero
One
Two

Java String substring() Example

String class substring method example


String class substring method example:- This example demonstrates the working of substring method example. this method returns a substring of a String , here substring is a new string in which value from certain index passed has been copied and pasted of String under method process

Syntax:- substring(int beginIndex)

Here is the code:-

/**
* @(#) IndexOfString.java
* IndexOfString class demonstrates the working of indexOf() method of String class of lang package
* @version 15-May-2008
* @author Rose India Team
*/



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

// Method here returns index location or number position of the specified character.
String str = "hare krishna hare krishna krishna krishna hare hare";
int prabhu = str.indexOf('h'), heram;

System.out.println("Index of 'h' in String 'str' is: " + prabhu);
System.out.println("Index of 'k' in String 'str' is: " + str.indexOf("k"));

//For a word or sequence of charaters, method returns the index location of letter with which the word starts.
System.out.println("Index of 'krishna' in String 'str' is: " + str.indexOf("krishna"));

}
}
Output of the program:-
value of String str1 taken by the method : as per einstein conclusion nothing can travel faster than light
value String str2 taken by the method: ram

Java String indexOf() Example

String class indexOf method example


String class indexOf method example:- This example demonstrates the working of indexOf method. this method returns the index location of character specified.

Syntax:-indexOf('h')

Here is the code:-

/**
* @(#) IndexOfString.java
* IndexOfString class demonstrates the working of indexOf() method of String class of lang package
* @version 15-May-2008
* @author Rose India Team
*/



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

// Method here returns index location or number position of the specified character.
String str = "hare krishna hare krishna krishna krishna hare hare";
int prabhu = str.indexOf('h'), heram;

System.out.println("Index of 'h' in String 'str' is: " + prabhu);
System.out.println("Index of 'k' in String 'str' is: " + str.indexOf("k"));

//For a word or sequence of charaters, method returns the index location of letter with which the word starts.
System.out.println("Index of 'krishna' in String 'str' is: " + str.indexOf("krishna"));

}
}
Output of the program:-
Index of 'h' in String 'str' is: 0
Index of 'k' in String 'str' is: 5
Index of 'krishna' in String 'str' is: 5

Java String concat Example

Here is the code:-
/**
* @(#) ConcatString.java
* ConcatString class demonstrates the working of concate() method of String class of lang package
* @version 14-May-2008
* @author Rose India Team
*/




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

// concat() method is called 'add to' method as this method adds
// String,s
// value inside parentheses to the String left side of the assignment
// operater(=)

String str = "Combination of Astrology, Astronomy and Technology", str1 = "He ram ", str2 = " can lead to the invention of computers that can tell the incidents that will happen latter in time", heram = "", prabhu = "";

heram = str1.concat(str);
prabhu = heram.concat(str2);

System.out.println(prabhu);
System.out.println();
System.out.println("It can also b done in this way as:- '''System.out.println(str1 + srt + str2 );''' and result will be same below ");
System.out.println(str1 + str + str2);
System.out.println();

}

}
Output of the program:-
He ram Combination of Astrology, Astronomy and Technology can lead to the invention of computers that can tell the incidents that will happen latter in time

It can also b done in this way as:- '''System.out.println(str1 + srt + str2 );''' and result will be same below
He ram Combination of Astrology, Astronomy and Technology can lead to the invention of computers that can tell the incidents that will happen latter in time

Combine String example

In this section, you will learn how to combine or merge two strings in java. The java.lang package provides the method that helps you to combine two strings and making into single string. The following program is used for concatenating two string through using the concat() method that concatenates the specified string to the end of string and finally, you will get the combined string.

Description of code:

concat(String str):
This is the method that concatenates the two specified strings.

Here is the code of program:

import java.io.*;

public class CombinString{
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter First String:");
String str1 = bf.readLine();
System.out.println("Enter Second String:");
String str2 = bf.readLine();
System.out.println("Combin string example!");
String com = str1.concat(str2);
System.out.println("Combined string: " + com);
}
}
Output of program:
C:\vinod\Math_package>javac CombinString.java

C:\vinod\Math_package>java CombinString
Enter First String:
RoseIndia
Enter Second String:
NewstrackIndia
Combin string example!
Combined string: RoseIndiaNewstrackIndia

Combine String example

In this section, you will learn how to combine or merge two strings in java. The java.lang package provides the method that helps you to combine two strings and making into single string. The following program is used for concatenating two string through using the concat() method that concatenates the specified string to the end of string and finally, you will get the combined string.

Description of code:

concat(String str):
This is the method that concatenates the two specified strings.

Here is the code of program:

import java.io.*;

public class CombinString{
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter First String:");
String str1 = bf.readLine();
System.out.println("Enter Second String:");
String str2 = bf.readLine();
System.out.println("Combin string example!");
String com = str1.concat(str2);
System.out.println("Combined string: " + com);
}
}
Output of program:
C:\vinod\Math_package>javac CombinString.java

C:\vinod\Math_package>java CombinString
Enter First String:
RoseIndia
Enter Second String:
NewstrackIndia
Combin string example!
Combined string: RoseIndiaNewstrackIndia

Compare string example - Equals()

In this section, you will learn how to compare two strings in java. The java lang package provides a method to compare two with their case either upper and lower. The equals() method provides the facility of comparing the two strings. The following program uses the equals() method and helps you to compare the two strings. If both strings are equal, it will display a message "The given strings are equal" otherwise it will show "The given string are not equal".

Description of code:

equals():
This is the method that compares an object values and returns Boolean type value either 'true' or 'false'. If it returns 'true' for the both objects, it will be equal otherwise not.

Here is the code of program:

import java.lang.*;
import java.io.*;

public class CompString{
public static void main(String[] args) throws IOException{
System.out.println("String equals or not example!");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter first string:");
String str1 = bf.readLine();
System.out.println("Please enter second string:");
String str2 = bf.readLine();
if (str1.equals(str2)){
System.out.println("The given string is equals");
}
else{
System.out.println("The given string is not equals");
}
}
}

Output of program:

Both are equals:

C:\vinod\Math_package>javac CompString.java

C:\vinod\Math_package>java CompString
String equals or not example!
Please enter first string:
Rose
Please enter second string:
Rose
The given string is equals

Both are not equals:

C:\vinod\Math_package>java CompString
String equals or not example!
Please enter first string:
Rose
Please enter second string:
rose
The given string is not equals

What is instance variable?

When a number of objects are created from the same class, the same copy of instance variable is provided to all. Remember, each time you call the instance the same old value is provided to you, not the updated one . In this program we are showing that how a instance variable is called in each instance, but the copy remains same irrespective the counter we have used in the constructor of a class. We can't call the non-static variable in a main method. If we try to call the non-static method in the main method then the compiler will prompt you that non-static variable cannot be referenced from a static context. We can call the non-static variable by the instance of the class.

The example will show you how you can use a non-static variables. First create a class named NonStaticVariable. Declare one global variable and call it in the constructor overloaded method in which you will have to increment the value of the variable by the counter. To access a non-static variable we will have to make a object of NonStaticVariable by using new operator. Now call the instance variable. Now again make a new object of the class and again call the instance variable. Now you can realize that the value of the instance variable in both the object is same.

Code of this program is given below:

public class NonStaticVariable{
int noOfInstances;
NonStaticVariable(){
noOfInstances++;
}
public static void main(String[] args){
NonStaticVariable st1 = new NonStaticVariable();
System.out.println("No. of instances for st1 : " + st1.noOfInstances);

NonStaticVariable st2 = new NonStaticVariable();
System.out.println("No. of instances for st1 : " + st1.noOfInstances);
System.out.println("No. of instances for st2 : " + st2.noOfInstances);

NonStaticVariable st3 = new NonStaticVariable();
System.out.println("No. of instances for st1 : " + st1.noOfInstances);
System.out.println("No. of instances for st2 : " + st2.noOfInstances);
System.out.println("No. of instances for st3 : " + st3.noOfInstances);

}
}

The output of this variable is given below :

As we can see in the output the same copy of the instance variable is provided to all the objects, no matter how many objects we create.

C:\java>java NonStaticVariable
No. of instances for st1 : 1
No. of instances for st1 : 1
No. of instances for st2 : 1
No. of instances for st1 : 1
No. of instances for st2 : 1
No. of instances for st3 : 1

How to use this keyword in java

The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts. As we can see in the program that we have declare the name of instance variable and local variables same. Now to avoid the confliction between them we use this keyword. Here, this section provides you an example with the complete code of the program for the illustration of how to what is this keyword and how to use it.

In the example, this.length and this.breadth refers to the instance variable length and breadth while length and breadth refers to the arguments passed in the method. We have made a program over this. After going through it you can better understand.

Here is the code of the program:

class Rectangle{
int length,breadth;
void show(int length,int breadth){
this.length=length;
this.breadth=breadth;
}
int calculate(){
return(length*breadth);
}
}
public class UseOfThisOperator{
public static void main(String[] args){
Rectangle rectangle=new Rectangle();
rectangle.show(5,6);
int area = rectangle.calculate();
System.out.println("The area of a Rectangle is : " + area);
}
}

Output of the program is given below:
C:\java>java UseOfThisOperator
The area of a Rectangle is : 30

Matrix Example in Java

In Java tutorial, you will learn about array and matrix. An array is the collection of same data type values. If we create a variable of integer type then, the array of int can only store the int values. It can't store other than int data type.

Matrix: A matrix is a collection of data in rows and columns format.

Description of program:

In this program we are going to implement a matrix. To make a program over the two dimensional array, first of all we have to declare class named as MatrixExample that has one static method outputArray() which takes integer type array and represents it. For displaying the matrix we need to its rows and column by using the array.length method. Now, we use the for loop to print all the values stored in the array. At last use the main() method inside which we are going to declare the values of the multidimensional array which we are going to use. Call the outputArray() method inside the main method. The output will be displayed to the user by println() method.

Here is the code of this Example:

class MatrixExample{
public static void main(String[] args) {
int array[][]= {{1,3,5},{2,4,6}};
System.out.println("Row size= " + array.length);
System.out.println("Column size = " + array[1].length);
outputArray(array);
}

public static void outputArray(int[][] array) {
int rowSize = array.length;
int columnSize = array[0].length;
for(int i = 0; i <= 1; i++) {
System.out.print("[");
for(int j = 0; j <= 2; j++) {
System.out.print(" " + array[i][j]);
}
System.out.println(" ]");
}
System.out.println();
}
}

Multiplication of two Matrix

This is a simple java program that teaches you for multiplying two matrix to each other. Here providing you Java source code with understanding the Java developing application program. We are going to make a simple program that will multiply two matrix. Two dimensional array represents the matrix.

Now, make this program, you have to declare two multidimensional array of type integer. Program uses two for loops to get number of rows and columns by using the array1.length. After getting both matrix then multiply to it. Both matrix will be multiplied to each other by using 'for' loop. So the output will be displayed on the screen command prompt by using the println() method.

Here is the code of this program:

class MatrixMultiply{
public static void main(String[] args) {
int array[][] = {{5,6,7},{4,8,9}};
int array1[][] = {{6,4},{5,7},{1,1}};
int array2[][] = new int[3][3];
int x= array.length;
System.out.println("Matrix 1 : ");
for(int i = 0; i < x; i++) {
for(int j = 0; j <= x; j++) {
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int y= array1.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i < y; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+array1[i][j]);
}
System.out.println();
}

for(int i = 0; i < x; i++) {
for(int j = 0; j < y-1; j++) {
for(int k = 0; k < y; k++){

array2[i][j] += array[i][k]*array1[k][j];
}
}
}
System.out.println("Multiply of both matrix : ");
for(int i = 0; i < x; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+array2[i][j]);
}
System.out.println();
}
}
}

Sum of two Matrix

In this section, we are going to calculate the sum of two matrix and containing its rows and columns. See below for better understanding to this.

In this program we are going to calculate the sum of two matrix. To make this program, we need to declare two dimensional array of type integer. Firstly it calculates the length of the both the arrays. Now we need to make a matrix out of it. To make the matrix we will use the for loop. By making use of the for loop the rows and column will get divide. This process will be performed again for creating the second matrix.

After getting both the matrix with us, we need to sum both the matrix. The both matrix will be added by using the for loop with array[i][j]+array1[i][j]. The output will be displayed by using the println() method.

Here is the code of this program:

class MatrixSum{
public static void main(String[] args) {
int array[][]= {{4,5,6},{6,8,9}};
int array1[][]= {{5,4,6},{5,6,7}};
System.out.println("Number of Row= " + array.length);
System.out.println("Number of Column= " + array[1].length);
int l= array.length;
System.out.println("Matrix 1 : ");
for(int i = 0; i < l; i++) {
for(int j = 0; j <= l; j++) {
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int m= array1.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i < m; i++) {
for(int j = 0; j <= m; j++) {
System.out.print(" "+array1[i][j]);
}
System.out.println();
}
System.out.println("Addition of both matrix : ");
for(int i = 0; i < m; i++) {
for(int j = 0; j <= m; j++) {
System.out.print(" "+(array[i][j]+array1[i][j]));
}
System.out.println();
}
}
}
Output of program:
C:\amar work>javac MatrixSum.java

C:\amar work>java MatrixSum
Number of Row= 2
Number of Column= 3
Matrix 1 :
4 5 6
6 8 9
Matrix 2 :
5 4 6
5 6 7
Addition of both matrix :
9 9 12
11 14 16

length() Method In Java

In this section, you will learn how to use length() method of the String class. We are going to using length() method. These method are illustration as follow here:

Description of program:

Here, we will know that how many character of length in String. First of all, we have to define class named "StringLength". Inside of class we have to define method of class in main class. After that we create one method which returns the integer type values. So we are using to length() method of the String class for the purpose.

length() method : This method return the length of this string as an integer value.

Here is the the code of this program:

import java.io.*;

class StringLength{
public static void main(String[] args){
try{
BufferedReader object=new BufferedReader (new InputStreamReader(System.in));
System.out.println("Eneter string value:");
String s=object.readLine();
int len=s.length();
System.out.println(len);
}
catch(Exception e){}
}
}
Output this program:
C:\java_work>javac StringLength.java
C:\java_work>java StringLength
Eneter string value:
amar
4

toUpperCase() Method In Java

Description of program:

Here, you will see the procedure of converting letters of the string in uppercase letter. So, we are using toUpperCase() method of the String class for the purpose.

The following program convert the string "india" into "INDIA" by using toUpperCase() method.

toUpperCase(): This method returns a string value.

Here is the code of this program:

public class ConvertInUpperCase{
public static void main(String args[]){
String javasefx = "india";
System.out.println("String is : " + javasefx);
String upper = javasefx.toUpperCase();
System.out.println("String in uppercase letter: " + upper);
}
}

Output of program:
C:\java_work>javac ConvertInUpperCase.java

C:\java_work>java ConvertInUpperCase
String is : india
String in uppercase letter: INDIA

charAt() Method In Java

Description of program:

Here, you will understand about the procedure of the charAt() method through the following java program. This program reads a string as input through the keyboard. And first this shows the length of the string then find the character at the 4th (mentioned as a parameter of the method) position of the string that is retrieved by using charAt() method. This method takes a parameter that is the position of the string. The charAt() method returns a character value for the character at the given position of the string.

Here is the code of this program:

import java.io.*;
class CharAt{
public static void main(String[] args){
try{
BufferedReader object=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String");
String s=object.readLine();
int len=s.length();
System.out.println(len);
char char1=s.charAt(4);
System.out.println(char1);
}
catch(Exception e){}
}
Output this program:
C:\java_work>java CharAt
Enter the String
roseindia
9
i

Trim() - Java String Methods

Description of code:

trim():
This method removes the blank spaces from both ends of the given string (Front and End).

Here is the code of program:

import java.lang.*;

public class StringTrim{
public static void main(String[] args) {
System.out.println("String trim example!");
String str = " RoseIndia";
System.out.println("Given String :" + str);
System.out.println("After trim :" +str.trim());
}
}

Simple java program

public class Print{
public static void main(String[] args){
int i=1;
int j;
while(i<=7){
for(j=1;j<=i;j++)
System.out.print("*");
i=i+2;
System.out.println();
}
i=5;
while(i>=1){
for(j=1;j<=i;j++)
System.out.print("*");
i=i-2;
System.out.println();
}
}
}

Answer

Out put of Print.java

*
***
*****
*******
*****
***
*

Tuesday, January 19, 2010

Prime Number in Java

Here is the code of the Program
import java.io.*;

class PrimeNumber {
public static void main(String[] args) throws Exception{
int i;
BufferedReader bf = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter number:");
int num = Integer.parseInt(bf.readLine());
System.out.println("Prime number: ");
for (i=1; i < num; i++ ){
int j;
for (j=2; j<i; j++){
int n = i%j;
if (n==0){
break;
}
}
if(i == j){
System.out.print(" "+i);
}
}
}
}

Find out the prime number

Here is the code program:
class Prime_number {
public static void main(String[] args) {
int num = 11;
int i;
for (i=2; i < num ;i++ ){
int n = num%i;
if (n==0){
System.out.println("not Prime!");
break;
}
}
if(i == num){
System.out.println("Prime number!");
}
}
}

Preparing table of a number by using loop

Here is the code of the prorgram:
class  PreparingTable{
public static void main(String[] args) {
int a=25, b=1;
System.out.println("the table of "+a+"= ");
while(b<=10){
int c = a*b;
System.out.println(c);
b = b+1;
}
}
}

Listing out leap years between certain period

Here is the code of the program:
class leapyears
{
public static void main(String[] args)
{
int i=2006;
int n;
for (n=1990; n<=i ; n++){
int l=n%4;
if (l==0){
System.out.println("leap year: "+n);
}
}
}
}
Download this program.

Checking whether a year is leap or not

Here is the code of program:
class  Leapyear
{
public static void main(String[] args)
{
int n=2000;
if (n%4==0){
System.out.println("The given year is a leap year");
}
else{
System.out.println("This is not a leap year");
}
}
}
Download the program:

Write a program to construct a triangle with the ?*?

Here is the code of the program:
import java.io.*;

class triangle{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
for (int i=1; i<a;i++ ){
for (int j=1; j<=i;j++ ){
System.out.print("*");
}
System.out.println("");
}
}
catch(Exception e){}
}
}
Download the program.

Write a program for calculating area and perimeter of a rectangle

Here is the code of the program:
import java.io.*;
class RecArea
{
public static void main(String[] args)
{

int l=0;
int w=0;

try{

BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter length of rectangle : ");
l = Integer.parseInt(br1.readLine());
System.out.println("Enter width of rectangle : ");
w = Integer.parseInt(br1.readLine());
int area = l*w;
System.out.println("Area of Rectangle : "+area);
int perimiter = 2*(l+w);
System.out.println("Perimeter: " + perimiter);

}catch(Exception e){System.out.println("Error : "+e);}

}
}
Download this example.

Palindrome Number Example in Java

Description of program:

With the help of this program, we are going to determine whether the given number is palindrome or not. To achieve the desired result, firstly we have to define a class named "Palindrome". After that we will ask the user to enter any integer type number and then we will reverse it. After reversing the number we will check whether the given number is palindrome or not. If the given number is larger, then it will display a message "Out of range!".

Here is the code of this program

import java.io.*;

public class Palindrome {
public static void main(String [] args){
try{
BufferedReader object = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter number");
int num= Integer.parseInt(object.readLine());
int n = num;
int rev=0;
System.out.println("Number: ");
System.out.println(" "+ num);
for (int i=0; i<=num; i++){
int r=num%10;
num=num/10;
rev=rev*10+r;
i=0;
}
System.out.println("After reversing the number: "+ " ");
System.out.println(" "+ rev);
if(n == rev){
System.out.print("Number is palindrome!");
}
else{
System.out.println("Number is not palindrome!");
}
}
catch(Exception e){
System.out.println("Out of range!");
}
}
}
Download this example

Website Design by Mayuri Multimedia