double x=5;
println
This will print the item and put the cursor in new line.
printf
System.out.printf("Hello, %s. Next year, you'll be %d", name, age);
write
You can see formatting output in java here.
Every Java program has a main method with a String[] args parameter. This parameter indicates that the main method receives an array of strings, namely, the arguments specified on the command line.
For example, consider this program:
public class Message
{
public static void main(String[] args)
{
if (args[0].equals("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");
// print the other command-line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " + a[i]);
System.out.println("!");
}
}
java Message -g cruel world
Differing from cpp
In the main method of a Java program, the name of the program is not stored in the args array. For example, when you start up a program as
byte x,y,z; /* 08bits long, not assigned, multiple declaration */ short numberOfChildren; /* 16bits long */ int counter; /* 32bits long */ long WorldPopulation; /* 64bits long */ float pi; /* 32bit single precision */ double avagadroNumber; /* 64bit double precision */ boolean signal_flag; /* true or false only */ char c; /* 16bit single Unicode character */
clone() | equals() | copy(Object src) | finalize() | getClass() |
hashCode() | notify() | notifyAll() | toString() | wait() |
public class GraphicsBox extends Box
The GraphicsBox class assumes or inherits all the properties of the Box class and can now add its own properties and methods as well as override existing methods. Overriding means creating a new set of method statements for the same method signature (name, number of parameters and parameter types). For example:
A java variable can be declared using the keyword final. Then the final variable can be assigned only once. You cannot be modify it afterwards. However it can be used in different contexts.
Following are the places where final can be used:
Other effects of final:
Notice how using final
is an entirely negative act. The final
keyword works by subtracting, limiting default language mechanisms: the ability to override a method, to set a variable or a field. The motivations behind using final
fall into three broad categories: correctness, robustness, and finally performance. Seeing them 1 by one.
static
, final
is used to flag constants. This usage is well-known to all Java programmers, so I won't expand much on it. It is useful to know that the value of a field declared constant in that manner will be computed statically if possible, at compile-time. private static final int ERROR_CODE = 1 + 3 * 4 / 2;
public static final String ERROR_MESSAGE = "An error
occurred with code=" + ERROR_CODE;
public void doSomething(final int i, final int j){
// ...
}
final
is used here to ensure the two indexes i
and j
won't accidentally be reset by the method. It's a handy way to protect against an insidious bug that erroneously changes the value of your parameters. Generally speaking, short methods are a better way to protect from this class of errors, but final parameters can be a useful addition to your coding style. public void doSomething(int i, int j){
final int n = i + j; // must be declared final
Comparator comp = new Comparator() {
public int compare(Object left, Object right) {
return n; // return copy of a local variable
}
};//note the semicolon here
}
public class MyClass{
//initializing hereitself
private final int i = 2;
}
public class MyClass{
private final int i;
public MyClass()
{
i = 2;
}
}
While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final:
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
As the comments imply, it is illegal for B to inherit A since A is declared as final.
‘final’ should not be called as constants. Because when an array is declared as final, the state of the object stored in the array can be modified. You need to make it immutable in order not to allow modifcations. In general context constants will not allow to modify. In C++, an array declared as const will not allow the above scenario but java allows. So java’s final is not the general constant used across in computer languages.
A variable that is declared static final is closer to constants in general software terminology. You must instantiate the variable when you declare it static final.
Definition as per java language specification (third edition) – 4.12.4 is “A final variable may only be assigned to once.”(§4.1.2). See notes on final w.r.t Java memory model here -
Java language specification tries to redefine the meaning of constant in the following way!
We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).
Final is used to construct immutable objects in java. See – Immutable Objects
int[] x;or
int x[];Both are legal positions for the brackets. To declare a multidimensional array, use multiple sets of brackets, e.g.
int i[][];
declares a two dimensional array. Note that, for example, int[]i[];
is also legal, and means the same thing. In Java, multidimensional arrays can be "not square" i.e. they are just arrays of arrays, and each of those constituent arrays can be of a different size. new
keyword to construct them. For example having declared an array i: int[] i;you then construct the array and assign it to i as follows:
i = new int[10];The size of the array is in the brackets (in this example 10). It is common to do both operations in one statement:
int i[] = new int[10];
int array[] = new int[15];
for(int j=0; j
array[j]=j;
}
char c[]= new char[] {'a','b','c','d','e'};or you can use
char c[]= {'a','b','c','d','e'};
protected
- can only be accessed by classes in the same package or subclasses of this class. This frequently surprises experienced developers, especially those with a prior backround in the mutant hybrid of object orientated programming and assembly language known as 'C++' :-) To fair the name is misleading, as it sounds like it restricts access, where as it in fact it adds subclasses outside the package to the list of things that can access the item in question, as compared to using "default" access. public
- can be accessed by any other class. private
- can only be accessed from inside the class. public
, abstract
or final
: public
- is visible outside of its package. Without this modifier, the class cannot be accessed outside its package. abstract
- cannot be instantiated, is allowed to contain abstract
methods. final
- cannot be subsclassed. private
, protected
, public
, static
, final
, native
or abstract
: private
- can only be accessed from inside the class. Private members are not inherited by subclasses. Inner classes can be declared private
. protected
- can only be accessed by classes in the same package or subclasses of this class. public
- can be accessed by any other class. static
- belongs to the class rather than any particular instance of the class. For variables, effectively, there is just one copy of this variable for all instances of the class, and if an instance changes the value, the other instances see that new value. For methods, it means the method can be called without having created an instance, but within the methodd you cannot use the this
keyword, or refer to instance variables and methods directly (without creating an instance and referring to the variable/class in that instance). For inner classes, it means they can be instantiated without having an instance of the enclosing class, but as with static methods, the methods of the inner class cannot refer to instance variables or methods of the enclosing class directly. final
- cannot be changed. Variables are constants, methods cannot be overridden, classes cannot be subclassed. Since Java1.1 you can declare the variable without assigning a value. Once you assign a value, you cannot change it. The are known as 'blank' finals, are frequently used for things like constants you wish to initialise from a configuration file. native
- a method which is not written in java and is outside the JVM in a library. abstract
- a method which is not implemented. Must be implemented in a subclass if that subclass is to be 'concrete' and allow people to instantiate it. implements
or extends
keywords are not used. For example the following line causes the method to return an object which is an instance of an anonymous nested class: return new SomeClass() { /*body of the anonymous class goes here*/ };You might like to think of an anonymous nested class as part of a really long
new
statement, which happens to contain a class definition, and which is why it has a ";" at the end. The following example calls someMethod()
, passing an instance of the anonymous nested class: someMethod(new SomeClass() { /*body of the anonymous class goes here*/ });In both cases
SomeClass()
is not the name of the anonymous class (anonymous means it has no name) rather is it the name of the class that you are extending or the interface you are implementing. These classes cannot define a constructor, as they do not have a name that you can use to declare the constructor method. If SomeClass() is a class, the default constructor of that class is called, if you want to use a non-default constructor instead, you supply arguments e.g.: return new SomeClass(12) { /*body of the anonymous class goes here*/ };will call the SomeClass constructor which takes an int.
Inner x = new Inner();
constructs an instance of Inner where Inner is a nested class defined in the current class. this
object exists, or the current this
object is not an instance of the outer class. Outer.Inner y = new Outer().new Inner();The above creates an instance of Inner called y, but it had to construct an instance of Outer first. The following example creates the Outer instance on a separate line, the syntax in the second line is the one you use when you already have an instance of the outer class.
Outer x = new Outer();If Inner is static, you can use:
Outer.Inner y = x.new Inner();
Outer.Inner I= new Outer.Inner();
final
, in addition to the above. For a given class, determine if a default constructor will be created and if so state the prototype of that constructor. |
classname()
where classname is the name of you class. A default constructor is automatically created only if you do not create any constructors in your class. If you create a non-default constructor (i.e. one that takes an argument), then you may have to create a default one yourself, if you want there to be one. super(...)
(to use a constructor in the parent) or this(...)
. If you use such calls, they must be the first thing in the constructor.
|
|
Seq | Usage | Seq | Usage |
---|---|---|---|
\b | backspace | \\ | backslash |
\f | formfeed | \" | double quote |
\n | newline | \' | single quote |
\r | carriage return | \### | Octal encoded character |
\t | horizontal tab | \uHHHH | Unicode encoded character |