JavaIntellectualTricks

Java Coding Standards

Whenever we are writing java code, it is highly recommended to follow coding standards.
Whenever we are writing any component, it's name should reflect the purpose of that component (functionality). The main advantage of this approach is readability and maintainability of the code will be improved.
Example:
//Not Recommended
class A {
 public int m1(int x, int y) {
  return x + y;
 }
}
//Recommended
package com.learning.java public class Calculator { public static int sum(int firstNumber, int secondNumber) { return firstNumber + secondNumber; } }
Coding standard for class:
Usually class names are nouns, should starts with upper case character and if contains multiple words every inner word should starts with upper case character.
Example:
String
StringBuilder
Account
Student

Coding standard for interfaces:
Usually interface names are adjectives, should starts with upper case character and if contains multiple words every inner word should starts with upper case character.
Example:
Runnable
Serializable
Comparable

Coding standard for methods:
Usually method names are either verbs or verb-noun combinations, should starts with lower case character and if contains multiple words every inner word should starts with upper case character.(camel case convention)
Example:
print()
run()
start()
setName()
getSalary()

Coding standard for variable:
Usually variable names are nouns, should starts with lower case character and if contains multiple words every inner word should starts with upper case character.(camel case convention)
Example:
name
age
MobileNumber
Coding standard for constant:
Usually constant names are nouns, should contain only upper case characters and if it contains multiple words, then these words are separated with underscore(_) symbol.
Example:
MAX_VALUE
PI
MAX_PRIORITY
MIN_PRIORITY

Note: Usually we can declare constants with public static and final modifiers.

Coding standard for JavaBean:
A Java Bean is a simple java class which contains some private variables along with public setter and getter methods for those variables.
Example:
public class Student{
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
class name ends with Bean is not official convention. i.e  “StudentBean” naming convention is not recommended.

Syntax for setter method:

  • It should be public method.
  • Return type should be void.
  • Method name should be prefixed with set
  • method should contain some arguments

Syntax for getter method:

  • It should be public method.
  • Return type should not be void.
  • Method name should be prefixed with get
  • method should not contain any argument

Note: for boolean property getter method name can be prefixed with either “get” or “is”, but recommended to use “is”
Example:
private boolean empty;
public boolean isEmpty(){
return empty;
}
public boolean getEmpty(){
return empty;
}

Coding standard for Listeners:
case 1:
To register a listener:
method name should be prefixed with “add”
method should be public
Example:
public void addMyActionListener(myActionListener  l) //valid
public void registerMyActionListener(myActionListener l) //Invalid
public void addMyActionListener(ActionListener l) //Invalid

case 2:
To de-register a listener:
method name should be prefixed with “romove”
method should be public
Example:
public void removeMyActionListener(myActionListener  l) //valid
public void unRegisterMyActionListener(myActionListener l) //Invalid
public void addMyActionListener(ActionListener l) //Invalid
public void deleteMyActionListener(myActionListener l) //Invalid

Command Line Arguments


  • The arguments which are passing from command prompt are called command line arguments.
  • With these command line arguments JVM will create an array and by passing that array as argument JVM will call main().

Example:
>java Test A B C
A=args[0];
B=args[1];
C=args[2];

The main objective of command line arguments is we can customize behavior of the main().

Q. Why java main( ) takes always String as parameter?

Case 1:
class Test {
 public static void main(String[] args) {
  for (int i = 0; i <= args.length; i++) {
   System.out.println(args[i]);
  }
 }
}
>java Test A B // o/p: A B  ArrayIndexOutsOfBoundsException
>java Test A B C // o/p: A B C  ArrayIndexOutsOfBoundsException
If we replace <= with < ,then we won't get any run time exception.

Case 2:
class Test {
 public static void main (String[] args){ 
  String[] argh={“X”,”Y”,”Z”}; 
  args=argh; 
  for(String s: args){ 
   System.out.println(s); 
  } 
 }
}
o/p:
>java Test A B // o/p: X Y Z
>java Test A B C // o/p: X Y Z    

Case 3:
With in main() command line arguments are available in String form.
class Test {
 public static void main(String[] args) {
  System.out.println(args[0] + args[1]);
 }
}
> javaTest 10 20 //o/p: 1020

Case 4:
Usually space itself is the separator between command line arguments. If our command line arguments itself contains the space then we have to enclose that command line arguments with in double quotes.
class Test {
 public static void main(String[] args) {
  System.out.println(args[0]);
 }
}
> java Test “Note Book” //o/p:  Note Book

Exploring main( ) method

Whether class contains main( ) method or not and whether main() is declared according to requirement or not , these things won't be checked by compiler. At run time JVM is responsible to check these things. If JVM unable to find main(), then we will get run time exception saying ”NoSuchMethodError: main”

class Test{
}
>javac Test.java // No error
>java Test // NoSuchMethodError: main

At run time JVM always searches for the main() with the following prototype.
public static void main(String[] args)
Here:
public refers – to call by JVM from anywhere
static refers – without existing object also JVM has to call this method for one time.
void refers – main() won't return anything to JVM
main refers – this is the name which is configured inside JVM
String[] args refers – command line arguments

The above syntax is very strict and we perform any change then we will get run time exception saying NoSuchMethodError: main

Even though the above syntax is very strict, the following changes are acceptable.

  • Instead of public static , we can take static public i.e the order of modifier is not important.             We can declare String array in any acceptable form

main(String[] args)
main(String  []args)
main(String  args[])

  • We can take any valid java identifier instead  of args.
main(String[]  purna)

  • We can replace String array with var-arg parameter

main(String...  args)

  • We can declare main() with the following modifiers

final, synchronized, strictfp
class Test{
static final synchronized strictfp public void main(String...  purna){
System.out.println(“valid main method”);
}
}

Q1. Which of the following main() declarations are valid?
1. public static void main(String args) // (Invalid)
2. public static void Main(String[] args) // (Invalid)
3. public  void main(String[] args) // (Invalid)
4. public static int  main(String[] args) // (Invalid)
5. final synchronized strictfp public void main(String[]  args) // (Invalid)
6. final synchronized strictfp public  static void main(String[]  args) // (valid)
7. public static void main(String...  args) // (valid)

Q2.In which of the above cases we will get compile time error ?
We won't get compile time error anywhere. But except last two cases in remaining we will get runtime exception saying  NoSuchMethodError: main

Case 1: 
Overloading of the main method is possible ,but JVM will always call String[] arguments main() only.
The other overloaded method, we have to call explicitly like normal method call.
class Test{
public static void main(String[] args){
System.out.println(“String []”);
}
public static void main(int[] args){ //overloaded methods
System.out.println(“int []”);
}
}
o/p: String [ ]

Case 2:
inheritance concept applicable for main(), hence while executing child class if child does not contain main(), then parent class main () will be executed.

//p.java
class P{
public static void main(String[] args){
System.out.println(“Parent main”);
}
}
class C extends P{
}
>javac P.java
>java P  // o/p: Parent main
>java C // o/p: Parent main

Case 3: 
It seems overriding concept applicable for main(), but it is not method overriding, but it is method hiding.
//p.java
class P{
public static void main(String[] args){
System.out.println(“Parent main”);
}
}
class C extends P{
public static void main(String[] args){ // It is method hiding but not method overriding
System.out.println(“Child main”);
}
}
>javac P.java
>java P  // o/p: Parent main
>java C // o/p: Child main

Note:
For main() inheritance and overloading concepts are applicable, but overriding concept is not applicable. Instead of overriding,  method hiding is applicable.

1.7 version enhancements w.r.t main():

Until 1.6 version, if the class doesn't contain main(), then we ll get run time exception saying  NoSuchMethodError: main. But from 1.7 version onwards instead of   “NoSuchMethodError: main” we will get more elaborated information.
Example:
class Test{
}
1.6 version:
>javac Test.java
>java Test //R.E: NoSuchMethodError: main
1.7 version:
>javac Test.java
>java Test   //R.E. Main method not found in class Test, please define the main method as:
public static void main(String[] args)

From 1.7 on wards main() is mandatory to start program execution,hence even though class contains static block it won't be executed if the class does not main().
Example 1:
class Test{
static {
System.out.println(“static block”);
}
}
1.6 version:
>javac Test.java
>java Test // static block & R.E: NoSuchMethodError: main
1.7 version:
>javac Test.java
>java Test //R.E. Main method not found in class Test, please define the main method as:
public static void main(String[] args)
Example 2:
class Test{
static {
System.out.println(“static block”);
System.exit(0);
}
}
1.6 version:
>javac Test.java
>java Test // static block
1.7 version:
>javac Test.java
>java Test //R.E. Main method not found in class Test, please define the main method as:
public static void main(String[] args)

Example 3:
class Test{
static {
System.out.println(“static block”);
}
public static void main(String[] args){
System.out.println(“main method”);
}
}
1.6 version:
>javac Test.java
>java Test // static block
    // main method
1.7 version:
>javac Test.java
>java Test // static block
    // main method

1.6 flowchart:
1. Identification of static members
2. execute static blocks and static variable assignments
3. check for main()

  • If it is available execute main()
  • If it is not available R.E: NoSuchMethodError: main
1.7 flowchart:
1. check for main()

  • If it is available identifies static members then execute static blocks and static variable assignments
  • If it is not available Error: R.E. Main method not found in class Test, please define the main method as: public static void main(String[] args) then program terminates.
Q. Without writing main() is it possible to print some statements to the console?
Ans: Yes by using static block, but this rule is applicable until 1.6 versions, but from 1.7 version onwards it is impossible to print some statements to the console with out writing main().



var- arg methods

Variable Number of Argument methods:

Until 1.4 version , we cannot declare a method with variable number of arguments. If there is a change in number of arguments, compulsory we should go for new method, which increases length of the code and reduces readability. To overcome this problem SUN people introduced var-args methods in 1.5 version. According to this we can declare a method which can take variable number of arguments, such type of methods are called var- arg methods.
Syntax: methodName(int... x);


  • We can call this method by passing any number of int values including 0 number. i.e.  sum(int... x) then we can call this sum method by sum(); sum(10); sum(10,20); sum(10,20,30); sum(10,20,30,40);

class Test{
public static void sum(int... x){
System.out.println(“var-arg method”);
}
public static void main(String args []){
sum();
sum(10);
sum(10,20);
sum(10,20,30);
sum(10,20,30,40);
}
}
>javac Test.java
>java Test
o/p:      var-arg method
    var-arg method
    var-arg method
    var-arg method
    var-arg method

  • Internally var-arg parameter is converted in to one dimensional array. Hence with in the var-arg method we can differentiate values by using index.

class Test{
public static void sum(int... x){
int total=0;
for(int x1: x){
total=total+x1;
}
System.out.println(“Sum is: ”+ total);
}
public static void main(String args []){
sum();
sum(10);
sum(10,20);
sum(10,20,30);
sum(10,20,30,40);
}
}
o/p:   Sum is : 0
Sum is : 10
Sum is : 30
Sum is:  60
Sum is:  100

Q. Which of the following are the valid var-arg declarations?
1. m1(int...  x)  (valid)
2. m1(int   ...x) (valid)
3. m1(int...x)    (valid)
4. m1(int  x...) (Invalid)
5. m1(int.  ..x) (Invalid)
6. m1(int  .x..) (Invalid)

  • we can use var-arg parameter with normal parameter i.e

m1(int x, int... y)
m1(String s,double... d)
If we mix normal parameter with var-arg parameter, then var-arg parameter should be last parameter. i.e.
m1(double... d,String s) (Invalid)
m1(char ch,d,String... s) (valid)

  • Inside var-arg method we can take only one var-arg parameter and we can't take more than one var-arg parameter. i.e.

m1(int...  x ,double... d) (Invalid)

  • Inside a class we can't declare var-arg method and corresponding 1-D array method simultaneously, otherwise we ' ll get compile time error.

class Test{
public static void m1(int...  x){
System.out.println(“int...”);
}
public static void m1(int[]  x){
System.out.println(“int[]”);
}
}
C.E.: cannot declare both m1(int []) and m1(int...) in Test

  • In general, var-arg method will get least priority i.e if no other method matched then only var-arg method will get the chance to execute

.It is exactly same as default case inside switch.
class Test{
public static void m1(int...  x){
System.out.println(“var-arg method”);
}
public static void m1(int  x){
System.out.println(“Normal Method”);
}
public static void main(String args []){
m1(); //  var-arg method
m1(10); // Normal Method
m1(10,20); // var-arg method
}
}

Equivalence between var-arg parameter and one dimensional array:

case 1: Where ever one dimensional array is present, we can replace with var-arg parameter.
m1(int[]  x) = = m1(int...  x) (valid)
Example: main(String[] args) = = main(String...  args)

case 2:  Where ever var-arg parameter ispresent, we can't replace with  one dimensional array.
m1(int...  x) = = m1(int[]  x) (invalid)

Note: 
1. m1(int...  x) = =  int[]  x
we can call this method by passing a group of int values and x will become one dimensional array.
2. m1(int[]...  x) = = int[][]  x

  • We can call this method by passing a group of dimensional int arrays and x will become 2 D int array

class Test{
public static void main(String args []){
int[] a={10,20,30};
int[] b={40,50,60};
m1(a,b);
}
public static void m1(int[]...  x){
for(int[]  x1: x){
System.out.println(x1[0]); // 10, 40
}
}
}

Variables

Types of variable:
Based on type of value represented by a variable, all variables are divide in to 2 types.
1.Primitive variables
Primitive variables can be used to represent primitive values.
Example:
int x=10; // here x is called as primitive variables
2.Reference variables
Reference variables can be used to refer objects
Example:
Student s=new Student(); // here s is called as reference variable

Based on position of declaration and behavior all variables are divide in to 3 types.
1. instance variables
2. static variables
3. local variables

Instance variables:
  • If the value of a variable is varied from object to object, such types of variable are called as instance variables.
  • For every object, a separate copy of instance variable is created.
  • Instance variables should be declared with in the class directly, but outside of any method or constructor or block.
  • Instance variables are created when an object is created and destroyed at the time of object destruction, hence the scope instance variable is exactly same as object.
  • Instance variables will be stored in the heap memory as a part of object.
  • We can't access instance variables directly from static area, but we can access by using object reference.But we can access instance variables directly from instance area.
Example:
class Test{
int x=100;
public static void main(String [] args){
System.out.prinln(x); // C.E Non-static variable x cannot be referenced from a static context
Test t= new Test();
System.out.prinln(t.x);  //100
}
public void m1(){
System.out.prinln(x);  //100
}
}
For instance variables JVM is always providing default initial value and we are not required to perform initialization explicitly.
Example:
class Test{
int i;
boolean b;
double d;
String s;

public static void main(String [] args){
Test t= new Test();
System.out.prinln(t.i);  //0
System.out.prinln(t.b); //false
System.out.prinln(t.d); //0.0
System.out.prinln(t.s); //null
}
}
Instance variables are also known as object level variables or attributes.

Static variables:
  • If the value of the variable not varied from object to object, then it is not recommended to declare variable as instance variable. We have to declare such type variables as class level by using static modifier.
  • In the case of instance variables for every object a separate copy will be created, but in the case of static variables, a single copy will be created at class level and shared by every object of the class.
  • Instance variables should be declared with in the class directly, but outside of any method or constructer or block.
  • Instance variables are created at the time of class loading and destructed at time of class unloading, hence the scope of the static variables is exactly same as the scope of the .class file.

If we are trying to run a simple java program the following steps are carring on:-
> java Test

1. start the JVM.
2. create and start main thread.
3. Locate the Test.class file
4. Load the Test.class file
5. Execute main() method
6. Unload  Test.class file
7. Terminate main thread
8. Shutdown the JVM

static variables will be stored in method area.
We can access static variable either by object reference or by class name, but recommended to use class name.
With in the same class it is not required to use class name and we can use directly.
class Test{
int x=100;
public static void main(String [] args){
System.out.prinln(x); // C.E Non-static variable x cannot be referenced from a static context
Test t= new Test();
System.out.prinln(t.x);  //100
}
public void m1(){
System.out.prinln(x);  //100
}
}

For instance variables JVM is always providing default initial value and we are not required to perform initialization explicitly.
Example:
class Test{
int x=10;
public static void main(String [] args){
Test t= new Test();
System.out.prinln(t.x);  //10
System.out.prinln(Test.x); //10
System.out.prinln(x); //10
}
}
We can access static variables directly from both instance and static areas.
class Test{
int x=100;
public static void main(String [] args){
System.out.prinln(x); // C.E Non-static variable x cannot be referenced from a static context
Test t= new Test();
System.out.prinln(t.x);  //100
}
public void m1(){
System.out.prinln(x);  //100
}
}

For instance variables JVM is always providing default initial value and we are not required to perform initialization explicitly.
Example:
class Test{
int i=10;
public static void main(String [] args){
System.out.prinln(i);  //10
}
public void m1(){
System.out.prinln(i);  //10
}
}
For static variables JVM will provide default values and we are not required to perform initialization explicitly.
Example:
class Test{
static int i;
static boolean b;
static double d;
static String s;

public static void main(String [] args){
System.out.prinln(Test .i);  //0
System.out.prinln(Test .b); //false
System.out.prinln(Test .d); //0.0
System.out.prinln(Test .s); //null
System.out.prinln(i);  //0
System.out.prinln(b); //false
System.out.prinln(d); //0.0
System.out.prinln(s); //null
}
}
static variables are also known as class level variables or fields.
Example:
class Test{
static int x=10;
int x=20;
public static void main(String [] args){
Test t1=new Test();
t1.x=111;
t1.y=222;
Test t2=new Test();
System.out.prinln(t2.x+”--”+t2.y);  //111--20
}
}

Local variables:
  • The variables which are inside the constructor, block or method are called local variables.
  • Sometimes to meet temporary requirements of the programmer, we can declare a variable inside a method, block or constructor . Such type of variables are also called as local/automatic/stack/temporary variable.
  • Local variables will be stored inside stack memory.
  • Local variables will be created while executing the block in which we declared it .
  • Once block execution completes, automatically local variables will be destroyed. Hence the scope of local variable is the block in which we declared  it.

Example 1:
class Test{
public static void main(String [] args){
int i=0;
for(int j=0;j<3;j++){
i=i+j;
}
System.out.prinln(i+” ”+j);  // C.E cannot find symbol, symbol: variable j, location: class Test
}
}
Example 2:
class Test{
public static void main(String [] args){
try{
int j=Integer.parseInt(“ten”);
}
catch(NumberFormatException  nfe){
j=10;  // C.E cannot find symbol, symbol: variable j, location: class Test
}
 System.out.prinln(j);  // C.E cannot find symbol, symbol: variable j, location: class Test
}
}

For local variables JVM won't provide default values, compulsorily we should perform initialization explicitly before using that variable i.e if we are not using then, it is not required to perform initialization.

Example 1:
class Test{
public static void main(String [] args){
int i;
System.out.prinln(“Hello”); // Hello
}
}
Example 2:
class Test{
public static void main(String [] args){
int i;
System.out.prinln(i); // C.E : variable i might not have been initialized
}
}
Example 3:
class Test{
public static void main(String [] args){
int i;
if(args.length>0){
x=10;
}
System.out.prinln(i); // C.E : variable i might not have been initialized
}
}
Example 4:
class Test{
public static void main(String [] args){
int i;
if(args.length>0){
x=10;
}
else{
x=20;
}
System.out.prinln(i);  // No Error //Java Test  A B then o/p=10, //Java Test  then o/p=20
}
}
Note :
1. It is not recommended to perform initialization for local variables inside logical blocks because there is no guarantee for the execution of these blocks always at run time.
2. It is highly recommended to perform  initialization for local variables  at the time of declaration at least with default values.
3. The only applicable modifier for local variables is final. Bymistake if we are trying apply any other modifier then we 'll get compile time error.

Example:
class Test{
public static void main(String [] args){
public int x=10; // C.E Illegal start of expression
private int x=10; // C.E Illegal start of expression
protected int x=10; // C.E Illegal start of expression
static int x=10; // C.E Illegal start of expression
transient int x=10; // C.E Illegal start of expression
volatile int x=10; // C.E Illegal start of expression
final int x=10; // No error
}
}
Note:
If we are not declaring with any modifier then by default it is default. But this rule is applicable only for instance and static variables but not for local variables.

Conclusions:
1. For instance and static variables JVM is providing deafult values and we are not required to perform initialization explicitly. But for local variaable JVM won't provide deafult values and we are  required to perform initialization explicitly before using that variable.
2. Instance and static can be accessed by multiple threads simultaneously and hence these are not thread safe. But in the case of local variables for every thread a separate copy will be created and hence local variables are thread safe.
3. Every variable in java should be either instance or static or local. Every variable in java should be either primitive or reference. So the various possible combinations of variable in java are instance-primitive, instance-reference, static-primitive, static-reference, local-primitive and local-reference.

UnInitialized arrays:
class Test{
int[] x;
public static void main(String [] args){
Test t=new Test();
System.out.println(t.x); //null
System.out.println(t.x[0]); //NullPointerException
}
}

Instance level:
int[] x;
System.out.println(obj.x); //null
System.out.println(obj.x[0]); //NullPointerException

int[] x=new int[3];
System.out.println(obj .x); // [I e3563@5
System.out.println(obj .x[0]); //NullPointerException

Static level:
static int[] x;
System.out.println(obj.x); //null
System.out.println(obj.x[0]); //NullPointerException


static int[] x=new int[3];
System.out.println(obj .x); // [I e3563@5
System.out.println(obj .x[0]); //NullPointerException

Local level:
int[] x;
System.out.println(obj.x); // variable x might not have been initialized
System.out.println(obj.x[0]); // variable x might not have been initialized

int[] x=new int[3];
System.out.println(obj .x); // [I e3563@5
System.out.println(obj .x[0]); //0

Arrays

  1. Introduction
  2. Array Declaration
  3. Array Creation
  4. Array Initialization
  5. Array Declaration, creation and initialization in a single line
  6. length vs length()
  7. Anonymous Arrays
  8. Array Element Assignments
  9. Array variable Assignments
Introduction:-

  • An array is an indexed collection of fixed number of homogeneous data elements.
The main advantage of arrays is , we can represent huge number of values by using single variable. So that readability of the code will be improved, but the main disadvantage of the arrays is fixed in size i.e once we creates an array there is no chance of increasing or decreasing in the size based on the requirement.
Hence to use arrays concept, compulsory we should know the size in advance , which may not possible always.
Array Declaration:-

One Dimensional Array Declaration:-
int[] x ; //valid and recommended because name is clearly separated from type.
int []x; //valid but not recommended.
int x[]; //valid but not recommended.

At the time of declaration we can't specify the size , otherwise we ll get compile time error.
Example: int[6] x; //Invalid

Two Dimensional Array Declaration:-
int[][] x ; //valid and recommended because name is clearly separated from type.
int [][]x; //valid but not recommended.
int x[][]; //valid but not recommended.
int[] []x; //valid but not recommended.
int[] x[]; //valid but not recommended.
int []x[]; //valid but not recommended.

Q.Which of the followings are valid?
  1. int[] a,b; // valid ,a's dimension=1 & b's dimension=1
  2. int[] a[],b; //valid ,a's dimension=2 & b's dimension=1
  3. int[] a[],b[]; //valid ,a's dimension=2 & b's dimension=2
  4. int[] []a,b; //valid, a's dimension=2 & b's dimension=2
  5. int[] []a,b[]; //valid, a's dimension=2 & b's dimension=3
  6. int[] []a,[]b; //Invalid

  • If we want to specify dimension before the variable, that facility is applicable only for first variable in a declaration. If we are trying to apply for remaining variables ,we ll get compile time error. Ex: int[] []a (valid), []b (Invalid), []c (Invalid);
Three Dimensional Array Declaration:-
int [][][]a; //valid
int [][][]a; //valid
int a[][][]; //valid
int[] [][]a; //valid
int[] a[][]; //valid
int[] []a[]; //valid
int[][] []a; //valid
int[][] a[]; //valid
int [][]a[]; //valid
int []a[][]; //valid

Array Creation:-
Every array in java is an object only,hence we can create arrays by using 'new' operator.
Example:
int[] a=new int[3];
For every array type, corresponding classes are available and these classses are part of java language and not available to the programmer level.

int[] a=new int[3];
System.out.println(a.getClass().getname()); // o/p: [I
ArrayType
Corresponding Class Name
int[]
[I
int[][]
[[I
double[]
[D
short[]
[S
byte[]
[B
boolean[]
[Z
Points:
  1. At the time of array creation , compulsory we should specify the size, Otherwise we ll get compile time error.
    Example:- int[] x=new int[]; // Invalid
            int[] x=new int[6]; //valid
  1. It is legal to have an array with size zero in java.
    Example: int[] x=new int[0]; //valid
  2. If we are trying to specify array size with some negative int value, then we ll get Run time Exception saying NegativeArraySizeException.
    Example: int[] x=new int[-6]; //No Compile Time Error
  3. To specify array size , the allowed data types are byte,short,char,int. If we are trying to specify any other type, then we ll get compile time error.
    Example: int[] x=new int[10]; // valid
    int[] x=new int['a']; //valid
    byte b=20;
    int[] x=new int[b]; //valid
    short s=10;
    int[] x=new int[10l]; //Invalid C.E possible loss of precession, found: long, required: int
  4. The maximum allowed array size in java is 2147483647, which is the maximum value of int data type.
    Example: (i) int[] x=new int[2147483647]; //valid
             (ii) int[] x=new int[2147483648]; // C.E. Integer Number too large
Even in the (i) case we may get a Run time Exception if sufficient heap memory is not available.

Two Dimensional Array Creation:-
In java 2 D array is not implemented by using matrix style. Sun people followed array of arrays approach for multi dimensional array creation.
The main advantage of this approach is memory utilization will be improved.
Example:-
Student No
Math
Physics
Chemistry
Bio
1
45
12
23
12
2
56
64
Not appeared
Not appeared
3
85
Not appeared
Not appeared
Not appeared
Here “Not appeared” memory locations are wasted, so SUN people followed array of arrays approach i.e.
Here memory is optimized.
Example-1:
int[][] x=new int [2][];
x[0]=new int[2];
x[1]=new int[3];
                                                                        (Example-1)

Example-2:
int[][][] x=new int [2][][];
x[0]=new int[3][];
x[0][0]=new int[1];
x[0][1]=new int[2];
x[0][2]=new int[3];
x[1]=new int[2][2];
x[1][0]=new int[2];
x[01[1]=new int[2];

                                                                          (Example-2)

Q.Which of the following array declarations are valid ?

1. int[] a= new int[]; //Invalid, at least base size must be specified
2. int[] a= new int[3]; //valid
3. int[][] a= new int[][]; //Invalid, at least base size must be specified
4. int[][] a= new int[3][]; //valid
5. int[][] a= new int[][4]; //Invalid, base size must be specified
6. int[][] a= new int[3][4]; //valid
7. int[][][] a= new int[3][4][5]; //valid
8. int[][][] a= new int[3][4][]; //valid
9. int[][][] a= new int[3][][5]; //Invalid; without 2nd dimension we can't assign 3rd dimension
10.int[][][] a= new int[][4][5]; //Invalid; without 1st dimension we can't assign 2nd and 3rd dimension

Array Initialization:
Once we creates an array, every element by default initialized with default values.
Example-1:
Int[] x=new int[3];
System.out.println(x); // [I@8d00ce
System.out.println(x[0]); //0
Example-2:
Int[][] x=new int[2][3];
System.out.println(x); // [[I@8d00ce
System.out.println(x[0]); // [I@7f00de
System.out.println(x[0])[0]; //0
Example-3:
Int[][] x=new int[2][];
System.out.println(x); // [[I@8d00ce
System.out.println(x[0]); // null
System.out.println(x[0])[0]; //NullPointerException

Note: If we are trying to perform any operation on null, then we ll get run time exception saying “NullPointerException”.

Once we creates an array, every array element by default initialized with default values.
If we are not satisfied with default values,then we can override these values with our customized values.
int[] x=new int[6];
x[0]=10;
x[1]=20;
x[2]=30;
x[3]=40;
x[4]=50;
x[5]=60;
x[6]=70; // ArrayIndexOutOfBoundsException
x[-6]=80; // ArrayIndexOutOfBoundsException
x[2.5]=90; // Compilation Error, Possible loss of precission, found :double, required :int

Note: If we are trying to access array element with out of range index (either +ve or -ve int value), then we ll get runtime exception saying “ArrayIndexOutOfBoundsException”.

 Array Declaration,Creation and Initialization in a single line:-

we can declare, create and initialize an array in a single line(shortcut representation)
Example:-
int [] x;
x=new int[3];
x[0]=10;
x[1]=20;
x[2]=30;
 //Alternate way
int [] x={10,20,30};
char[] ch={'a','e','i','o','u'};
String [] s={"A","AA","AAA"};
We can use this shortcut for multidimensional arrays also.

Example 1:
int[][] x={{10,20}{30,40,50}};
see the below figure for memory representation.
(Example-1)
Example 2:
int [][][] x={{{10,20,30},{40,50,60}},{{70,80},{90,100,110}}};
                                                                   (Example-2)
System.out.println(x[0][1][2]);//60
System.out.println(x[1][0][1]);//80
System.out.println(x[2][0][0]);//ArrayIndexOutsOfBoundsException
System.out.println(x[1][2][0]);//ArrayIndexOutsOfBoundsException
System.out.println(x[1][1][1]);//100
System.out.println(x[2][1][0]);//ArrayIndexOutsOfBoundsException
 case:1
 If we want to use this shortcut compulsory we should perform all activities in a single line. If we are trying to divide into m multiple lines , then we will get compile time error.
 Example 1:
int x=10; == int x; x=10;
int [] x={10,20,30}; == int [] x;(correct) x={10,20,30};(illegal start of expression)

 length vs length( ):-

length:
length is a final variable applicable for arrays.
length variable represents the size of the array.
Example:
int [] x=new int[6];
s.o.p(x.length());//C.E. can't find symbol method length() location class int[]
s.o.p(x.length);//6
length( ):
length( ) is a final method applicable for String objects.
length( ) returns number of characters present in the String.
 Example:
 String s="purna";
s.o.p(s.length);//can't find symbol variable length location class java.lang.String
s.o.p(s.length());//5

Note:length variable applicable for arrays but not for String objects where as length() applicable for String objects but not for arrays.
 String [] s={"A","AA","AAA"};
s.o.p(s.length); // correct
s.o.p(s.length()); //C.E can't find symbol ,symbol: variable length(), location: class String[]
s.o.p(s[0].length); //C.E can't find symbol ,variable length, location: class- java.lang.String
s.o.p(s[0].length()); //correct
Example:
int [][] x=new int [6][3];
System.out.println(x.length);//6
System.out.println(x[0].length);//3
Note: In multi dimensional length variable represents only base size but not total size.
There is no direct to way to find out total length of multi dimensional array but indirectly we can find as follows:
x[0].length+x[1].length+x[2].length+...........

Anonymous Array:
Sometimes we can declare an array without name, such type of name less arrays are called anonymous arrays.
The main purpose of anonymous arrays is just for instant use(one time usage).
Declaration:
we can create anonymous array as follows: new int[]{10,20,30,40}
1.while creating anonymous arrays we can't specify the size, otherwise we will get compile time error.
Example:
new int[4]{10,20,30,40} //invalid
new int[]{10,20,30,40} //valid

class Test{
public static void main(String [] args){
sum(new int[]{10,20,30,40});
}

public static void sum(int [] x){
int total=0;
for(int x1: x){
total=total+x1;
}
System.out.println(“The sum is”+ total);
}
}
In the above example just to call sum(), we require an array, but after completing sum() method call we are not using that array anymore. Hence for this one requirement anonymous array is the best choice.
2. We can create multi dimensional anonymous arrays also.
new int []{{10,20},{30,40,50}}
3.Based on our requirement we can give the name for anonymous array, then it is no longer anonymous.
new int[{10,20,30}] //anonymous
Int [] x= new int[{10,20,30}]; //not anonymous

 Array element assignments:-
Case 1:
In the case of primitive type arrays as array elements, we can provide any type,which can be implicitly promoted to declared type.
Example:
int [] x= new int[5];
x[0]=10;
x[1]='a';
byte b=20;
x[2]=b;
short s=30;
x[3] =s;
x[4]=10l; //C.E. Possible loss of precision found long required :int
In the case of float type arrays, the allowed data types are byte,short,int,long,char,float.
Case 2:
In the case of Object type arrays as array elements ,we can provide either declared type objects or it's child class objects.
Example 1:
Object [] a=new Object[10];
a[0]=new Object();
a[1]=new String(“purna”);
a[2]=new Integer(10);
Example 2:
Number [] n=new Number[10];
n[0]=new Integer(10);
n[1]=new Double(10.5);
n[2]=new String(“purna”); // C.E. Incompatible types: found java.lang.String, required: java.lang.Number
Case 3:
For interface type arrays as array elements,it's implementation class objects are allowed.
Runnable [] r = new Runnable[10];
r[0]=new Thread(); //Here: Class Thread implements Runnable
r[1]=new String(“purna”); //C.E. Incompatible type found: java.lang.String required java.lang.Runnable.
Array Type Allowed element type
Primitive Arrays Any type which can be implicitly promoted to declared type.
Object type Arrays Either declared type or its child class objects
Abstract class type Arrays It's child class objects
Interface type Array It's implementation class objects
Array variable Assignments:

Case 1:
Element level promotions are not applicable at array level.
char element can be promoted to int type, where as char [] can't be promoted to int[].
Example:
int [] a={10,20,30,40};
char [] ch={'a','b','c','d'};
int [] b=a; //valid
int [] c=ch; //invalid C.E Incompatible type found char[] required: int[]

Q.Which of the following promotions will be performed automatically?
1. char --> int //valid
2. char[] -->int[] //invalid
3. int --> double //valid
4. int[] --> double[] //invalid
5. float --> int //invalid
6. float[] --> int[] //invalid
7. String --> Object //valid
8.String[] --> Object[] //valid

Note: But in the case of object type array, the child class type array can be promoted to parent class type array.
String [] s={“A”,”B”,”C”};
Object [] a=s; //valid

Case 2:
Whenever we are assigning one array to another array, internal elements won't be coppied, just reference variables will be reassigned.
int[] a={10,20,30,40,50};
int[] b={60,70,80};
  1. a=b; //valid
  2. b=a; //valid
Case 3:
Whenever we are assigning one array to another array, the dimensions must be matched. For example in the place of one dimensional int array we should provide one dimensional int array only.
If we are trying to provide any other dimension, then we will get compile time error.

int[][] a= new int[3][];
a[0]= new int[4][3]; // C.E Incompatible type found int[][], required int[]
a[0]=10; // C.E Incompatible type found int, required int[]
a[0]=new int[2]; //valid
Note: Whenever we are assigning one array to another array, both dimensions and type must be matched but sizes are not required to match.
Example 1:
class Test{
public static void main(String [] args){
for(int i=0;i<args.length;i++){

System.out.println(args[i]);
}
}
}
java Test A B C // O/P- A B C ArrayIndexOutOfBoundsException
java Test A B // O/P- A B ArrayIndexOutOfBoundsException
java Test // O/P- ArrayIndexOutOfBoundsException

Example 2:
class Test{
public static void main(String [] args){
String [] argh ={“A”,”B”,”C”};
args=argh;
for(String s:args ){
System.out.println(s);
}
}
}
java Test A B C // O/P- X Y Z
java Test A B // O/P- X Y Z
java Test // O/P- X Y Z
Example 3:
int[][] a= new int[4][3]; // Here 5 objects are created
a[0]= new int[4]; // Here 1 object is created
a[1]= new int[2]; // Here 1 object is created
a= new int[3][2]; // Here 4 objects are created
Total How many Objects are created here ? Ans- 11
Total How many Objects are eligible for garbage collected ? Ans- 7

Literals

Any Constant value which can be assigned to a variable.
Example: int x=10;
Here, int represents Data Type/Key Word, x represents Variable/Identifier, 10 represents Constant/Literal.

Integral Literal:
For Integral data types (byte, short, int , long) we can specify literal value in the following ways.

1.Decimal Literals (Base 10)
Allowed digits are 0 to 10
Example: int x=10;

2.Octal Literal (Base 8)
Allowed digits are 0 to 8
Literal value should be prefixed with zero(0).
Example: int x=010;

3.Hexadecimal Literal( Base 16)
Allowed digits are 0 to 9, a to f
Literal value should be prefixed with 0X or 0x
Example 1 : int x=0X10;

For extra digit ( a to f ) , we can use both lower case and upper case character. This is one of very few area where java is not case sensitive.

These are only possible ways to specify literal values for integral data types.

Q. Which of the following declarations are valid?

int x=10; (valid)
int x=0786; (in valid C.E. Integer number too large)
int x=0777; (valid)
int x= 0XFace; (valid)
int x=0XBeef; (valid)
int x=0XBeer; (C.E ; expected)

Example 2:
class Test{
public static void main (String [] args){
int x=10;
int y=010;
int z=0X10;
System.out.println(x+“ ”+y+” ”+z);
}
}
o/p- 10 8 16

Note: If we are giving the values as decimal, octal, hexadecimal then by default JVM internally converts all the values in to decimal form and gives the o/p as decimal form.

  • By default every integral literal is of int type, but we can specify explicitly as long type by suffixed with l or L.
int x=10; (valid)
long l=10L; (valid)
int x=10L; C.E Possible loss of Precesion required int, found long
long l=10; (valid as int value can be stored in long variable i.e 32 bit value can be stored in 64 bit allocating variable)
  • There is no direct way to specify byte and short literals explicitly, but indirectly we can specify. When ever we are assigning integral literal to the byte variable and if the value with in the range of byte, then compiler treats it automatically as byte literal. Similarly short literal also.
byte b=10; valid
byte b=127; valid
byte b=128; Possible loss of Precision found int, required byte

short s=32767; valid
short s=32768; Possible loss of Precision found int, required short

Floating Point Literal:
By default every floating point literal is of double type and hence we can't assign directly to the float variable.
But we can specify floating point literal as float type by suffixed with f or F.
Example:
float f=123.456; //possible loss of Precision found double ,required float
float f=123.456f; //valid
double d=123.456; //valid
we can specify explicitly floating point literal as double type by suffixed with d or D.
Of course this convention is not required.
Example:
double d=123.456d;
float f=123.456d; // C.E possible loss of  precision found double , required float.

We can specify floating point literals only in decimal form and we can't specify in octal and hexadecimal forms.
Example:
double d=123.456; //valid
double d=0123.456; // valid as this is the decimal literal not octal literal as 0 before floating value is not considered and considered as decimal.
double d=0X123.456 //C.E. Malformed floating point literal

We can assign integral literal directly to floating point variables and that integral literal can be specified either in decimal, octal or hexadecimal forms.
Example:
double d=0786; //invalid, integer value too large
double d=0XFace; // valid
double d=0786.0; //valid
double d=0XFace.0; // invalid
double d=0777; //valid
double d=10; //valid

We can't assign floating point literals to integral types.
Example:
double d=10; // valid
int x=10.0; // possible loss of precision found double , required int

We can specify floating point literal even in exponential form(scientific notation)
Example:
double d=1.2e3; // valid and o/p=1200.0 ( since 1.2*10^3)
float f=1.2e3; // C.E possible loss of precision found double, required float.
float f=1.2e3; // valid

boolean Literal:

The only allowed values for boolean data type are true or false.
Examples:
boolean b=true; (valid)
boolean b=0; (invalid, gives compile time error, “incompatible type”, found int, required boolean)
boolean b=True; (invalid, gives compile time error, “can't find symbol”, class Test)
boolean b=”True”; (invalid, gives compile time error, “incompatible type”, found java.lang.String, required boolean)

Ex.1                                                                      Ex. 2
class Test{                                                            class Test{
public static void main(String []args){                public static void main(String []args){
int x=10;                                                               while(1){
if(x){                                                                     System.out.println(“Hello”);
System.out.println(“Hello”); }
}                                                                            }
else{                                                                      }
System.out.println(“Hello”);
}
}
}
These two programs are valid in case of c & c++, but in java it gives error.
Here both the program will give compilation error “Incompatible Types ” found int, required boolean. Because if and while loop condition needs a boolean value only in case of java, and as java is strongly typed programming language this is not supported in java.

char Literal:
We can specify char literal as single character with in single quotes.
Example:
char ch='a'; // valid
char ch=a; // C.E. Can't find symbol, symbol: variable a, class Test
char ch=”a”; // C.E. Incompatible type found java.lang.String required char
char ch='ab'; //C.E 1 unclosed charcter literal
//C.E 2 unclosed charcter literal
//C.E 3 not a java statement

We can specify char literal as integral literal which represents UNICODE value of the character and that integral literal can be specified either in decimal or octal or hexadecimal forms, But allowed range is 0 to 65535.
Example:
char ch=97; System.out.println(ch); // o/p- a
char ch=0XFace; //valid
char ch=0777; // valid
char ch=65535; //valid
char ch=35536; // Invalid C.E. Possible loss of precesion, found : int required :char

Note: follow www.unicode.org to get all the respected symbol of characters between 0 to 65535.

We can represent char literal in UNICODE representation which is nothing but '\uXXXX' where XXXX stands for 4 digit hexadecimal number.
Example:
char ch='\u0061'; System.out.println(ch); // o/p- a
Every escape character is a valid char literal.
Example:
char ch='\n' // valid
char ch='\t' // valid
char ch='\m' // Invalid C.E Illegal Escape character


Escape character
Description
1
\n
New Line
2
\t
Horizontal Tab
3
\r
Carriage Return
4
\b
Back Space
5
\f
Form Feed
6
\'
Single Quote
7
\''
Double Quote
8
\\
Back Slace
Q. Which of the following are the valid char literal?
char ch=65536; //Invalid due to out of Range
char ch=0XBeer; //Invalid due to r symbol
char ch=\uface; // Invalid due to single quote missed
char ch='\m'; //Invalid C.E. Illegal Escape character
char ch='iface'; //Invalid due to i symbol
char ch='ubeef'; //valid

String Literal:

Any sequence of characters with in double quotes is treated as String Literal.

Example:
String s=”purnachandra”;

1.7 Enhanced features to Literals:

Binary Literal:

For integral data types until 1.6 versions we can specify Literal values in the following ways.
1. Decimal form
2. Octal form
3. Hexadecimal form
But from 1.7 version on wards we can specify Literal values even in binary form also.
Allowed digits are 0 and 1..
Literal value should be prefixed with 0b or 0B.

Example:
int x=0B1111; System.out.println(x); // o/p- 15

Usage of _(underscore) in literal:
From 1.7 version on wards we can use _ symbol between digits of numeric literals.

Example:
double d= 123456789;

double d=1_2_3_456.7_8_9; //Indian standard
double d=123_456.7_8_9; //US standard

The main advantage of this approach is the readability of the code will be improved.

At the time of compilation these underscore symbols will be removed automatically, Hrnce after compilation the above lines ll become

double d=123456.789;
We can use more than one underscore symbol also between the digits.

double d= 1___23_4_5___6.7_8_9;

We can use the underscore symbol only between the digits .If we are using any where else we ll get compile time error.

double d=_1_23_456.7_8_9; //Invalid
double d=1_23_456_/7_8_9; //Invalid
double d= 1_23_456.7_8_9_; //Invalid


Note:
1. 8 byte long value we can assign to 4 byte float variable because both are following different memory representation internally.
float f=10 l;
System.out.println(f); o/p- 10.0

2. char and short data types both occupy same 2 bytes memory space , even though we can't able to store char value in short data type, because char does n't have signed value (-ve value), but byte contain signed values. So the maximum value of char(65535) cant be stored in byte variable.