Tuesday, February 28, 2012

STRING CONSTRUCTOR IN JAVA

String Constructors
         The String class supports several constructors. To create an empty String, you call the default constructor.


Example:

String s = new String();

       It will create an instance of String with no characters in it.
Frequently, you will want to create strings that have initial values.
The String class provides a variety of constructors to handle this.

To create a String initialized by an array of characters

String(char chars[ ])
 Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
 This constructor initializes s with the string “abc”.
You can specify a subrange of a character array as an initializer using the following constructor:
 String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use.

Example:
 
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String sam = new String(chars, 2, 3);
This initializes s with the characters cde. You can construct a String object that contains the same character sequence as another String object using this constructor:
String(String str)
Here, str is a String object.

Example:
class CreateString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
output:
Java
Java

  s1 and s2 contain the same string.
VA RY
  • Even though Java’s char type uses 16 bits to represent the Unicode character set, the typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set.
  • Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array.

String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
  • asciiChars specifies the array of bytes.
  • The second form allows you to specify a subrange. In each of these constructors, the byte-to-character conversion is done by using the default character encoding of the platform. 

Example:
 class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
output:
ABCDEF
CDE
  • Extended versions of the byte-to-string constructors are also defined in which you can specify the character encoding that determines how bytes are converted to characters.
  • The contents of the array are copied whenever you create a String object from an array. If you modify the contents of the array after you have created the string, the String will be unchanged.
 String Length
        The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method
int length( )
The following fragment prints “3”, since there are three characters in the string s: 
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());

Wednesday, February 22, 2012

JAVA CLASS CONSTRUCTOR

JAVA CONSTRUCTOR
  • A class contains constructors that are invoked to create objects from the class blueprint.
  • A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object.
  • It can be used to initialize the objects ,to required ,or default valuesat the time of object creation It is not mandatory for the coder to write a constructor for the class
If no user defined constructor is provided for a class, compiler initializes member variables to its default values.
  • numeric data types are set to 0
  • char data types values are null
CONTRUCTOR DESCRIPTION:
  • Constructors are used to assign initial values to instance variables of the class.
  • A default constructor with no arguments will be called automatically by the Java Virtual Machine (JVM).
  • Constructor is always called by new operator. Constructors are declared just like as we declare methods, except that the constructor don't have any return type.
In order to create a Constructor observe the following rules
  • It has the same name as the class
  • It should not return a value not even void
  • You don't have to provide any constructors for your class, but you must be careful when doing this.
  • The compiler automatically provides a no-argument, default constructor for any class without constructors.
  • This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does.
  • If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.

Example:
class Sample_constructor
{
public static void main(String args[])
{
Sample_constructor sam=new Sample_constructor();
//object is reated &
//constructor is invoked using new
System.out.Println("Hai ...")
}
}

OUTPUT:
Hai...

NOTE:
· Though there is no constructor definition, Java defaultly does the contructor process when method is invoked using new operator with tha same name of class.
· Here there in this example there is no construction defitions.but when code new Sample_contructor() is reached  it creates & initializes object

Monday, February 20, 2012

JAVA CLASSES AND OBJECTS

CLASSES AND OBJECTS

Class:

  • A class is a blue print to create instance of itself.
  • A class defines constituent members which enable these class instances to have state and behavior
  • Data field members (member variables or instance variables) enable a class object to maintain state. Other kinds of members, especially methods, enable a class object's behavior. Class instances are of the type of the associated class.
  • A class usually represents a noun, such as a person, place or (possibly quite abstract) thing, or something nominalized.
  • Classes consist of and are composed from structural and also behavioral constituents, though there may not be a requirement to include any structural or behavioral constituents at all. 
  • A class contains both data (referred to as attributes), and executable code (referred to as methods).
  • Programming languages that include classes as a programming construct offer support for various class-related features. These features, and the syntaxes with which they are provided, vary greatly. Various control features such as member access specifiers may be provided by a language.

Example:

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

Example:
class Sample extends SuperClass
implements Interface1 {
// field, constructor, and
// method declarations
}

means that Sample is a subclass of SuperClass and that it implements the Interface1 interface.

  • Here the extend keyword derives properties of the base class.Thus inheritance property is used.
  • And implements keyword creates the interface to access all methods and data members in that class


In general, class declarations can include these components, in order:
  1. Modifiers such as publicprivate, and a number of others that you will encounter later.
  2. The class name, with the initial letter capitalized by convention.
  3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  5. The class body, surrounded by braces, {}.

Object:
  • An object is any entity that can be manipulated by the commands of a programming language, such as a valuevariablefunction, or data structure
  • The modern concept of "object" and the object-oriented approach to programming were introduced by the Simula programming language originally released in 1967, popularized by Smalltalk released two years later in 1969, and became standard tools of the trade with the spread of C++ originally released in 1983.
  • In the "pure" object-oriented approach, the data fields of an object should only be accessed through its methods (subroutines).

Properties of an object:
Three properties characterize objects:
  1. Identity: the property of an object that distinguishes it from other objects
  2. State: describes the data stored in the object
  3. Behavior: describes the methods in the object's interface by which the object can be used

Object creation:
  •  Object for above given program can be created by using new keyword.new keyword dynamically allocates memory to object

Example:

Sample sam=new Sample( );    //Object of class Sample
  • This sam object is used to access the all the data members and member functions in Sample class.




Wednesday, February 15, 2012

COMMAND LINE ARGUMENTS

COMMAND LINE ARGUMENTS
  •  A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.
  • The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run.
  • When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings.
  • Java application can accept any number of arguments directly from the command line. The user can enter command-line arguments when invoking the application. 
  • When running the java program from java command, the arguments are provided after the name of the class separated by space.

Example:
  • Consider our Java program as sample.java with command line arguments.For that we have give the arguments in command prompt when invoking the program.
  • use java sample arg1 arg2 arg3....to run sample java program.
Program: 

public class Sample {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}
 
Compilation:
 
use the following code to run this program
javac Sample.java
java Sample Hai Hello World
 
Output:
 
Hai
Hello
World
 
Note: 
  • If you want give single command line argument for the same Output(above output), 
  • Compile the program and run using the code
    java Sample "Hai Hello World"

Output:
Hai Hello World


Parsing Numeric Command-Line Arguments

  • If your program needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "8", to a numeric value. 
Example:
public class Sample {
    public static void main (String[] args) {
int firstArg;
if (args.length > 0) {
    try {
        firstArg = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        System.err.println("Argument"
            + " must be an integer");
        System.exit(1);
    }
}
}
} 
  • parseInt throws a NumberFormatException if the format of args[0] isn't valid. All of the Number classes — Integer, Float, Double, and so on — have parseXXX methods that convert a String representing a number to an object of their type

Sunday, February 12, 2012

JAVA DATA TYPES

BASIC JAVA PROGRAMMING LANGUAGE TYPES 
 
The Java programming language has many built in data types.These fall into two broad categories:
  • class types
  • primitive types
Primitive types are aimple values,are not objects.Class types are used for more complex types, including all of the types.Class types are used to create objects.

Primitive  Types

Java programming language defines eight primitive data types, which can be considered in 4 categories:
  • Logical-boolean
  • Texual-char
  • Integral-byte,short,int and long
  • Floating point-double and float
Logical -boolean
  • Logical values are represented using the boolean type,which takes either true or false.It has two literal values:true and false.
Textual-char
  • Single characters represented by using the char type.A char represents a 16-bit, unsigned Unicode character.Single character must enclose a character literal in single quotes(' ').
Example:
'b' The letter b

Texual-String
  • It is not a primitive but a class, to represent sequences of characters.String literals enclosed in double quotes("").
Primitive data types.

A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:
 
  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
  •  short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
  • int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.
  • long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal  class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lana.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type.

Default Values

The following chart summarizes the default values for the above data types.

Data Type
Default Value (for fields)
byte
0
short
0
int
0
long
0L
float
0.0f
double
0.0d
char
'\u0000'
String (or any object)
Null
boolean
False
 
 

 Java Primitive Data Types (8)

TypeContainsDefaultSizeRange
booleantrue or falsefalse1 bitNA
charUnicode character
unsigned
\u000016 bits or
2 bytes
0 to 216-1 or
\u0000 to \uFFFF
byteSigned integer08 bit or
1 byte
-27 to 27-1 or
-128 to 127
shortSigned integer016 bit or
2 bytes
-215 to 215-1 or
-32768 to 32767
intSigned integer032 bit or
4 bytes
-231 to 231-1 or
-2147483648 to 2147483647
longSigned integer064 bit or
8 bytes
-263 to 263-1 or
-9223372036854775808 to
9223372036854775807
floatIEEE 754 floating point
single-precision
0.0f32 bit or
4 bytes
�1.4E-45 to
�3.4028235E+38
double
IEEE 754 floating point
double-precision
0.064 bit or
8 bytes
�439E-324 to
�1.7976931348623157E+308