Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Tuesday, 27 August 2013

Wrapper class



Wrapper class

Wrapper class were a solution of the primitive data type not being a part of object oriented approach of java….like being returned from a method as a method.
Java allows you to include the primitives in the family of objects by using what are called wrapper classes
There is a wrapper class for every primitive in java.. the wrapper class for int is Integer, for float is Float.
The wrapper classes in the Java API serve two primary purposes:
  • To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
  • To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.
The wrapper object of a wrapper class can be created in one of two ways: by instantiating the wrapper class with the new operator or by invoking a static method on the wrapper class.
Creating wrapper object with new operator
Primitive datatype-->Wrapper Class-->Constructor arguments
  • boolean--> Boolean--> boolean or String
  • byte--> Byte--> byte or String
  • char--> Character--> char
  • short--> Short--> short or String
  • int-->Integer--> int or String
  • long--> Long--> long or String
  • float-->Float--> float double or String
  • double-->Double--> double or String
All the wrapper classes are declared final. That means you cannot derive a subclass from any of them.All the wrapper classes except Boolean and Character are subclasses of an abstract class called Number, whereas Boolean and Character are derived directly from the Object class.All of the wrapper classes except Character provide two constructors: one that takes a primitive of the type being constructed, and one that takes a String representation of the type being constructed.
Boolean wboo = new Boolean("false");
Boolean yboo=new Boolean(false);
Character c1 = new Character('c');
Note that there is no way to modify a wrapped value—that is, the wrapped values are immutable. To wrap another value, you need to create another object.

WRAPPING PRIMITIVES USING A STATIC METHOD
All wrapper classes offers static valueOf() methods which give you another approach to creating wrapper objects. Because it's a static method, it can be invoked directly on the class (without instantiating it), and will return the corresponding object that is wrapping what you passed in as an argument.
this method  take a String representation of the appropriate type of primitive as its first argument, it also takes an additional argument, int radix, which indicates in what base (for example binary, octal, or hexadecimal) the first argument is represented
Integer i2 = Integer.valueOf("101011", 2);  // converts 101011 to 43 and assigns the
                                           // value 43 to the Integer object i2

USING WRAPPER CONVERSION UTILITIES
xxxValue() method
When you need to convert the value of a wrapped numeric to a primitive, use one of the many xxxValue() methods. All of the methods in this family are no-arg methods. Each of the six numeric wrapper classes has six methods, so that any numeric wrapper can be converted to any primitive numeric type.
Integer i2 = new Integer(42);  //  make a new wrapper object
byte b = i2.byteValue();         //  convert i2's value to a byte primitive
short s = i2.shortValue();      //  another of Integer's xxxValue methods
double d = i2.doubleValue(); //  yet another of Integer's xxxValue methods

xxx Parsexxx(String) method
If you do not need to store a value in a wrapper but just want to convert the type , you can do it by using an appropriate static method of the appropriate wrapper class. For example, all the wrapper classes except Character offer a static method that has the following signature:
static <type> parse<Type>(String s)
The <type> may be any of the primitive types except char (byte, short, int, long, float, double, or boolean), and the <Type> is the same as <type> with the first letter uppercased;
String s = "123";
int i = Integer.parseInt(s);


parseXxx() and valueOf()
·  parseXxx() returns the named primitive.
·  valueOf() returns a newly created wrapped object of the type that invoked the method.
double d4 = Double.parseDouble("3.14");     // convert a String to a primitive
System.out.println("d4 = " + d4);               // result is  "d4 = 3.14"
Double d5 = Double.valueOf("3.14");         // create a Double object
System.out.println(d5 instanceof Double ); // result is "true"

toString() method
All of the wrapper classes have a no-arg, nonstatic, instance version of toString(). This method returns a String with the value of the primitive wrapped in the object—
Double d = new Double("3.14");
System.out.println("d = " + d.toString() );    //  result is "d = 3.14"
All of the numeric wrapper classes provide an overloaded, static toString() method that takes a primitive numeric of the appropriate type (Double.toString() takes a double), and, of course, returns a String with that primitive’s value.
System.out.println("d = " + Double.toString(3.14);    // result is "d = 3.14"
Integer and Long provide a third toString() method. It is static, its first argument is the appropriate primitive, and its second argument is a radix. The radix argument tells the method to take the first argument (which is radix 10 or base 10 by default), and convert it to the radix provided, then return the result as a String
System.out.println("hex = " + Long.toString(254,16); // result is "hex = fe"

toXxxString() method(Binary, Hexadecimal, Octal)
The Integer and Long wrapper classes let you convert numbers in base 10 to other bases. These conversion methods, toXxxString(), take an int or long, and return a String representation of the converted number,
String s3 = Integer.toHexString(254);       // convert 254 to hex
System.out.println("254 in hex = " + s3);   // result is "254 in hex = fe"
String s4 = Long.toOctalString(254);        // convert 254 to octal
System.out.println("254 in octal = "+ s4);  // result is "254 in octal = 376"
Quick review
  • Java uses primitive types, such as int, char, double to hold the basic data types supported by the language.
  • Sometimes it is required to create an object representation of these primitive types.
  • These are collection classes that deal only with such objects. One needs to wrap the primitive type in a class.
  • To satisfy this need, java provides classes that correspond to each of the primitive types. Basically, these classes encapsulate, or wrap, the primitive types within a class.
  • Thus, they are commonly referred to as type wrapper. Type wrapper are classes that encapsulate a primitive type within an object.
  • The wrapper types are Byte, Short, Integer, Long, Character, Boolean, Double, Float.
These classes offer a wide array of methods that allow to fully integrate the primitive types into Java’s object hierarchy.

Wrapper classes for converting simple types

Simple Type
Wrapper class
boolean
Boolean
char
Character
double
Double
float
Float
int
Integer
long
Long

Converting primitive numbers to Object numbers using constructor methods

Constructor calling
Conversion Action
Integer IntVal = new Integer(i);
Primitive integer to Integer object
Float FloatVal = new Float(f);
Primitive float to Float object
Double DoubleVal = new Double(d);
Primitive double to Double object
Long LongVal = new Long(l);
Primitive long to Long object

NOTE : I, f, d and l are primitive data values denoting int, float, double and long data types. They may be constants or variables.

Converting Object numbers to Primitive numbers using typeValue() method

Method calling
Conversion Action
int i = IntVal.intValue();
Object to primitive integer
float f = FloatVal.floatValue();
Object to primitive float
double d = DoubleVal.doubleValue();
Object to primitive double
long l = LongVal.longValue();
Object to primitive long

Converting Numbers to Strings using toString() method

Method calling
Conversion Action
str = Integer.toString(i);
Primitive integer i to String str
str = Float.toString(f);
Primitive float f  to String str
str = Double.toString(d);
Primitive double d to String str
str = Long.toString(l);
Primitive long l to String str

Converting String Object in to Numeric Object using static method ValueOf()

Method calling
Conversion Action
IntVal = Integer.ValueOf(str);
Convert String into Integer object
FloatVal = Float.ValueOf(str);
Convert String into Float object
DoubleVal = Double.ValueOf(str);
Convert String into Double object
LongVal = Long.ValueOf(str);
Convert String into Long object

Converting Numeric Strings to Primitive numbers using Parsing method

Method calling
Conversion Action
int i = Integer.parseInt(str);
Converts String str into primitive integer i
long l = Long.parseLong(str);
Converts String str into primitive long l

NOTE : parseInt() and parseLong() methods throw a Number Format Exception if the value of the str does not represent an integer. 


Class in JAVA


BASIC
All the objects that have similar properties and similar behavior are grouped together to form a class. Class is the java way to implement encapsulation.A class is a user defined data type and objects are the instance variables of class.



GENERAL FORM OF CLASS

A class is declared by use of the class keyword.The data, or variables, defined within a class are called instance variables because each instance
of the class (that is, each object of the class) contains its own copy of these variables.
class class name {
type instance variable;
//
type method name(parameter-list) {
//body of method
}
to access the instance variables and methods declared within a class and assign values to instance variable we need to create object of class using dot (.) operator.
object of class is created as classname obj =new classname();
class area(){
double length;
double width;
}
class calculatearea()
{
public static void main(String args[])
{
area obj=new area();
double area;
obj.length=9;
obj.breath=4;
area=obj.length*obj.breath;
System.out.printllln(“area is”+area);
}
}


concept of object
object of a class is created by new operator.

The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This
reference is, more or less, the address in memory of the object allocated by new.This reference is then stored in the variable.

History of JAVA




Java is a general-purposeconcurrentclass-basedobject-oriented computer programming language that is specifically designed to have as few implementation dependencies as 
 possible.
 
Java code that can run on one platform does not need to be recompiled to run on another.

Java applications are typically compiled to byte code (class file) that can run on any Java virtual machine (JVM) regardless of computer architecture.


James Gosling, Mike Sheridan, and Patrick
Naughton initiated the Java language project
 in June 1991. Java was originally designed for interactive television, but it was too advanced for the digital cable television industry at the time. The language was initially called Oak after an oak tree that stood outside Gosling's office. It went by the name Green later, and was later renamed Java, from Java coffee, said to be consumed in large quantities by the language's creators. Gosling aimed to implement a virtual machine and a language that had a familiar C/C++ style of notation.

Sun Microsystems released the first public implementation as Java 1.0 in 1995. It promised "Write Once, Run Anywhere" (WORA), providing no-cost run-times on popular platforms.
Major web browsers soon incorporated the ability to run Java applets within web pages, and Java quickly became popular.
In 1997, Sun Microsystems approached the ISO/IEC JTC1 standards body and later the Ecma International to formalize Java, but it soon withdrew from the process.
On November 13, 2006, Sun released much of Java as free and open source software, (FOSS), under the terms of the GNU General Public License (GPL). On May 8, 2007, Sun finished the process, making all of Java's core code available under free software/open-source distribution terms, aside from a small portion of code to which Sun did not hold the copyright.
Sun's vice-president Rich Green said that Sun's ideal role with regards to Java was as an"evangelist." 

Following Oracle Corporation's acquisition of Sun Microsystems in 2009–2010, Oracle has described itself as the "steward of Java technology with a relentless commitment to fostering a community of participation and transparency". 

This did not hold Oracle, however, from filing a lawsuit against Google shortly after that for using Java inside the Android SDK

Java software runs on laptops to data centers,game consoles to scientific supercomputers. There are 930 million Java Runtime Environment downloads each year and 3 billion mobile phones run Java.

On April 2, 2010, James Gosling resigned from Oracle.
Oracle Corporation is the current owner of the official implementation of the Java SE platform, following their acquisition of Sun Micro systems on January 27, 2010

This implementation is based on the original implementation of Java by Sun. The Oracle implementation is available for Mac OS XWindows and Solaris



Major release versions of Java, along with their release dates:

  • JDK 1.0 (January 21, 1996)
  • JDK 1.1 (February 19, 1997)
  • J2SE 1.2 (December 8, 1998)
  • J2SE 1.3 (May 8, 2000)
  • J2SE 1.4 (February 6, 2002)
  • J2SE 5.0 (September 30, 2004)
  • Java SE 6 (December 11, 2006)
  • Java SE 7 (July 28, 2011)

Monday, 26 August 2013

JAVA : Collections

                    Collections And Framework


                                   Collections
A Collection is a group of objects .The collection framework  defines  several interfaces  of  which the collection  interfaces of which the collection  interfaces is the foundation  upon  which the collection  framework is built .The collection interface declares the  core method  that a collection will have.
collection  provides java developers a set of classes and interfaces  that makes  it easier to handle   a collection of objects,in this way it works a bit like array but their size can be change dynamically  and it has more advanced behavior than array.

                                    Framework


Framework are repeatable ways of  solving problem. Framework  are a prescriptive set of buildings blocks and services .The developers  can use  to achieve  some goal.Basically , a frame work  provides  the infrastructure  to solve a type  of  a problem .A Framework  is  not the solution to a problem ,it is simply the tool with which  we struct  a  solution .

                             Collection Interfaces

Collection:-
Enables you to work  with  group  of  object ,it is  at  the top  of the collections hierarchy.

List:-
Extends collection to handle sequences  (list of objects ).

Set:-
Extends  collection to handle  sets ,which must  contain unique elements .

Sorted set:-
Extends set to handle sorted set.


                    Collection  Interface Methods

 

Boolean Add All (collection c):-
Adds  all the elements  of c to  the  invoking collection  return  true if the operation  succeeded otherwise  return  false.
Boolean Add (object obj.):-
Adds obj. to the  invoking  collection return true  if obj was added to collection otherwise  return  false.

Void clear ():-
Remove all elements from the invoking  collection

Boolean contains(object obj):-
Return true if obj is an element  of the invoking  collection.

Boolean is empty():-
Returns   true if the invoking  collection  is  empty.

Boolean remove(object obj):-
Remove are instance  of obj. from the  invoking collection.

                           Collection Classes

Abstract Collection:-
Implements  most  of   the  collection  interfaces .

Abstract List:-
Extends  Abstract  collection  &  implements  most  of   the list  intefaces'

Abstract Sequential List:-
Extends  abstract list.

Linked List:-
Implements  a linked  list  by  extending  abstract sequential list. It is Designed to give better performance when you insert or delete elements from the middle of the collection. 

Array List:-  
Implements  a dynamic  array  by extending   abstract list.

Abstract Set:-
Extends   abstract  coolection& implements  most of the  set  interface.

Hash Set:-
Extends  abstract  set   for  use  with  a hash table.It prevents duplictes in the collection  and it can find a given element quickly in a collection..

Linked Hash Set:-
Extends  hash  set to allow insertions.
Tree Set:-
Implements  a set  stored  in a  free  explicits and prevents the duplicates.



Thursday, 1 August 2013

Installing JAVA AND Setting CLASS PATH


 Installing JAVA AND Setting CLASS PATH




  •        Install jdk 7.4(latest version) or any  other lower                    version.
  •        Set the class path for running the java program..
  •        Left click the my computer option.
  •       Click on the properties.
  •       Click on system properties.
  •       Click on advanced.
  •       Click on environment variable.
  •       Two different sections will be shown from lower section             select “path” and click on edit
  •        Open the location where jdk was installed and go inside              bin. (“C:\Program Files\Java\jdk1.7.0_04\bin”).
  •      Copy the address and paste it into variable value but be             careful not to delete previous entries and put”;”.
  •         Press OK.

After following these steps only you would be able to run a java program written in a simple text editor ,using dos comrade.
There are various other also various user friendly application which serves as a handy tool (net beans) in creating a java program and compiling it and running it without going through above stated points.

But as a beginner users are advised to create the program in notepad or any other text editors and compile them and run them through DOS. It will help in understanding java concept clearly.

Compiling and running a java program after the class path is set will be discussed in next post.....

Saturday, 27 July 2013

Top wesbites to learn Java

Wish to create your software games and web applications .Here i suggest some resource for you. Now you habe to practice the things which you read theoretically. It will help to sharp your skills .Apart from us LANG-ADDA there some more website to learn java.

Top 5 website
  1. http://docs.oracle.com/javase/tutorial
  2. http://thenewboston.org/tutorials.php
  3. http://javabeginner.com/
  4. http://javalessons.com/
  5. http://w3schools.com/js/


The Sites are;-

  1. http://www.javaalmanac.com - The online counter part of  Java Developer's Almanac
  2. http://www.onjava.com - O'Reilly's Java website. articles on java weekly.
  3. http://java.sun.com - The official Java developer website - new articles. 
  4. http://www.developer.com/java - Java articles
  5. http://www.java.net - The Java  website hosted by Sun Microsystems. 
  6. http://www.builder.com - Cnet's Builder.com website - All technical articles 
  7. http://www.ibm.com/developerworks/java - IBM's Developerworks; the Java section. 
  8. http://www.javaworld.com - One of the originals.  updates of Java articles. 
  9. http://www.devx.com/java - Java articles hosted at DevX. 
  10. http://www.fawcette.com/javapro - The JavaPro online magazine website. \
  11. http://www.sys-con.com/java - The Java Developers Journal online magazine website. 
  12. http://www.javadesktop.org - The desktop Java community hosted at Java dotnet. 
  13. http://www.theserverside.com - Often considered the resource for all discussion server-side Java specific.
  14. http://www.jars.com - The Java  Covers frameworks and applications. 
  15. http://www.jguru.com - A great source for Q&A style interaction in the community. 
  16. http://www.javaranch.com 
  17. http://www.ibiblio.org/javafaq/javafaq.html - The comp.lang.java FAQ - questions asked and  answered,
  18. http://java.sun.com/docs/books/tutorial/ - The Official Java tutorial from Sun - very useful for almost any feature set. 
  19. http://www.javablogs.com - Blog aggregator for the most active Java-based blogs throughout the internet. 
  20. http://java.about.com/ - Java news and articles