Home Blog Page 174

Class Character in Java

0

Share and Enjoy !

Class Character in Java

Character class provides us a value of the primitive type Character(char) in an object. An object of type Character contains a single field whose type is char. Character class provides an immutable object wrapper around the primitive char data type. charValue () returns the char value of a character object.

This class- Character is useful when we need to treat a char value as an object. Several methods take an Object reference as an input. For them, this is the ideal solution. This class also supports the Reflection API and class literals.

In Java, Character objects represent values defined by the Unicode standard. Unicode is defined by an organization called the Unicode Consortium. The defining document for Unicode is The Unicode Standard, Version 2.0 (ISBN 0-201-48345-9).

Several class methods provide the Java/ Unicode equivalent of the C<ctype.h> character macros for checking the type of characters and converting them to uppercase and lowercase letters.

getType() method returns the character type information. The return value is one of the constants defined by the class, which represents several broad Unicode character categories.digit() returns the integer equivalent of a given character for a given radix (eg, radix 16 for hexadecimal). fordigit() returns the character that corresponds to the specified value for the specified radix.

Some of the methods in the Character class are concerned with characters that are digits; these characters are used by several other classes to convert strings that contain numbers into actual numeric values. The digit-related methods all use a radix value to interpret characters.

The radix is the numeric base used to represent numbers as characters or strings. Octal is a radix 8 representation, while hexadecimal is a radix 16 representation. The methods that require a radix parameter use it to determine which characters should be treated as valid digits.

In radix 2, only the characters `0′ and `1′ are valid digits. In radix 16, the characters ‘0’ through ‘9’, ‘a’ through ‘z’, and ‘A’ through ‘Z’ are considered valid digits.

The class Character  is defined as :

public final class java.lang.Character extends java.lang.Object implements java.io.Serializable{
//Member Elements
public final static int MAX_RADIX;
public final static char MAX_VLUE;
public final static int MIN_RADIX;
public final static char MIN_VLUE;
public static final Class TYPE;
//character type constants
public static final byte COMBINING_SPACING _ MARK;
public static final byte CONNECTOR_PUNCTUATION;
public static final byte CONTROL;
public static final byte CURRENCY_SYMBOL;
public static final byte DASH_PUNCTUATION;
public static final byte DECIMAL_DIGIT_NUMBER;
public static final byte ENCLOSING_MARK;
public static final byte END PUNCTUATION;
public static final byte FORMAT;
public static final byte LETTER_NUMBER;
public static final byte LINE_SEPARATOR;
public static final byte LOWERCASE_LETTER;
public static final byte MATH_SYMBOL;
public static final byte MODIFIER_LETTER;
public static final byte MODIFIER_SYMBOL;
public static final byte NON_SPACING_MARK;
public static final byte OTHER_LETTER;
public static final byte OTHER_NUMBER;
public static final byte OTHER_PUNCTUATION;
public static final byte OTHER_SYMBOL;
public static final byte PARAGRAPH_SEPARATOR;
public static final byte PRIVATE_USE;
public static final byte SPACE_SEPARATOR;
public static final byte START_PUNCTUATION
public static final byte SURROGATE;
public static final byte TITLECASE_LETTER;
public static final byte UNASSIGNED;
public static final byte UPPERCASE_LETTER;
//constructor
public character(Char value)
//Methods:
public char charValue();
public static int digit(char ch,int redix);
public boolean equals(Object obj);
public static char forDigit(int digit,int redix);
public int hashCode();
public static char toLowerCase(char ch);
public static char toTtleCase(char ch);
public static char toUpperCase(char ch);
public String toString();
public static boolean isDefined(char ch);
public static boolean isDigit(char ch);
public static boolean isJavaLetter(char ch);
public static boolean isJavaLetterorDigit(char ch);
public static boolean isLetter(char ch);
public static boolean isLetterorDigit(char ch);
public static boolean isLowerCase(char ch);
public static boolean isSpace(char ch);
public static boolean isTitleCase(char ch);
public static boolean isUpperCase(char ch);
public static int getNumericValue(char ch);
public static int getType(char ch);
public static boolean isISOControl(char ch):
public static boolean isIdentifierIgnorable(char ch);
public static boolean isJavaIdentifierPart(char ch);
public static boolean isJavaIdentifierStart(char ch);
public static boolean isSpaceChar(char ch);
public static boolean isUnicodeIdentifierPart(char ch);
public static boolean isUnicodeIdentifierStart(char ch);
public static boolean isWhitespace(char ch);
}
 

The details of these are given as:

public final static int MAX_RADIX;

The constant value of this field is the largest value(36) permitted for the radix argument in the radix conversion method such as the digit method, the forDigit() method and the toString() method of the class Integer.

public final static char MAX_VLUE;

The constant value of this field is the largest value like-‘uffff’ for type char

public final static int MIN_RADIX;

The constant value of this field is the smallest value permitted for the radix argument in the radix conversion method such as the digit method, the forDigit() method and the toString() method of the class Integer.

public final static char MIN_VLUE;

The constant value of this field is the smallest value like-‘u0000’ for type char

public static final Class TYPE;

The Class object that represents the type char. It is always true that Character.TYPE == char.class.

public static final byte COMBINING_SPACING _ MARK;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte CONNECTOR_PUNCTUATION;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte CONTROL;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte CURRENCY_SYMBOL;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte DASH_PUNCTUATION;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte DECIMAL_DIGIT_NUMBER;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte ENCLOSING_MARK;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte END PUNCTUATION;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte FORMAT;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte LETTER_NUMBER;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte LINE_SEPARATOR;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte LOWERCASE_LETTER;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte MATH_SYMBOL;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte MODIFIER_LETTER;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte MODIFIER_SYMBOL;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte NON_SPACING_MARK;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte OTHER_LETTER;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte OTHER_NUMBER;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte OTHER_PUNCTUATION;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte OTHER_SYMBOL;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte PARAGRAPH_SEPARATOR;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte PRIVATE_USE;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte SPACE_SEPARATOR;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte START_PUNCTUATION

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte SURROGATE;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte TITLECASE_LETTER;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte UNASSIGNED;

This constant can be returned by the getType() method as the general category of a Unicode character.

public static final byte UPPERCASE_LETTER;

This constant can be returned by the getType() method as the general category of a Unicode character.

public character(Char value)

Creates a character object and initializes it so that it can represent the value passed in the argument. The argument char value will be encapsulated by this object.

public char charValue();

charValue() method returns the char value contained by the object.

public static int digit(char ch,int redix);

This method returns the numeric value represented by a digit character. For example, digit(‘7’,10) returns 7. If the value of ch is not a valid digit, the method returns -1. For example, digit(‘7’,2) returns -1 because ‘7’ is not a valid digit in radix 2.

Several methods in other classes use this method to convert strings that contain numbers to actual numeric values. The forDigit() method is an approximate inverse of this method.

If radix is greater than 10, characters in the range `A’ to ‘A’+radix-11 are treated as valid digits. Such a character has the numeric value ch-‘A’+10. By the same token, if the radix is greater than 10, characters in the range ‘a’ to ‘a’+radix-11 are treated as valid digits. Such a character has the numeric value ch-‘a’+10.

This method returns the numeric value of the digit. This method returns -1 if the value of ch is not considered a valid digit, if the radix is less than MIN_RADIX, or if the radix is greater than MAX_RADIX.

Parameters

ch– A char value that is a legal digit in the given radix.
radix– The radix used in interpreting the specified character as a digit. If radix is in the range 2 through 10, only characters for which the isDigit() method returns true are considered to be valid digits. If radix is in the range 11 through 36, characters in the ranges ‘A’ through ‘Z’ and ‘a’ through ‘z’ may be considered valid digits.

public boolean equals(Object obj);

equals() method returns true if obj is an instance of Character, and it contains the same value as the object this method is associated with. It overrides Object.equals() method. It returns true if the objects are equal; false if they are not.
Parameter-The object to be compared with this object.

public static char forDigit(int digit,int redix);

This method returns the character that represents the digit corresponding to the specified numeric value. If the digit is in the range 0 through 9, the method returns ‘0’+digit. If the digit is in the range 10 through MAX_RADIX-1, the method returns ‘a’+digit-10. The method returns ‘\ 0’ if the digit is less than 0, if the digit is equal to or greater than radix, if the radix is less than MIN_RADIX, or if the radix is greater than MAX_RADIX.

This method returns the character that represents the digit corresponding to the specified numeric value. The method returns ‘\0’ if the digit is less than 0, if the digit is equal to or greater than radix, if the radix is less than MIN_RADIX, or if the radix is greater than MAX_RADIX.
Parameters
digit– The numeric value represented as a digit character.
radix– The radix used to represent the specified value.

public int hashCode();

hashCode() method returns a hashcode based on the char value of the object. It overrides Object.hashCode() method.

public static char toLowerCase(char ch);

toLowerCase() method returns the lowercase equivalent of the specified character value. If the specified character is not uppercase or if it has no lowercase equivalent, the character is returned unmodified. The Unicode attribute table determines if a character has a mapping to a lowercase equivalent.

Some Unicode characters in the range \u2000 through \u2FFF have lowercase mappings. For example,\u2160 (Roman numeral one) has a lowercase mapping to \u2170 (small Roman numeral one). The toLowerCase() method maps such characters to their lowercase equivalents even though the method isUpperCase() does not return true for such characters.

This method returns The lowercase equivalent of the specified character, or the character itself if it cannot be converted to lowercase

Parameters
ch -A char value

public static char toTtleCase(char ch);

toTtleCase() method returns the titlecase equivalent of the specified character value. If the specified character has no titlecase equivalent, the character is returned unmodified. The Unicode attribute table is used to determine the character’s titlecase equivalent.

Many characters are defined by the Unicode standard as having upper- and lowercase forms. There are some characters defined by the Unicode standard that also have a titlecase form. The glyphs for these characters look like a combination of two Latin letters.

The titlecase form of these characters has a glyph that looks like a combination of an uppercase Latin character and a lowercase Latin character; this case should be used when the character appears as the first character of a word in a title.

For example, one of the Unicode characters that have a titlecase form like the letter ‘D’ followed by the letter ‘Z’. Here is what the three forms of this letter look like:

CharacterMeaning
Uppercase‘DZ’
Titlecase‘Dz’
Lowercase‘dz’

 

This method returns the titlecase equivalent of the specified character, or the character itself if it cannot be converted to titlecase.

Parameters
ch- A char value

public static char toUpperCase(char ch);

toUpperCase() method returns the uppercase equivalent of the specified character value. If the specified character is not lowercase or if it has no uppercase equivalent, the character is returned unmodified. The Unicode attribute table determines if a character has a mapping to an uppercase equivalent.

Some Unicode characters in the range \u2000 through \u2FFF have uppercase mappings. For example, \u2170 (small Roman numeral one) has a lowercase mapping to \u2160 (Roman numeral one). The toUpperCase() method maps such characters to their uppercase equivalents even though the method isLowerCase() does not return true for such characters.

This method returns the uppercase equivalent of the specified character, or the character itself if it cannot be converted to uppercase.
Parameters
ch -A char value

public String toString();

toString() method returns a string representation of the Character object. hence it returns a String of length one that contains the character value of the object. It overrides Object.toString() method.
Parameters
ch- A char value

public static boolean isDefined(char ch);

is definedisDefined method returns true if the specified character value has an assigned meaning in the Unicode character set. It returns true if the specified character has an assigned meaning in the Unicode character set; otherwise false.
Parameters
ch -A char value that needs to be examined.

public static boolean isDigit(char ch);

isDigit() method determines whether or not the specified character is a digit, based on the definition of the character in Unicode. It returns true if the specified character is defined as a digit in the Unicode character set; otherwise false.
Parameters
ch -A char value

public static boolean isJavaLetter(char ch);

isJavaLetter() method returns true if the specified character can appear as the first character in a Java identifier.

A character is considered a Java letter if and only if it is a letter, the character $, or the character _.

This method returns false for digits because digits are not allowed as the first character of an identifier.
This method returns true if the specified character can appear as the first character in a Java identifier; otherwise false.
Parameters
ch -A char value

public static boolean isJavaLetterorDigit(char ch);

isJavaLetterorDigit() method returns true if the specified character can appear in a Java identifier after the first character.
A character is considered a Java letter or digit if and only if it is a letter, a digit, the character $, or the character _.
This method returns true if the specified character can appear after the first character in a Java identifier; otherwise false.
Parameters
ch -A char value

public static boolean isLetter(char ch);

isLetter() method determines whether or not the specified character is a letter, based on the definition of the
character in Unicode. This method does not consider character values in ranges that have not been assigned meanings by Unicode to be letters.
This method returns true if the specified character is defined as a letter in the Unicode character set; otherwise false.
Parameters
ch- A char value

public static boolean isLetterorDigit(char ch);

isLetterorDigit() method determines whether or not the specified character is a letter or a digit, based on the definition of the character in Unicode.

There are some ranges that have not been assigned meanings by Unicode. If a character value is in one of these ranges, this method does not consider the character to be a letter.

This method returns true if the specified character is defined as a letter in the Unicode character set; otherwise false.
Parameters
ch -A char value

public static boolean isLowerCase(char ch);

isLowerCase() method determines whether or not the specified character is lowercase. Unicode defines a number of characters that do not have case mappings; if the specified character is one of these characters, the method returns false.

This method returns true if the specified character is defined as lowercase in the Unicode character set; otherwise false.

Parameters
ch -A char value

public static boolean isSpace(char ch);

isSpace() method determines whether or not the specified character is whitespace. This method recognizes the whitespace characters shown in the following table.

CharacterMeaning
\u0009Horizontal tab
\u000ANewline
\u000CFormfeed
\u000DCarriage return
\u0020” space

This method returns true if the specified character is defined as whitespace in the ISO-Latin-1 character set; otherwise false.
Parameters
ch- A char value

public static boolean isTitleCase(char ch);

isTitleCase() method determines whether or not the specified character is a titlecase character. Unicode defines a number of characters that do not have case mappings; if the specified character is one of these characters, the method returns false.

Many characters are defined by the Unicode standard as having upper- and lowercase forms. There are some characters defined by the Unicode standard that also have a titlecase form. The glyphs for these characters look like a combination of two Latin letters.

The titlecase form of these characters has a glyph that looks like a combination of an uppercase Latin character and a lowercase Latin character; this case should be used when the character appears as the first character of a word in a title.

For example, one of the Unicode characters that have a titlecase form looks like the letter ‘D’ followed by the letter ‘Z’. Here is what the three forms of this letter look like:

CharacterMeaning
Uppercase‘DZ’
Titlecase‘Dz’
Lowercase‘dz’

Parameters
ch -A char value

public static boolean isUpperCase(char ch);

isUpperCase() method determines whether or not the specified character is uppercase. Unicode defines a number of characters that do not have case mappings; if the specified character is one of these characters, the method returns false.

This method returns true if the specified character is defined as uppercase in the Unicode character set; otherwise false.

Parameters
ch -A char value

public static int getNumericValue(char ch);

getNumericValue() method returns the Unicode numeric value of the specified character as a non-negative integer.
It returns the Unicode numeric value of the character as a non-negative integer. This method returns -1 if the character has no numeric value; it returns -2 if the character has a numeric value that is not a nonnegative integer, such as 1/2.
Parameters
ch A char value

public static int getType(char ch);

getType This method returns the Unicode general category type of the specified character. The value corresponds to one of the general category constants defined by Character.

This method returns An int value that represents the Unicode general category type of the character.

Parameters
ch – A char value

public static boolean isISOControl(char ch):

isISOControl() method determines whether or not the specified character is an ISO control character. A character is an ISO control character if it falls in the range \u0000 through \u001F or \u007F through \u009F.

This method returns true if the specified character is an ISO control character; otherwise false.
Parameters
ch- A char value

public static boolean isIdentifierIgnorable(char ch);

isIdentifierIgnorable() method determines whether or not the specified character is ignorable in a Java or Unicode identifier.The following characters are ignorable in a Java or Unicode identifier:

CharacterMeaning
\u0000 – \u0008 \u000E – \u001B \u007F – \u009FISO control characters that aren’t whitespace
\u200C – \u200FJoin controls
\u200A – \u200EBidirectional controls
\u206A – \u206FFormat controls
\uFEFFZero-width no-break space

This method returns true if the specified character is ignorable in a Java or Unicode identifier; otherwise false.

Parameters
ch A char value

public static boolean isJavaIdentifierPart(char ch);

isJavaIdentifierPart() method returns true if the specified character can appear in a Java identifier after the first character.
A character is considered part of a Java identifier if and only if it is a letter, a digit, a currency symbol (e.g. $), a connecting punctuation character (e.g.  _), a numeric letter (e.g. a Roman numeral), a combining mark, a nonspacing mark, or an ignorable control character.

This method returns true if the specified character can appear after the first character in a Java identifier; otherwise false.
Parameters
ch A char value

public static boolean isJavaIdentifierStart(char ch);

isJavaIdentifierStart() method returns true if the specified character can appear in a Java identifier as the first character.

A character is considered a start of a Java identifier if and only if it is a letter, a currency symbol (e.g., $), or a connecting punctuation character (e.g., _).

It returns true if the specified character can appear as the first character in a Java identifier; otherwise false.

Parameters
ch A char value

public static boolean isSpaceChar(char ch);

isSpaceChar() method determines if the specified character is a space character according to the Unicode 2.0 specification. A character is considered to be a Unicode space character if and only if it has a general category “Zs”, “Zl”, or “Zp” in the Unicode specification.

This method returns true if the specified character is a Unicode 2.0 space characters; otherwise false.

Parameters
ch A char value

public static boolean isUnicodeIdentifierPart(char ch);

isUnicodeIdentifierPart() method returns true if the specified character can appear in a Unicode identifier after the first character.

A character is considered part of a Unicode identifier if and only if it is a letter, a digit, a connecting punctuation character (e.g., _), a numeric letter (e.g., a Roman numeral), a combining mark, a nonspacing mark, or an ignorable control character.

This method returns true if the specified character can appear after the first character in a Unicode identifier; otherwise false.
Parameters
ch A char value

public static boolean isUnicodeIdentifierStart(char ch);

isUnicodeIdentifierStart method returns true if the specified character can appear in a Unicode identifier as the first character.

A character is considered the start of a Unicode identifier if and only if it is a letter.

This method returns true if the specified character can appear as the first character in a Unicode identifier; otherwise false.

Parameters
ch A char value

public static boolean isWhitespace(char ch);

isWhitespace() method This method determines whether or not the specified character is whitespace. This method recognizes the following as whitespace

CharacterMeaning
Unicode category “Zs” except \u00A0 and \uFEFFUnicode space separators except for no-break spaces
Unicode category “Zl”Unicode line separators
Unicode category “Zp”Unicode paragraph separators
\u0009Horizontal tab
\u000ALinefeed
\u000BVertical tab
\u000CFormfeed
\u000DCarriage return
\u001CFile Separator
\u001DGroup Separator
\u001ERecord Separator
\u001FUnit Separator

This method returns true if the specified character is defined as whitespace according to Java; otherwise false.

Parameters
ch A char value
Apart from these methods this class also has other inherited methods from class Object. They are as follows:

  • clone()
  • getClass()
  • notifyAll()
  • finalize()
  • notify()
  • wait(long)
  • wait()
  • wait(long, int)

Share and Enjoy !

Vector Class Simplified in Java

0

Share and Enjoy !

Vector Class Simplified in Java

In general, the quantity of creating new objects is only known during runtime. Since we don’t know it during compile time, we can not create named handle like an array. To create dynamic and hold objects java provides container classes like a vector.

The Vector class implements a variable-length array that can hold any kind of object. Like an array, the elements in a Vector are accessed with an integer index. However, unlike an array, the size of a Vector can grow and shrink as needed to accommodate a changing number of objects. Vector provides methods to add and remove elements, as well as ways to search for objects in a Vector and iterate through all of the objects.

The Vector class implements grow-able array objects like ArrayList but for objects. Like Array, it contains components that can be accessed using an integer index. With vector, we can create a generic dynamic array that can hold objects of any type and any number.

The size of a Vector can grow or shrink as needed to accommodate additions of items and removal of items. Each Vector tries to optimize storage management by maintaining the capacity and capacity increment. The capacity is always at least as large as the Vector size. It is in general larger because as components are added to Vector, the Vector’s storage increases in chunks(equal to the size of the capacity increment).

The initial capacity of a Vector specifies how many objects it can contain before more space must be allocated. The capacity increment specifies how much more space is allocated each time the Vector needs to increase its capacity. We can fine-tune the performance of a Vector by adjusting the initial capacity and capacity increment.

An application can increase the capacity of a vector before increasing a large number of components. This phenomenon reduces the amount of incremental reallocation.

The structure of the Vector Class is given as :

public class java.util.Vector extends java.lang.Object implements java.lang.Cloneable,java.io.Serializable{
//Member elements:
protected int capacityIncrement;
protected int incrementCount;// the number of valid components in the vector
protected Object elementData[];//the array buffer into which the components of the vector are stored.the length of this array buffer is the current capacity of the vector.
//Constructors:
public Vector();//creates an empty vector
public Vector(int initialCapacity);//creates an empty vector with the initial capacity provided
public Vector(int initialCapacity,int capacityIncrement);//creates an empty vector with the initial capacity and capacity increment provided.
//Methods:
public final synchronized void addElement(Object obj);//adds the element obj at the end of the vector object and increment the size by 1.
public final synchronized void copyInto(Object anArray[]);//copies all elements from a vector to Array
public final synchronized void ensureCapacity(int minCapacity);//Sets the specified minimum capacity to the size of the Vector.
public final synchronized void insertElementAt(Object obj,int index);//inserts the specified element at the given index of the vector
public final synchronized void removeAllElements();//removes all elements from the vector
public final synchronized void removeElementAt(int index);//removes the element object present in the index location from the vector.Index must be in between 0 to size-1
public final synchronized void setSize(int newSize);//sets the size of the vector.If there were more than newSize elements in the vector, the extra elements are removed. If there were fewer elements in the vector the remaining spaces are filled with null.
public final synchronized void setElementAt(Object obj,int index);//Replaces the element at the specified index with specified element.
public final int capacity();//returns the current capacity of the Vector
public final int indexOf(Object element);
public final synchronized int indexOf(Object element,int index);
public final int lastIndexOf(Object element);
public final synchronized int lastIndexOf(Object element,int index);
public final int size();//returns the size of the vector.
public final synchronized Object elementAt(int index);//returns the element object present in the index of the vector.
public final synchronized Object firstElement();//returns the first element of the vector
public final synchronized Object lastElement();//returns the last element of the vector
public final synchronized void trimToSize();
public final boolean isEmpty(); //checks if the vector is empty.If it empty returns true else return false
public final synchronized boolean removeElement(Object obj); //removes the specified item from the vector
public final boolean contains(Object element);//returns true if the specified object is present in the Vector.
public final boolean contains(Collection c);//returns true if all the elements are present in the specified collection in the vector.
public final Object get(int index);//Returns the object which is available in the specified index.
public synchronized Object clone();
public final synchronized Enumeration element();
public final synchronized String toString();//returns a String representation of the Vector.
} 

The details of the class structure are given as follows:

protected int capacityIncrement;

protected int capacityIncrement represents the amount by which the internal array grows when more space is needed. If the value is 0, the internal array doubles in size when more space is needed.

protected int elementCount;

protected int elementCount represents the count of how many objects are contained in this Vector.

protected Object[] elementData;

protected Object[] elementData represents the array that holds the contents of this Vector.

public Vector();

public Vector() constructor creates an empty Vector with the default capacity of 10 and the default capacity increment of 0.

public Vector(int initialCapacity);

public Vector(int initialCapacity) constructor creates an empty Vector with the given capacity and the default capacity increment of 0.

Parameter
initialCapacity – The initial capacity of the Vector.

public Vector(int initialCapacity, int capacityIncrement);

public Vector(int initialCapacity, int capacityIncrement) constructor creates an empty Vector with the given capacity and capacity increment.

Parameter
initialCapacity – The initial capacity of the Vector.
CapacityIncrement – The amount to increase the capacity when more space is needed.

public final synchronized void addElement(Object obj);

public final synchronized void addElement(Object obj) method adds the given object to this Vector as its last element and increases its size by 1. The capacity of the Vector is increased if its size becomes greater than its capacity. Any kind of object can be added to a Vector.

Parameter
obj – The object to be added.

public final int capacity();

public final int capacity() method returns the size of the internal array of this Vector.

This method returns The capacity of this Vector.

public synchronized Object clone();

public synchronized Object clone() method creates a copy of this Vector and returns it.

This method returns A copy of this Vector.

public final boolean contains(Object elem);

public final boolean contains(Object elem) method determines whether or not the given object is contained in this Vector.

This method returns true if the given object is contained in this Vector; false otherwise.

Parameter
elem – The object to be found.

public final synchronized void copyInto(Object[] anArray);

public final synchronized void copyInto(Object[] anArray) method copies the object references in this Vector to the given array.

Parameter
anArray – The array to be filled.

public final synchronized Object elementAt(int index);

public final synchronized Object elementAt(int index) method returns the object at the given index in this Vector.

This method returns the object at the position given by the index.

Parameter
index – The index of the object to be returned.

public final synchronized Enumeration elements();

public final synchronized Enumeration elements() method returns an Enumeration that iterates through the objects in this Vector.

This method returns The objects in this Vector as an Enumeration.

public final synchronized void ensureCapacity(int minCapacity);

public final synchronized void ensureCapacity(int minCapacity) method expands the internal array, if necessary, to make the capacity of the Vector at least minCapacity.

Parameter
minCapacity – The minimum new capacity.

public final synchronized Object firstElement();

public final synchronized Object firstElement() method returns the object at index 0 in this Vector.

This method returns the first object in this Vector.

public final int indexOf(Object elem);

public final int indexOf(Object elem) method returns the index of the first occurrence of the given object in this Vector.

This method returns the index of the given object or -1 if it cannot be found.

Parameter
elem – The object to be found.

public final synchronized int indexOf(Object elem, int index);

public final synchronized int indexOf(Object elem, int index) method returns the index of the next occurrence of the given object in this Vector after the given index.

This method returns the index of the next occurrence of the given object after the specified index or -1 if it cannot be found.

Parameter
elem – The object to be found.
index – The starting index.

public final synchronized void insertElementAt(Object obj, int index);

public final synchronized void insertElementAt(Object obj, int index) method inserts the given object at the given index in this Vector. Each object in the Vector with an index greater than or equal to index is shifted upward in the Vector, so that it has an index of one greater than it did previously.

Parameter
obj – The object to be inserted.
index – The index at which to insert the object.

public final boolean isEmpty();

public final boolean isEmpty() method returns a boolean value that indicates whether or not the Vector is empty.

This method returns true if there are no objects in the Vector; false otherwise.

public final synchronized Object lastElement();

public final synchronized Object lastElement() method returns the last object in this Vector.

This method returns the last object in this Vector.

public final int lastIndexOf(Object elem);

public final int lastIndexOf(Object elem) method returns the index of the last occurrence of the given object in this Vector.

This method returns the index of the given object or -1 if it cannot be found.

Parameter
elem – The object to be found.

public final synchronized int lastIndexOf(Object elem, int index);

public final synchronized int lastIndexOf(Object elem, int index) method returns the index of the last occurrence of the given object in this Vector before the given index. In other words, the method searches backwards from index for the next occurrence.

This method returns the index of the last occurrence of the given object before the specified index or -1 if it cannot be found.

Parameter
elem – The object to be found.
index – The starting index.

public final synchronized void removeAllElements();

public final synchronized void removeAllElements() method removes all of the objects from this Vector, but does not change its capacity or capacity increment.

public final synchronized boolean removeElement(Object obj);

public final synchronized boolean removeElement(Object obj) method searches for the first occurrence of the given object in this Vector and removes it. If the object is found, each object in the Vector with an index greater than or equal to the index of the removed object is shifted downward in the Vector, so that it has an index of one less than it did previously.

This method returns true if the given object is found and removed; false otherwise.

Parameter
obj – The object to be removed.

public final synchronized void removeElementAt(int index);

public final synchronized void removeElementAt(int index) method removes the object at the given index from this Vector. Each object in the Vector with an index greater than or equal to index is shifted downward in the Vector, so that it has an index of one less than it did previously.

Parameter
index – The index of the object to be removed.

public final synchronized void setElementAt(Object obj, int index);

public final synchronized void setElementAt(Object obj, int index) method puts the given object at the given index in this Vector, replacing the object that was previously there.

Parameter
obj – The object to be put in the Vector.
index – The index at which to put the object.

public final synchronized void setSize(int newSize);

public final synchronized void setSize(int newSize) method sets the size (not the capacity) of this Vector. If the new size is bigger than the current size, null elements are added to the end of the Vector. If the new size is smaller than the current size, elements are discarded from index newSize to the end of the Vector.

Parameter
newSize – The new size.

public final int size();

public final int size() method returns the number of objects contained in this Vector.

This method returns the size of this Vector.

public final synchronized String toString();

public final synchronized String toString() method returns a string representation of this Vector. The string includes every object that is contained in the Vector, so the string returned by toString() can be quite long.

This method returns a string that represents this Vector.

public final synchronized void trimToSize();

public final synchronized void trimToSize() method sets the capacity of this Vector equal to its size. We can use this method to minimize the storage space used by the Vector, but any subsequent calls to addElement() or insertElement() forces the Vector to allocate more space.

Apart from these Vector class also has inherited methods from class- Object. They are as follows:

  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)
To overcome a size issue of the array the best alternative is to create and use Vector. Once it reaches the limit, we run out of space and we create a new array and copy the content from the old array to the new array. The vector class does the same. Since it gives size flexibility, a vector is less efficient than an array in terms of time.

The way we can create vectors are as follows:


Vector myVector1=new Vector();
Vector myVector2=new Vector(5);
 

A vector declared without specifying size can accommodate an unknown number of items in it. Even if the size is specified we can add different items beyond the size of the vector.

A vector is an unbounded Array but we can put any kind of objects into a vector using addElement() method and fetch using elementAt() method.It is effective when we don’t know in Advance what size our array will become.

An example of Vector class is given below:

 


//create a vector
Vector myFruits=new Vector();
//add elements to vector
myFruits.addElement("Banana");
myFruits.addElement("Apple");
myFruits.addElement("Grape");
//get elements from vector
String value=(String)myFruits.elementAt(i);
i belongs to 0 to myFruits.Size()-1
//or
Iterator it=myFruits.iterator();
while(it.hashNext())
{
System.out.println(it.next());
}
 

Advantage:

  1. It is very convenient to use and put standard objects into a container.
  2. A vector can be used to a list of objects (they may vary in size).
  3. We can add and delete objects from the Vector as and when required.

 

Disadvantage:

  1. Vector can not directly store simple data type , we can store only objects so we need to convert the data type into Objects before storing them.
  2. As in one place we insert objects and in other part of the code we get the objects from the Vector,it is very tough to determine if a bad object is inserted into the Vector.And we we only know the bad type of object in form of an exception.This makes the code very painful to find of issues and bug prone.
  3. We need to do the object casting to the appropriate type before working with them
Vector,stack,hashtable all deal with the Objects as if they had no specific type(they treat them as type Object,the root class of all classes in java). This works fine from one standpoint: we need to build only one container and java objects will go into the container.(Except primitives, we need Wrapper classes for that).

Here is an example how Vector can create issue while holding different data types into it:


class Pen{
private int penNumber;
Pen(int i)
{
penNumber=i;
}
void print(){
System.out.println("Pen #"+penNumber);
}
}
class Pencil{
private int pencilNumber;
Pencil(int i)
{
pencilNumber=i;
}
void print(){
System.out.println("Pencil#"+pencilNumber);
}
}
public class PenPencilTest{
public static void main(String args[])
{

Vector pens=new Vector();
//insert elements in the vector
for(int j=0;j<10;j++)
pens.addElement(new Pen(j));
pens.addElement(new Pencil(10));
//get elements from vector
for(int k=0;kj<pens.size;k++)
((pens)pens.elementAt(k)).print();
//Pencil is detected at runtime
}
}

Classes Pen and Pencil are distinct,they have nothing common other than the fact that they both are objects.(If we don’t say from which class they are inherited from automatically they inherit from Object).As vector class can hold Objects so we can put Pencil into the Pen vector.
Now using elementAt(index) method ,we get back a handle to an Object which we need to cast to appropriate type Pen or Pencil by putting in a cast expression (type) before calling a method.Otherwise we will get a syntax error. Again in the run time as wrong casting has happened to Pencil (we tried to cast to Pen), we will get an exception.

Share and Enjoy !

Class ThreadGroup in Java

0

Share and Enjoy !

Class ThreadGroup in Java:

A ThreadGroup is a set or collection of threads. We can include different threads and ThreadGroups in a single ThreadGroup. so a ThreadGroup can contain several threads and ThreadGroups as its member elements. In that case, it will form a tree structure popularly known as the thread tree.

In the thread tree, every thread and ThreadGroup will have a parent except the initial ThreadGroup.A thread can access it’s own ThreadGroup but not other ThreadGroup. We can perform operations on the group as a whole instead of individual threads. ThreadGroups are mainly applicable to system-level applications.

In java, there is a default ThreadGroup called SystemThreadGroup. When a java application is started, the java runtime creates the main thread group as a member of SystemThreadGroup. The main thread is created in the main thread group to run the main() method of the application.

Every thread instance is a member of exactly one thread group. By default, all new threads and thread groups created when objects are instantiated will become the member of the main thread group. All threads in an application will form a tree with the SystemThreadGroup as root.

The structure of the ThreadGroup class is as follows:

public class java.lang.ThreadGroup extends java.lang.Object{
//constructors
public ThreadGroup(String name)//constructs a new ThreadGroup whose parent is the ThreadGroup of the currently running thread.
public ThreadGroup(ThreadGroup parent,String name);//constructs a ThreadGroup whose parent is provided in the argument and it can throw NullPointerException if the ThreadGroup argument is null. It can also throw SecurityException if the current thread can not create a thread in the specified ThreadGroup.
//Methods:
public int activeCount();
public int activeGroupCount();
public final void checkAccess();
public final void destroy();
public int enumerate(Thread list[]);
public int enumerate(Thread list[],boolean recurse);
public int enumerate(ThreadGroup list[]);
public int enumerate(ThreadGroup list[],boolean recurse);
public final void resume();
public final void setDeamon(boolean deamon);
public final void setMaxPriority(int priority);
public final void stop();
public final void suspend();
public final int getMaxPriority();
public final String getName();
public final ThreadGroup getParent();
public final boolean isDeamon();
public boolean allowThreadSuspension(boolean b);
public synchronized boolean isDestroyed();
public void list();
public final boolean parentOf(ThreadGroup group);
public void UncaughtException(Thread t,Throwable e);
public String toString();
} 

The details of the ThreadGroup is given as:

public ThreadGroup(String name);

public ThreadGroup(String name) constructor creates a ThreadGroup object that has the specified name and the same parent ThreadGroup as the current thread.
Parameter
name -The name of this ThreadGroup object.

public ThreadGroup(ThreadGroup parent, String name;

public ThreadGroup(ThreadGroup parent, String name) constructor creates a ThreadGroup object with the specified name and parent ThreadGroup object.
Parameter
parent -The ThreadGroup object that this ThreadGroup object is to be added to.
name – The name of this ThreadGroup object.

public int activeCount();

public int activeCount() method returns an approximation of the number of threads that belong to this ThreadGroup object and any child ThreadGroup objects. The count is approximate because a thread can die after it is counted, but before the complete count is returned. Also, after a child, ThreadGroup is counted but before the total count is returned, additional Thread and ThreadGroup objects can be added to a child ThreadGroup.

This method returns an approximation of the current number of threads in this ThreadGroup object and any child ThreadGroup objects.

public int activeGroupCount();

public int activeGroupCount() method returns an approximation of the number of child ThreadGroup objects that belong to this ThreadGroup object. The count is approximate because after a child ThreadGroup is counted but before the total count is returned, additional ThreadGroup objects can be added to a child ThreadGroup.

This method returns an approximation of the current number of child ThreadGroup objects in this ThreadGroup object.

public boolean allowThreadSuspension(boolean b); 

public boolean allowThreadSuspension(boolean b); method specifies whether or not the Java virtual machine is allowed to suspend threads due to low memory.

This method returns the boolean value true.

Parameter
b – A boolean value that specifies whether or not the run-time system is allowed to suspend
threads due to low memory.

public final void checkAccess();

public final void checkAccess() method determines if the currently running thread has permission to modify this ThreadGroup object.

public final void destroy();

public final void destroy() method destroys this ThreadGroup object and any child ThreadGroup objects. The ThreadGroup must not contain any Thread objects. This method also removes the ThreadGroup object from its parent ThreadGroup object.

public int enumerate(Thread list[]);

public int enumerate(Thread list[]) method stores a reference in the array for each of the Thread objects that belongs to this ThreadGroup or any of its child ThreadGroup objects.
If the array is not big enough to contain references to all the Thread objects, only as many
references, as will fit, are put into the array.

No indication is given that some Thread objects were left out, so it is a good idea to call activeCount() before calling this method, to get an idea of how large to make the array.

This method returns the number of Thread objects stored in the array.

Parameter
list – A reference to an array of Thread objects.

public int enumerate(Thread list[], boolean recurse);

public int enumerate(Thread list[], boolean recurse) method stores a reference in the array for each of the Thread objects that belong to this ThreadGroup object. If recurse is true, the method also stores a reference for each of the Thread objects that belongs to a child ThreadGroup object of this ThreadGroup.

If the array is not big enough to contain references to all the Thread objects, only as many
references as will fit are put into the array. No indication is given that some Thread objects were left out, so it is a good idea to call activeCount() before calling this method, to get an idea of how large to make the array.

This method returns the number of Thread objects stored in the array.
Parameter
list – A reference to an array of Thread objects.
recurse – A boolean value that specifies whether or not to include Thread objects that belong to child ThreadGroup objects of this ThreadGroup object.

public int enumerate(ThreadGroup list[]);

public int enumerate(ThreadGroup list[]) method stores a reference in the array for each ThreadGroup object that belongs to this ThreadGroup or any of its child ThreadGroup objects.

If the array is not big enough to contain references to all the ThreadGroup objects, only as many references as will fit are put into the array. No indication is given that some ThreadGroup objects were left out, so it is a good idea to call activeGroupCount() before calling this method, to get an idea of how large to make the array.

This method returns the number of ThreadGroup objects stored in the array.
Parameter
list – A reference to an array of ThreadGroup objects.

public int enumerate(ThreadGroup list[], boolean recurse);

public int enumerate(ThreadGroup list[], boolean recurse) method stores a reference in the array for each of the ThreadGroup objects that belong to this ThreadGroup object. If recurse is true, the method also stores a reference for each of the ThreadGroup objects that belongs to a child ThreadGroup object of this ThreadGroup.

If the array is not big enough to contain references to all the ThreadGroup objects, only as many references as will fit are put into the array. No indication is given that some ThreadGroup objects were left out, so it is a good idea to call activeGroupCount() before calling this method, to get an idea of how large to make the array.

This method returns the number of ThreadGroup objects stored in the array.

Parameter
list – A reference to an array of ThreadGroup objects.
recurse – A boolean value that specifies whether or not to include ThreadGroup objects that belong
to child ThreadGroup objects of this ThreadGroup object.

public final int getMaxPriority();

public final int getMaxPriority() method returns the maximum priority that can be assigned to Thread objects that belong to this ThreadGroup object.

It is possible for a ThreadGroup to contain Thread objects that have higher priorities than this
maximum, if they were given that higher priority before the maximum was set to a lower value.

This method returns the maximum priority that can be assigned to Thread objects that belong to this ThreadGroup object.

public final String getName();

public final String getName() method returns the name of this ThreadGroup object.
This method returns the name of this ThreadGroup object.

public final ThreadGroup getParent();

public final ThreadGroup getParent() method returns the parent ThreadGroup object of this ThreadGroup object. If this ThreadGroup is at the root of the thread group hierarchy and has no parent, the method returns null.

This method returns the parent ThreadGroup object of this ThreadGroup, or null if this ThreadGroup is the root of the thread group hierarchy.

public final boolean isDaemon();

public final boolean isDaemon() method determines whether or not this ThreadGroup is a daemon thread group, based on the value of daemon attribute of this ThreadGroup object. A daemon thread group is destroyed when the last Thread in it is stopped, or the last ThreadGroup in it is destroyed.

This method returns true if this ThreadGroup is a daemon thread group; otherwise false.

public synchronized boolean isDestroyed(); 

public synchronized boolean isDestroyed(); method determines whether or not this ThreadGroup has been destroyed.

This method returns true if this ThreadGroup has been destroyed; otherwise false.

public void list();

public void list() method outputs a listing of the contents of this ThreadGroup object to System.out.

public final boolean parentOf(ThreadGroup g);

public final boolean parentOf(ThreadGroup g) method determines if this ThreadGroup object is the same as the specified ThreadGroup or one of its ancestors in the thread-group hierarchy.

This method returns true if this ThreadGroup object is the same ThreadGroup or a direct or indirect parent of the specified ThreadGroup; otherwise false.

Parameter
g – A ThreadGroup object.

public final void resume();

public final void resume() method resumes each Thread object that directly or indirectly belongs to this ThreadGroup object by calling its resume() method.

public final void setDaemon(boolean daemon);

public final void setDaemon(boolean daemon) method sets the daemon attribute of this ThreadGroup object to the given value. A daemon thread group is destroyed when the last Thread in it is stopped, or the last ThreadGroup in it is destroyed.

Parameter
daemon – The new value for this ThreadGroup object’s daemon attribute.

public final void setMaxPriority(int pri);

public final void setMaxPriority(int pri) method sets the maximum priority that can be assigned to Thread objects that belong to this ThreadGroup object.

It is possible for a ThreadGroup to contain Thread objects that have higher priorities than this
maximum, if they were given that higher priority before the maximum was set to a lower value.
Parameter
pri – The new maximum priority for Thread objects that belong to this ThreadGroup object.

public final void stop();

public final void stop() method stops each Thread object that directly or indirectly belongs to this ThreadGroup object by calling its stop() method.

public final void suspend();

public final void suspend() method suspends each Thread object that directly or indirectly belongs to this ThreadGroup object by calling its suspend() method.

public String toString();

public String toString() method returns a string representation of this ThreadGroup object.

This method returns a string representation of this ThreadGroup object.

public void uncaughtException(Thread t, Throwable e);

public void uncaughtException(Thread t, Throwable e) method is called when a Thread object that belongs to this ThreadGroup object dies because of an uncaught exception. If this ThreadGroup object has a parent ThreadGroup object, this method just calls the parent’s uncaughtException() method. Otherwise, this method must determine whether the uncaught exception is an instance of ThreadDeath. If it is, nothing is done. If it is not, the method calls the printStackTrace() method of the exception object.

If this method is overridden, the overriding method should end with a call to super.uncaughtException().

Parameter
t – A reference to a Thread that just died because of an uncaught exception.
e – The uncaught exception.
Below is an example how to create a thread and assign it to the thread group:

Apart from these ThreadGroup class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

ThreadGroup tg=new ThreadGroup();
//creates a  new ThreadGroup 
Thread t=new Thread(tg);
// creates a thread in tg ThreadGroup as a member.
 

Share and Enjoy !

Class Runtime in Java

0

Share and Enjoy !

Class Runtime in Java

Every Java application has a single instance of class Runtime. Runtime class allows the application to interact with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method as an application can not create its own instance of this class.

Runtime class encapsulates a number of platform-dependent system functions. The static method getRuntime() returns the Runtime object for the current platform, and this object can be used to perform system functions in a platform-independent way.

The Runtime class provides access to various information about the environment in which a program is running. The Java run-time environment creates a single instance of this class that is associated with a program. The Runtime class does not have any public constructors, so a program cannot create its own instances of the class.

A program must call the getRuntime() method to get a reference to the current Runtime object. Information about operating system features is accessible through the System class.

exec() starts a new process running externally to the interpreter.

exit() causes the Java interpreter to exit and return a specified return code.

freeMemory() returns the approximate amount of free memory.

totalMemory() returns the total amount of memory available to the Java interpreter.

gc() forces the garbage collector to run synchronously, which may free up more memory.

runFinalization() forces the finalize() methods of unreferenced objects to be run immediately. This may free up system resources that those objects were holding.

load() loads a dynamic library with a fully-specified pathname.

loadLibrary() loads a dynamic library with only the library name specified; it looks in platform-dependent locations for the specified library. These libraries generally contain native code definitions for native methods.

traceInstructions() and traceMethodCalls() enable and disable tracing by the interpreter.

Note

  • some of the Runtime methods are more commonly called via the static methods of the System class.
  • Any processes run outside of Java may be system-dependent.

The structure of the class-Runtime is as follows :

public class java.lang.Runtime extends java.lang.Object{
//methods:
public Process exec(String command) throws IOException;;
public Process exec(String command,String exp[]) throws IOException;;
public Process exec(String commandArray[])throws IOException;;
public Process exec(String commandArray[],String exp[])throws IOException;;
public void exit(int status);
public native long freeMemory();
public native void gc();
public InputStream getLocalizedInputStream(InputStream in);
public OutputStream getLocalizedOutputStream(OutputStream out);
public static Runtime getRuntime();
public synchronized void load(String fileName);
public synchronized void loadLibrary(String libName);
public native void runFinalization();
public native long totalMemory();
public native void traceInstruction(boolean on);
public native void traceMethodCalls(boolean on);
public static void runFinalizersOnExit(boolean value);
}
 

The details of the class structure are given as follows:

public static Runtime getRuntime();

public static Runtime getRuntime() method returns a reference to the current Runtime object. Because the other methods of the Runtime class are not static, a program must call this method first in order to get a reference to a Runtime object that can be used in calling the other methods.

This method returns a reference to the current Runtime object.

public static void runFinalizersOnExit(boolean value); 

public static void runFinalizersOnExit(boolean value); method specifies whether or not the finalize() methods of all objects that have to finalize() methods are run before the Java virtual machine exits. By default, the finalizers are not run on exit.

Parameter
value – A boolean value that specifies whether or not finalization occurs on exit.

public Process exec(String command);

public Process exec(String command) method starts a new process to execute the given external command. The standard input, standard output, and standard error streams from the process are redirected to OutputStream and InputStream objects that are accessible through the Process object returned by this method. Calling this method is equivalent to:
exec(command, null)

This method returns a Process object that controls the process started by this method.

Parameter
command – A string that contains the name of an external command and any arguments to be passed to it.

public Process exec(String command, String envp[]);

public Process exec(String command, String envp[]) method starts a new process to execute the given external command. The standard input, standard output, and standard error streams from the process are redirected to OutputStream and InputStream objects that are accessible through the Process object returned by this method.

The method parses the command string into words that are separated by whitespace. It creates a String object for each word and places word String objects into an array. If that array is called commandArray, calling this method is equivalent to:
exec(commmandArray, envp)

This method returns a Process object that controls the process started by this method.

Parameter
command – A string that contains the name of an external command and any arguments to be passed to it.
envp – An array of strings that specifies the values for the environment variables of the new process. Each String in the array should be of the form variableName =value. If envp is null, the values of the environment variables in the current process are copied to the new process.

public Process exec(String cmdarray[]);

public Process exec(String cmdarray[]) method starts a new process to execute the given external command. The standard input, standard output, and standard error streams from the process are redirected to OutputStream and InputStream objects that are accessible through the Process object returned by this method. Calling this method is equivalent to:
exec(commandArray, null)

This method returns a Process object that controls the process started by this method.

Parameter
commandArray – An array of strings that contains separate strings for the name of an external command and any arguments to be passed to it. The first string in the array must be the command name.

public Process exec(String cmdarray[], String envp[]);

public Process exec(String cmdarray[], String envp[]) method starts a new process to execute the given external command. The standard input, standard output, and standard error streams from the process are redirected to OutputStream and InputStream objects that are accessible through the Process object returned by this method.

This method returns a Process object that controls the process started by this method.

Parameter
commandArray – An array of strings that contains separate strings for the name of an external command and any arguments to be passed to it. The first string in the array must be the command name.
envp – An array of strings that specifies the values for the environment variables of the new process. Each String in the array should be of the form variableName =value. If envp is null, the values of the environment variables in the current process are copied to the new process.

public void exit(int status);

public void exit(int status) method causes the Java virtual machine to exit with the given status code. By convention, a nonzero status code indicates abnormal termination. This method never returns.

Parameter
status – The exit status code to use.

public native long freeMemory();

public native long freeMemory() method returns an estimate of the number of free bytes in system memory. The value returned by this method is always less than the value returned by totalMemory(). Additional memory may be freed by calling the gc() method.

This method returns an estimate of the number of free bytes in system memory.

public native void gc();

public native void gc() method causes the Java virtual machine to run the garbage collector in the current thread.

The garbage collector finds objects that will never be used again because there are no live references to them. After it finds these objects, the garbage collector frees the storage occupied by these objects.

The garbage collector is normally run continuously in a thread with the lowest possible priority so that it works intermittently to reclaim storage. The gc() method allows a program to invoke the garbage collector explicitly when necessary.

public InputStream getLocalizedInputStream(InputStream in);

public InputStream getLocalizedInputStream(InputStream in) method returns an InputStream object that converts characters from the local character set to Unicode. For example, if the InputStream uses an 8-bit character set with values less than 128 representing Cyrillic letters, this method maps those characters to the corresponding Unicode characters in the range ‘\u0400’ to ‘\u04FF’.

This method is deprecated as of JDK 1.1. You should instead use the new InputStreamReader and BufferedReader classes to convert characters from the local character set to Unicode.

This method returns the localized InputStream.

Parameter
in – An InputStream object that is to be localized.

public OutputStream getLocalizedOutputStream(OutputStream out); 

public OutputStream getLocalizedOutputStream(OutputStream out); method returns an OutputStream object that converts characters from Unicode to the local character set. For example, if the local character set is an 8-bit character set with values less than 128 representing Cyrillic letters, this method maps Unicode characters in the range ‘\u0400’ to ‘\u04FF’ to the appropriate characters in the local character set.

This method is deprecated now. We should instead use the new OutputStreamWriter and BufferedWriter classes to convert characters from Unicode to the local character set.

This method returns the localized OutputStream.

Parameter
out – An OutputStream object that is to be localized.

public synchronized void load(String filename);

public synchronized void load(String filename) method loads the specified dynamically linked library. It is often more convenient to call the load() method of the System class because it does not require getting a Runtime object.

Parameter
filename – A string that specifies the complete path of the file to be loaded.

public synchronized void loadLibrary(String libname);

public synchronized void loadLibrary(String libname) method loads the specified dynamically linked library. It looks for the specified library in a platform-specific way.

It is often more convenient to call the loadLibrary() method of the System class because it does not require getting a Runtime object.

Parameter
libname – A string that specifies the name of a dynamically linked library.

public native void runFinalization();

public native void runFinalization() method causes the Java virtual machine to run the finalize() methods of any objects in the finalization queue in the current thread.

When the garbage collector discovers that there are no references to an object, it checks to see if the object has a finalize() method that has never been called. If the object has such a finalize() method, the object is placed in the finalization queue. While there is a reference to the object in the finalization queue, the object is no longer considered garbage-collectible.

Normally, the objects in the finalization queue are handled by a separate finalization thread that runs continuously at a very low priority. The finalization thread removes an object from the queue and calls its finalize() method. As long as the finalize() method does not generate a reference to the object, the object again becomes available for garbage collection.

Because the finalization thread runs at a very low priority, there may be a long delay from the time that an object is put on the finalization queue until the time that its finalize() method is called. The runFinalization() method allows a program to run the finalize() methods explicitly. This can be useful when there is a shortage of some resource that is released by a finalize() method.

public native long totalMemory();

public native long totalMemory() method returns the total number of bytes in system memory in the Java virtual machine. The total includes the number of bytes of memory being used by allocated objects, as well as the number of free bytes available for allocating additional objects. An estimate of the number of free bytes in system memory is available through the freeMemory() method.

This method returns the total number of bytes in system memory.

public native void traceInstructions(boolean on);

public native void traceInstructions(boolean on) method controls whether or not the Java virtual machine outputs a detailed trace of each instruction that is executed. The boolean parameter causes tracing to be turned on or off. The tracing of instructions is only possible in a Java virtual machine that was compiled with the tracing option enabled. Production releases of the Java virtual machine are generally not compiled with tracing enabled.

Parameter
on – A boolean value that specifies if instructions are to be traced. true if instructions are to be traced; otherwise false.

public native void traceMethodCalls(boolean on);

public native void traceMethodCalls(boolean on) method controls whether or not the Java virtual machine outputs a detailed trace of each method that is invoked. The boolean parameter causes tracing to be turned on or off. The tracing of instructions is only possible in a Java virtual machine that was compiled with the tracing option enabled. Production releases of the Java virtual machine are generally not compiled with tracing enabled.

Parameter
on – A boolean value that specifies if method calls are to be traced. true if instructions are to be traced; otherwise false.

Apart from these Runtime class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

Share and Enjoy !

Class Exception in Java

0

Share and Enjoy !

Class Exception in Java

The class Exception and its subclasses are a form of throwable objects that indicates conditions that can be caught using a catch clause in the code.

This class forms the root of the exception hierarchy in Java. An Exception signals an abnormal condition that must be specially handled to prevent program termination. Exceptions may be caught and handled. Exceptions that are not subclasses of RuntimeException must be declared in the throws clause of any method that can throw them.
getMessage() returns a message associated with the exception. See Throwable for other methods.

The Exception class is the superclass of all of the standard exception classes that can be thrown in Java. The subclasses of Exception represent exceptional conditions a normal Java program may want to handle. Any explicitly thrown object in a Java program should be an instance of a subclass of Exception.

Many of the standard exceptions are also subclasses of RuntimeException. Run-time exceptions represent run-time conditions that can occur generally in any Java method, so a method is not required to declare that it throws any of the run-time exceptions. However, if a method can throw any of the other standard exceptions, it must declare them in its throws clause.

A Java program should try to handle all of the standard exception classes since they represent routine abnormal conditions that should be anticipated and caught to prevent program termination.

The structure of the Exception class is given below:

public class java.lang.Exception extends java.lang.Throwable{
//constructor
public Exception();
//constructs an empty Exception object that is an object with no message specified.
public Exception(String message);
//constructs an Exception object with the message specified.
}

This message is used later to extract information from the Exception.

The class Exception also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

Share and Enjoy !

Class System in Java

0

Share and Enjoy !

Class System in Java

The System class contains several useful methods and member elements. As all the members of the System class are static, we do not need to instantiate this class. We can directly call them By using the System. (member name) like-System.in or System.out etc. System class provides the methods that provide a platform-independent interface to system functionality.

The System class provides access to various information about the operating system environment in which a program is running. For example, the System class defines variables that allow access to the standard I/O streams and methods that allow a program to run the garbage collector and stop the Java virtual machine.

All of the variables and methods in the System class are static. In other words, it is not necessary to create an instance of the System class to use its variables and methods. The System class does not define any public constructors, so it cannot be instantiated.

The System class supports the concept of system properties that can be queried and set. The following properties are guaranteed always to be defined:

 

Property NameMeaning
file.encodingThe character encoding for the default locale
file.encoding.pkgThe package that contains converters between local encodings and Unicode
file.separatorFile separator (‘/’ on UNIX, ‘ \’ on Windows)
java.class.pathThe classpath
java.class.versionJava class version number
java.compilerThe just-in-time compiler to use, if any
java.homeJava installation directory
java.vendorJava vendor-specific string
java.vendor.urlJava vendor URL
java.versionJava version number
line.separatorLine separator(‘ \n’ on UNIX, ‘ \r\n’ on Windows)
os.archOperating system architecture
os.nameOperating system name
os.versionOperating system version
path.separatorPath separator (‘:’ on UNIX, ‘,’ on Windows)
user.dirUser’s current working directory when the properties were initialized
user.homeUser’s home directory
user.languageThe two-letter language code of the default locale
user.nameUser’s account name
user.regionThe two-letter country code of the default locale
user.timezoneThe default time zone

Additional properties may be defined by the run-time environment. The -D command-line option can be used to define system properties when a program is run.

The Runtime class is related to the System class; it provides access to information about the environment in which a program is running.

The structure of Class System in Java is given as:

public final class java.lang.System extends java.lang.Object{
//Member elements:
public static final InputStream in;// This is the standard inputStream and it is already opened by JVM. It is ready to supply input data. This stream takes input from keyboard.But this can be configured to take input from any other  source.
public static final PrintStream err;//This corresponds to standard error Stream.
public static final PrintStream  out; //This is the standard output stream and it is already opened to provide output data.This stream prints output to display or console but can be configured to other output destination.
//Methods:
public static native void arrayCopy(Object Array_Src,int src_position,Object Array_Dest,int dest_position,int length);
public static native long currentTimeMills();
public static void exit(int status);
public static void gc();
public static Properties getProperties();
public static String getProperty(String key);
public static String getProperty(String key,String def);
public static String getenv(String name);
public static SecurityManager getSecurityManager();
public static void load(String fileName);
public static void loadLibrary(String libFileName);
public static void runFinalization();
public static void setProperties(Properties prop);
public static void setSecurityManager(SecurityManager sm);
public static native int identityHashCode(Object obj);
public static void runFinalizersOnExit(boolean value);
public static void setErr(PrintStream err);
public static void setIn(InputStream in);
public static void setOut(PrintStream out);
}
 

The details of the class structure are given as follows:

public static final InputStream in;

public static final InputStream in describes The standard input stream. In an application environment, this variable refers to a java.io.InputStream object that is associated with the standard input for the process running the Java virtual machine.

The value of in can be set using the setIn() method. The value of in can only be set if the currently installed SecurityManager does not throw a SecurityException when the request is made.
Before Java 1.1, it was not final. It has been made final as of Java 1.1 because the unchecked ability to set in is a security hole.

public static final PrintStream err;

public static final PrintStream err describes the standard error stream. In an application environment, this variable refers to a java.io.PrintStream object that is associated with the standard error output for the process running the Java virtual machine. In an applet environment, the PrintStream is likely to be associated with a separate window, although this is not guaranteed.

The value of err can be set using the setErr() method. The value of err can only be set if the
currently installed SecurityManager does not throw a SecurityException when the request is
made.

Before Java 1.1, err was not final. It has been made final as of Java 1.1 because the unchecked ability to set err is a security hole.

public static final PrintStream  out;

public static final PrintStream out describes The standard output stream. In an application environment, this variable refers to a java.io.PrintStream object that is associated with the standard output for the process running the Java virtual machine. In an applet environment, the PrintStream is likely to be associated with a separate window, although this is not guaranteed.

out is the most commonly used of the three I/O streams provided by the System class. Even in GUI-based applications, sending output to this stream can be useful for debugging. The usual idiom for sending output to this stream is:
System.out.println(“Some text”);
The value of out can be set using the setOut() method. The value of out can only be set if the currently installed SecurityManager does not throw a SecurityException when the request is made.

Before to Java 1.1, out was not final. It has been made final as of Java 1.1 because the unchecked ability to set out is a security hole.

public static native void arrayCopy(Object Array_Src,int src_position,Object Array_Dest,int dest_position,int length);

public static native void arrayCopy(Object Array_Src,int src_position,Object Array_Dest,int dest_position,int length) method copies a range of array elements from the src array to the dst array. The number of elements that are copied is specified by length. The elements at positions src_position through src_position+length-1 in src are copied to the positions dst_position through dst_position+length-1 in Array_Dest, respectively.

If Array_Src and Array_Dest refer to the same array, the copying is done as if the array elements were first copied to a temporary array and then copied to the destination array.

Before this method does any copying, it performs several checks. If either Array_Src or Array_Dest is null, the method throws a NullPointerException and Array_Dest is not modified.

If any of the following conditions are true, the method throws an ArrayStoreException, and Array_Dest  is not modified:

  • Either src or Array_Dest  refers to an object that is not an array.
  • Array_Src and Array_Dest  refer to arrays whose element types are different primitive types.
  • Array_Src refers to an array that has elements that contain a primitive type, while Array_Dest  refers to an array that has elements that contain a reference type, or vice versa.

If any of the following conditions are true, the method throws an ArrayIndexOutOfBoundsException, and Array_Dest  is not modified:

  • Array_SrcOffset, Array_DestOffset, or length is negative.
  • Array_SrcOffset+length is greater than Array_Src.length().
  • Array_DestOffset+length is greater than Array_Dest.length().

Otherwise, if an element in the source array being copied cannot be converted to the type of the destination array using the rules of the assignment operator, the method throws an ArrayStoreException when the problem occurs. Since the problem is discovered during the copy operation, the state of the Array_Dest array reflects the incomplete copy operation.

Parameter
Array_Src – The source array.
src_position – An index into the source array.
Array_Dest – The destination array.
dest_position – An index into the destination array.
length – The number of elements to be copied.

public static native long currentTimeMills();

public static native long currentTimeMills() method returns the current time as the number of milliseconds since 00:00:00 UTC, January 1, 1970. It will not overflow until the year 292280995. The java.util.Date class provides more extensive facilities for dealing with times and dates.
This method returns the current time as the number of milliseconds since 00:00:00 UTC, January 1, 1970.

public static void exit(int status);

public static void exit(int status) method causes the Java virtual machine to exit with the given status code. This method works by calling the exit() method of the current Runtime object. By convention, a nonzero status code indicates abnormal termination. This method never returns.

Parameter
status – The exit status code to use.

public static void gc();

public static void gc() method causes the Java virtual machine to run the garbage collector in the current thread. This method works by calling the gc() method of the current Runtime object.

The garbage collector finds objects that will never be used again because there are no live references to them. After it finds these objects, the garbage collector frees the storage occupied by these objects.

The garbage collector is normally run continuously in a thread with the lowest possible priority so that it works intermittently to reclaim storage. The gc() method allows a program to invoke the garbage collector explicitly when necessary.

public static Properties getProperties();

public static Properties getProperties() method returns all of the defined system properties encapsulated in a java.util.Properties object. If there are no system properties currently defined, a set of default system properties is created and initialized. As discussed in the description of the System class, some system properties are guaranteed always to be defined.

This method returns a Properties object that contains the values of all the system properties.

public static String getProperty(String key);

public static String getProperty(String key) method returns the value of the named system property. If there is no definition for the named property, the method returns null. If there are no system properties currently defined, a set of default system properties is created and initialized. As discussed in the description of the System class, some system properties are guaranteed always to be defined.

This method returns the value of the named system property or null if the named property is not defined.

Parameter
key – The name of a system property.

public static String getProperty(String key,String def);

public static String getProperty(String key, String def) method returns the value of the named system property. If there is no definition for the named property, the method returns the default value as specified by the def parameter. If there are no system properties currently defined, a set of default system properties is created and initialized. As discussed earlier in the description of the System class, some system properties are guaranteed to always be defined.

This method returns the value of the named system property, or the default value if the named property is not defined.
Parameter
key -The name of a system property.
def – A default value for the property.

public static String getenv(String name);

public static string getenv(String name) method is obsolete; it always throws an error. Use getProperties() and the -D option instead.
This method returns the value of the environment variable or null if the variable is not defined.
Parameter
name – The name of a system-dependent environment variable.

public static SecurityManager getSecurityManager();

public static SecurityManager getSecurityManager() method returns a reference to the installed SecurityManager object. If there is no SecurityManager object installed, the method returns null.

This method returns a reference to the installed SecurityManager object or null if there is no SecurityManager object installed.

public static void load(String fileName);

public static void load(String fileName) method loads the specified dynamically linked library. This method works by calling the load() method of the current Runtime object.

Parameter
filename – A string that specifies the complete path of the file to be loaded.

public static void loadLibrary(String libFileName);

public static void loadLibrary(String libFileName) method loads the specified dynamically linked library. It looks for the specified library in a platform-specific way. This method works by calling the loadLibrary() method of the current Runtime object.

Parameter
libFileName – A string that specifies the name of a dynamically linked library.

public static void runFinalization();

public static void runFinalization() method causes the Java virtual machine to run the finalize() methods of any objects in the finalization queue in the current thread. This method works by calling the runFinalization() method of the current Runtime object.

When the garbage collector discovers that there are no references to an object, it checks to see if the object has a finalize() method that has never been called. If the object has such a finalize() method, the object is placed in the finalization queue. While there is a reference to the object in the finalization queue, the object is no longer considered garbage collectible.

Normally, the objects in the finalization queue are handled by a separate finalization thread that runs continuously at a very low priority. The finalization thread removes an object from the queue and calls its finalize() method. As long as the finalize() method does not generate a reference to the object, the object again becomes available for garbage collection.
Because the finalization thread runs at a very low priority, there may be a long delay from the time that an object is put on the finalization queue until the time that its finalize() method is called.

The runFinalization() method allows a program to run the finalize() methods explicitly. This can be useful when there is a shortage of some resource that is released by a finalize() method.

 

public static void setProperties(Properties prop);

public static void setProperties(Properties prop) method replaces the current set of system property definitions with a new set of system property definitions that are encapsulated by the given Properties object.

As discussed in the description of the System class, some system properties are guaranteed to always be defined.

Parameter
prop – A reference to a Properties object.

public static void setSecurityManager(SecurityManager sm);

public static void setSecurityManager(SecurityManager sm) method installs the given SecurityManager object. If s is null, then no SecurityManager object is installed. Once a SecurityManager object is installed, any subsequent calls to this method throw a SecurityException.

Parameter
sM – A reference to a SecurityManager object.

public static native int identityHashCode(Object obj);

public static native int identityHashCode(Object obj) method returns the same hashcode value for the specified object as would be returned by the default hashCode() method of Object, regardless of whether or not the object’s class overrides hashCode().

This method returns the identity hashcode value for the specified object.
Parameter
obj – An object.

public static void runFinalizersOnExit(boolean value);

public static void runFinalizersOnExit(boolean value) method specifies whether or not the finalize() methods of all objects that have to finalize() methods are run before the Java virtual machine exits.

By default, the finalizers are not run on exit. This method works by calling the runFinalizersOnExit() method of the current Runtime object.
Parameter
value -A boolean value that specifies whether or not finalization occurs on exit.

public static void setErr(PrintStream err);

public static void setErr(PrintStream err) method sets the standard error stream to be this PrintStream object.
Parameter
err – A PrintStream object to use for the standard error stream.

public static void setIn(InputStream in);

public static void setIn(InputStream in) method sets the standard input stream to be this InputStream object.
Parameter
in – A InputStream object to use for the standard input stream.

public static void setOut(PrintStream out);

public static void setOut(PrintStream out) method sets the standard output stream to be this PrintStream object.
Parameter
out – A PrintStream object to use for the standard output stream.

Apart from these System class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

Example:

What is System.out.println?

System.out.Prinln() method writes a line to console as output data. The System.out corresponds to the OutputStream as described above and does not need to instantiate the System class. As they are static we can directly call them. pritln() method is defined in the PrintStream class.

From day one while learning Java we use to give this command to print some value to console. It may be for output purposes or debugging purposes.

Now let us understand what is System, what is out and what is println?
The system is a built-in class that is present in java.lang package. This class is of final modifier type so it can not be inherited to other classes. or it can not be instantiated. This package defines a class called System. The System class holds a collection of static methods and variables.the standard input, output and error output of the java runtime are stored in, out, err variables.

out is a static final field (ie, variable)in System class which is of the type PrintStream (a built-in class, contains methods to print the different data values).

static fields and methods must be accessed by using the class name, so ( System.out ).  Simply..out is a static member of type PrinStream class(java.io) declared in the System class. static members of a class can be accessed directly by classname that’s why System.out.out here denotes the reference variable of the type PrintStream class. As this is of type static,

  1. It gets instantiated as soon as the class is loaded.
  2. It creates a mapping with the console where the program is running
  3. The stream becomes open and ready for accepting data.

println() is a public method in PrintStream class to print the data values. Hence to access a method in PrintStream class, we use it out.println() (as nonstatic methods and fields can only be accessed by using the reference variable).

As we discussed println() method is a member of the out object which is a static data member of System class. println() always appends a newline character to the end of the string i.e any subsequent output will start on a new line.

 double x=5;
double y;
y=Math.sqrt(x);
system.out.println("y"+y);

Here + stands for concatenation operator of two strings. The double value of y is converted to an equivalent string and concatenated with the initial string.
Note- There are multiple println() method exists with different parameters.
The code snippet might help you to understand better…

public final class java.lang.System {    
public static final java.io.PrintStream out;     
// some methods . . .     
}     
public class java.io.PrintStream extends.......{     
public void println(....){     
. .     
}     
}

More details to find on java.lang.system class check out here..

So this command can not be altered and package can not be modified. We can not create our own variable to do print.

like

system.XYZ.print(“Test”);

is invalid

==============================================
But surely you can represent this method in different other ways…
One of the way may be–

import java.io.*;
public class Animesh
{
private static PrintStream out = System.out;
public static void main(String args[])
{
out.println("This is good");
}
}

Here instead of System.out.println() we are using out.println()
==============================================
Another way may be–

import javax.swing.JOptionPane;    
import java.io.*;     
public class animesh {
public static void main(String[] args) {
String str=JOptionPane.showInputDialog("enter data");
System.out.println(str);
animesh d=new animesh();
d.print(str);
}
public void print(Object obj){
System.out.println(obj.toString());
}
}

Here I have modified some other way….here instead of System.out.println() I am using d.print(str).These are all wrapper technique on top of System.out.println()  Nothing else!!

How to Run Java Program Without Main Function??

In Java, a static initializer gets executed as soon as the class is
loaded, even before the main method is called!!!.

So if we create a static block and give some command inside it. It will execute. The JVM finds and loads the class into memory when you run this code, the static initializer is executed during the loading and initialization of the class.
But my suggestion does not use this feature while developing your application. And even if you use this feature please make sure to incorporate
System.exit(0); After your code
System.exit(0) is called at the end of the static block to terminates the program. If not, then the JVM would have next used reflection on that class to find the main() method. If it does not find the main method, it throws an exception. if we don’t write main() in the program then the compiler doesn’t know
where to start the program…

public class WithoutMain {
static {
System.out.println( "Hello World" );
System.exit(0);
}
}

How To Get System Properties In Java?

For each system, system properties information (persistent ) will be maintained in the form of system properties. Mainly we use properties to maintain system configuration. The system class will maintain a Properties object to get all the details.

In short, it is nothing but a key-value pair in the form of string.
The important aspect of System property is “to access any value from it, it requires current security manager’s approval”

More details can be found here:

Lets see an example:

import java.util.Properties;
public class systemTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties p=System.getProperties();
p.list(System.out);
}
}

output:
java.vm.specification.vendor=XYZ Corporation
user.variant=
os.name=Windows XP
sun.jnu.encoding=Cp1252
java.library.path=C:Program FilesJavajdk1.7.0_21bin…
java.specification.name=Java Platform API Specification
java.class.version=51.0
sun.management.compiler=HotSpot Client Compiler
os.version=5.1
user.home=C:Documents and Settingsanichatt.AP…
user.timezone=
java.awt.printerjob=sun.awt.windows.WPrinterJob
file.encoding=Cp1252
java.specification.version=1.7
user.name=anichatt
java.class.path=E:myProgram
java.vm.specification.version=1.7
sun.arch.data.model=32
java.home=C:Program FilesJavajdk1.7.0_21jre
sun.java.command=systemTest
java.specification.vendor=xyz Corporation
user.language=en
awt.toolkit=sun.awt.windows.WToolkit
java.vm.info=mixed mode, sharing
java.version=1.7.0_21
java.ext.dirs=C:Program FilesJavajdk1.7.0_21jre…
sun.boot.class.path=C:Program FilesJavajdk1.7.0_21jre…
java.vendor=xyz Corporation
file.separator=
java.vendor.url.bug=http://bugreport.sun.com/bugreport/
sun.cpu.endian=little
sun.io.unicode.encoding=UnicodeLittle
sun.desktop=windows
sun.cpu.isalist=pentium_pro+mmx pentium_pro pentium+m…

Below are the system properties that can be tracked using the system class’s Property Object. Important system properties

KeyMeaning
“file.separator”Character that separates components of a file path. This is “/" on UNIX and "" on Windows.
“java.class.path”Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
“java.home”Installation directory for Java Runtime Environment (JRE)
“java.vendor”JRE vendor name
“java.vendor.url”JRE vendor URL
“java.version”JRE version number
“line.separator”Sequence used by operating system to separate lines in text files
“os.arch”Operating system architecture
“os.name”Operating system name
“os.version”Operating system version
“path.separator”Path separator character used in java.class.path
“user.dir”User working directory
“user.home”User home directory
“user.name”User account name

taken from docs.oracle.com.
How to get single property from the list?? say I want to retrieve OS name and current location of the class file. so the corresponding code:

import java.util.Properties;
public class systemTest {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Properties p=System.getProperties();
  //p.list(System.out);
  System.out.println(p.getProperty("java.class.path"));
  System.out.println(p.getProperty("os.name"));
  }
}

output:
. (dot -it means current working directory)
Windows XP

How To Check System Configuration Before Proceeding With Our Code In Java?

let’s say I have developed a program in Java-1.6 and used some code which got enhanced in that particular version.
like-

  • Native platform Security (GSS/Kerberos) integration.
  • Java Authentication and Authorization Service (JAAS) login
  • the module that employs LDAP authentication
  • New Smart Card I/O API
  • Native security services technical article

Let’s assume that this program will run on java -1.5. Definitely the compatibility will not be there.

As per stack over flow

The compiler is not backwards compatible because bytecode generated with Java6 JDK won’t run in Java 1.5 jvm (unless compiled with the -target 1.5 flag). But the JVM is backwards compatible, as it can run older bytecodes.

So I guess they chose to consider the compatibility from the point of view of javac (as it is the part specific to the JDK), meaning that the bytecode generated can be run in future releases of the jvm (that is more related to the JRE, but also bundled in the JDK).

In brief, we can say:

JDK’s are (usually) forward compatible.
JRE’s are (usually) backward compatible.

Let us also assume , my program needs the below written…

  • Java version-java 1.7
  • OS-Windows XP
  •  and I have some requirement where the .class file should be in C drive.

if all of the above are matching then our program is good to go else we will simply say with the configuration, this program will not run…

Let’s see how: I have shown how to get system properties previously. From the list of properties, we are only going to choose

  • java version
  • OS
  • class. path

 

import java.util.Properties;
public class systemTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean b=false;
Properties p=System.getProperties();
p.list(System.out);
//get all the list of properties.
String path=p.getProperty("java.class.path");
String os=p.getProperty("os.name");
String javaVersion=p.getProperty("java.specification.version");
System.out.println(path);
System.out.println(os);
System.out.println(javaVersion);
if((path.indexOf("C:\")>=0||path.equals(".")) && os.equals("Windows XP") && javaVersion.equals("1.7"))
b=true;
//checks the path contains C drive,also checks for OS or java version
if(b)
System.out.print("We can proceed");
else
System.out.print("We can not proceed");
}
}

output:
. (dot means present working directory.)
Windows XP
1.7
We can proceed

Now if the java version is 1.4 (running)in the client machine. It should say “We can not proceed”. By this way, we can achieve the precondition cases for running our tests.

Share and Enjoy !