Friday, January 22, 2010

Core Java Tutorials - General Concepts

byte 8bit, short 16bit, int 32bit, long 64bit, float 32bit, double 64bit, char 16bit, boolean

The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement
ArrayList a = new ArrayList() ;
a.add("1");
a.add(new Test());
for (Object item:a){
System.out.println(item);
//Output 1 Test@4523
}


You can use a construct called varargs to pass an arbitrary number of values to a method.
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name.

public void test(int a, String...strings){//varargs should be last parameter
System.out.println(strings[1]);
}
obj.test("a","b","c");

//Output b

Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost.
Reference data type parameters, such as objects, are also passed into methods by value.This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.

NOTE:
public void swap(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
swap(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}


//OUTPUT:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0



Point originOne = new Point(23, 94);



Covariant return type, means that the return type is allowed to vary in the same direction as the subclass.

Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.

a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

You can declare an inner class within the body of a method. Such a class is known as a local inner class. You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes.
The enum declaration defines a class (called an enum type). All enums implicitly extend java.lang.Enum

Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.

There are three annotation types that are predefined by the language specification itself: @Deprecated, @Override, and @SuppressWarnings.
Annotations have a number of uses, among them:
Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.

Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
Runtime processing — Some annotations are available to be examined at runtime.

An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
javac -source 1.4 Foo.java
the implements clause follows the extends clause

Marker Interface have no methods defined within them.

You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.

An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.

public final Class getClass() : Returns the runtime class of an object.
By definition, if two objects are equal, their hash code must also be equal.
The syntax for these two java.io.PrintStream methods (format and printf) is the same:
public PrintStream format(String format, Object... args)
System.out.format("The value of the float variable is %f, while the value of the integer variable is %d, and the string is %s", floatVar, intVar, stringVar);
System.out.format("%f%n", java.lang.Math.PI);
// --> "3.141593"
System.out.format("%10.3f%n", java.lang.Math.PI); /
/ --> " 3.142"

java.text.DecimalFormat class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(new java.text.DecimalFormat("###,###.###").format(123456.789));
// -->123,456.789

Note : Using the static import language feature, you don't have to write Math (all methods are static) in front of every math function (say MATH.cos(angle)):
import static java.lang.Math.*;
The random() method returns a pseudo-randomly selected number between 0.0 and 1.0.
The MIN_VALUE and MAX_VALUE constants contain the smallest and largest values that can be contained by an object of that Number (abstract class) type.


A wrapper class that "wraps" the char in a Character object
if you pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character (or any primitive wrapper classes) for you. This feature is called autoboxing—or unboxing, if the conversion goes the other way.

Character ch = 'a'; // the primitive char 'a' is boxed into the Character object ch
the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.

String str = String.format(String format, Object... args);
String[] split(String regex)
//split on regex match
String trim()
//trim whitespaces
The String class provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf().

A StringBuffer class that is exactly the same as the StringBuilder class, except that it is thread-safe by virtue of having its methods synchronized.
new StringBuilder();//creates empty builder, capacity 16
Generics add stability to your code by making more of your bugs detectable at compile time.
first create a generic type declaration by changing the code "public class Box" to "public class Box"; this introduces one type variable, named T, that can be used anywhere inside the class.

public class Box {
private Object object;
public void add(Object object){this.object = object;}
public Object get(){return object; }
}


Since its methods accept or return Object, you're free to pass in whatever you want (Integer, String etc.), provided that it's not one of the primitive types. However, should you need to restrict the contained type to something specific (like Integer)

public class Box<> { //Generic version of the Box class
private T t;
// T stands for "Type"
public void add(T t){this.t = t;}
public T get(){return t;}
}


From Client main method use it as, so errors can be detected at compile time
Box integerBox = new Box();
Box integerBox = new Box(); //also allowed
integerBox.add(new Integer(10));
Integer someInteger = integerBox.get();
public class Box { ...} would be allowed.
public class Box {...}
//Bounded type parameter

Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors.
public <> void inspect(U u){ ... }
public <> void inspect(U u){ ... }

To specify additional interfaces that must be implemented, use the & character, as in:
<>
You can perform a generic type invocation, passing Number as its type argument, and any subsequent invocation of add will be allowed if the argument is compatible with Number: (this is Subtyping)
Box box = new Box();
box.add(new Integer(10));
// OK
box.add(new Double(10.1));
// OK

To specify a cage capable of holding some kind of animal: (Wildcards)
Cage someCage = ...;
Read "? extends Animal" as "an unknown type that is a subtype of Animal, possibly Animal itself".

The code , therefore, would be read as "an unknown type that is a supertype of Animal, possibly Animal itself".

An unbounded wilcard, which simply looks like . An unbounded wildcard is essentially the same as saying .
When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.
For instance, Box is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments.
This means that you can't find out what type of Object a generic class is using at runtime.

You could import Rectangle and its public nested classes by using the following two statements.
import graphics.Rectangle;
import graphics.Rectangle.*;
Be aware that the second import statement will not import Rectangle.

1 comment:

  1. Static methods cannot be overriden.
    If you have a static method in base class and if you have a method with same signature in sub class, you wouldnt notice a compiler error but overriding doesnt happen.If you create an object with reference type base class and actual object of subclass and when you invoke the static method, the method in the base class gets called and not the subclass.

    ReplyDelete