Lang Fundamental

There are many things to learn in Java Fundamental .Lets divide in 9 categories and learn. Along with this we will be learning the installation of JAVA in Operating System.

Identifiers

What is an identifier in java?

Identifiers are the names in Java . It is variables, methods, classes, packages and interfaces name. Identifier names should begin with a letter, the underscore or a dollar sign. Java has 50 Keywords, 3 Reserved Literals.

In the above program

  • SmartCodeWork is a Class Name
  • main() is a Method name, main method or any method must be small letter character or symbol _ and $.
  • String is a data type.
  • name is the variable name.

Rules to define Java identifiers

Rule 1: The only allowed characters ¡n java identifiers

1)abcd 2) 0 to 9 3)$ 4) A to Z 4) _ (underscore)

Rule 2: If we are using any other character we will get compile time error.

1) total_number valid 2) Total# invalid

Rule 3: identifiers are not allowed to starts with digit.

1)ABC123 valid 2)123ABC invalid

Rule 4: java identifiers are case sensitive up course java language itself treated as case sensitive language.

Rule 5: There is no length limit for java identifiers but it is not recommended to take more than 15 character lengths.

Rule 6: We can’t use reserved words as identifiers.
Example: int if = 5; —-> Invalid

Rule 7: All predefined java class names and interface names we use as identifiers.


Even though it is legal to use class names and interface names as identifiers but it is not a good programming practice.

Reserved Words

In java some identifiers are reserved to associate some functionality or meaning such type of reserved identifiers are called reserved words.

Reserved words for data types: (8)

Reserved words for flow control: (11)
1) if 2) switch 3) default 4)do 5) else 6) case 7)for 8) while 9)break 10)continue 11)return

Keywords for Modifiers :(11)
1) public 2) private   3) protected 4) static   5)final 6)abstract
7) synchronized 8) native    9) strictfp(1 .2 version) 10) transient
11) volatile

Keywords for exception handing:(6)
1)try     2) catch    3)finally    4)throw    5) throws 6) assert(1 .4 version)

Class related keywords:(6)
1) class    2) package   3) import   4)extends  5)implements   6) interface

Object related Keywords:(4)
1) new    2) instanceof   3)super   4)this

Void return type keyword:
If a method won’t return anything compulsory that method should be declared with the void return type in java but it is optional ¡n C++.
1) void

Void return type keyword:
If a method won’t return anything compulsory that method should be declared with the void return type in java but it is optional ¡n C++.
1) void

Unused keywords:
goto: Create several problems in old languages and hence it is banned in java. Const: Use final instead of this. By mistake if we are using these keywords in our program we will get compile time error.

Reserved literals:
1) true values for boolean data type. 2) false 3) null — default value for object reference.

Enum:
This keyword introduced in 1 .5v to define a group of named constants.

Data Types

Every variable has a type, every expression has a type and all types are strictly define moreover every assignment should be checked by the compiler by the type compatibility hence java language is considered as strongly typed programming language.

byte:
Size: 1 byte (8 bits)
Max value: +127
Min value: -128
Range: -128to 127 [-27 to 27-1]

Byte data type is best suitable if we are handling data in terms of streams either from the file or from the network.

short:
The most rarely used data type in java is short.
Size: 2 bytes
Range: -32768 to 32767(-215 to 215-1)

Short data type is best suitable for 16 bit processors like 8086 but these processors are completely outdated and hence the corresponding short data type is also out data type.

int:
This is most commonly used data type in java.
Size: 4 bytes
Range:-21 47483648 to 21 47483647 (-231 to 231 -1)

long:
Whenever int is not enough to hold big values then we should go for long data type. To hold the number Of characters present in a big file int may not enough hence the return.

type of length() method is long.
long l = f.length();//fis a file
Size: 8 bytes

Range: -263 to 263-1

Note: All the above data types (byte, short, int and long) can be used to represent whole numbers. If we want to represent real numbers then we should go for floating point data types.

Floating Point Data types:

boolean:
Size: Not applicable (virtual machine dependent)
Range: Not applicable but allowed values are true or false.

char:
In old languages like C & C++ are ASCII code based the no of ASCII code characters are < 256 to represent these 256 characters 8 – bits enough hence char size in old languages 1 byte. In java we are allowed to use any worldwide alphabets character and java is Unicode based and no of unicode characters are > 256 and <= 65536 to represent all these characters one byte is not enough compulsory we should go for 2 bytes.
Size: 2 bytes Range: O to 65535

Literals

Any constant value which can be assigned to the variable is called literal.

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

1) Decimal literals: Allowed digits are O to 9.
Example: int x = 10;
2) Octal literals: Allowed digits are O to 7.
Value should be prefixed with zero.
Example: int x= O1O;
3) Hexadecimal literals:

  1. The allowed digits are O to 9.
  2. For the extra digits we can case characters.
  3. This is one of very few areas where java is not case sensitive.
  4. Literal value should be prefixed with ox(or)oX.

Example: int x = 0x10;
These are the only possible ways to specify integral literal.

Example

By default every integral literal is int type but we can specify explicitly as long type by suffixing with small I (or) capital L.

Example

There is no direct way to specify byte and short literals explicitly. But whenever we are assigning integral literal to the byte variables and its value within the range of byte compiler automatically treats as byte literal. Similarly short literal also.

Example

Floating Point Literals:
Floating point literal is by default double type but we can specify explicitly as float type by suffixing with f or F.

Example

We can specify explicitly floating point literal as double type by suffixing with d or D.

Example

We can specify floating point literal only in decimal form and we can’t specify in octal and hexadecimal forms.

Example

We can assign data types and decimal, octal integral literal directly to the floating point that integral literal can be specified in and Hexadecimal form also.

Example

But we can’t assign floating point literal directly to the integral.

int x = 10.0; //C.E Possible loss of Precision

Example

Boolean literals:
The only allowed values for the boolean type are true (or) false where case is important i.e,lower case

Example

Char literals:
A char literal can be represented as single character within single quotes.

We can specify a char literal as integral literal which represents Unicode of that character. We can specify that integral literal either in decimal or octal or hexadecimal form but allowed values.

We can represent a char literal by Unicode representation which is nothing but ‘\uxxxx’ (4 digit hexadecimal number)

Every escape character in java acts as a char literal.

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

String s=”John”; (valid)

1.7 Version enhancements with respect to Literals:

The following 2 are enhancements
1. Binary Literals
2. Usage of ‘_’ in Numeric Litera
ls

Binary Literals:

For the integral data types until 1.6v we can specified literal value in the following ways

1. Decimal 2. Octal 3. Hexa decimal

>But from 1.7v onwards we can specify literal value in binary form also.
>The allowed digits are O to 1.
>Literal value should be prefixed with Ob or OB.

Usage of symbol in numeric literals:
From 1.7v onwards we can use underscore( _ ) symbol in numeric literals.

The main advantage of this approach is readability of the code will be improved. At the time of compilation ‘_‘symbol will be removed automatically, hence after compilation the above lines will become double d = 123456.789.
We can use more than one underscore symbol also between the digits.

Example:
double d = 1_23__456.789;

Arrays

An array is an indexed collection of fixed number of homogeneous data elements. The main advantage of arrays is we can represent multiple values with the same name so that readability of the code will be improved.

But the main disadvantage of arrays is Fixed in size that is once we created an array there is no chance of increasing or decreasing the size based on our
requirement that ¡s to use arrays concept compulsory we should know the size in advance which may not possible always.

Single dimensional array declaration:

At the time of declaration we can’t specify the size otherwise we will get compile time error.

Three dimensional array declaration:

Note:
If we want to specify the dimension before the variable that rule is applicable only for the 1 st variable. Second variable onwards we can’t apply ¡n the same declaration.

Array construction:
Every array in java is an object hence we can create by using new operator.

int [] a = new int [3];

Rule 1:
At the time of array creation compulsory we should specify the size otherwise we will get compile time error.

Rule 2:
It is legal to have an array with size zero in java.

Rule 3:
If we are taking array size with -ve mt value then we will get runtime exception saying NegativeArraySizeException.

Rule 4:
The allowed data types to specify array sizes are byte, short, char, int. By mistake if we are using any other type we will get compile time error.

Rule 5:
The maximum allowed array size in java is maximum value of int size [2147483647].

Array Initialization:
Whenever we are creating an array every element is initialized with default value automatically.

Declaration, construction and initialization of an array in a single line:

Anonymous Arrays:
Sometimes we can create an array without name such type of nameless arrays are called anonymous arrays. The main objective of anonymous arrays is just for instant use. We can create anonymous array as follows. At the time of anonymous array creation we can’t specify the size otherwise we will get compile time error.

In the above program just to call sum(), we required an array but after completing sum() call we are not using that array any more, anonymous array is best suitable.

Types of Variables

Based on the type of value represented by a variable all variables are divided into 2 types. They are:

1. Primitive variables
2. Reference variable
s

Primitive variables:
Primitive variables can be used to represent primitive values.

int x = 1O;

Reference variables:
Reference variables can be used to refer objects.
Student s = new Student()

‘s’ is an Object

Division 2:
Based on the behaviour and position of declaration all variables are divided into the following 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 type of variables are called instance variables.
• For every object a separate copy of instance variables will be created.
• Instance variables will be created at the time of object creation and destroyed at the time of object destruction hence the scope of instance variables is exactly same as scope of objects.
• Instance variables will be stored on the heap as the part of object.
• Instance variables should be declared with in the class directly but outside of any method or block or constructor.
• Instance variables can be accessed directly from Instance area, but cannot be accessed directly from static area.
• But by using object reference we can access instance variables from static area.

For the instance variables it is not required to perform initialization JVM will always provide default values.Instance variables also known as object level variables or attributes.
Static variables:

• If the value of a variable is not varied from object to object such type of variables is not recommended to declare as instance variables. We have to declare such type of variables at 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 for entire class only one copy will be created and shared by every object of that class.

• Static variables will be crated at the time of class loading and destroyed at the time of class unloading hence the scope of the static variable is exactly same as the scope of the .class file.

• Static variables will be stored in method area. Static variables should be declared with in the class directly but outside of any method or block or constructor.

• Static variables can be accessed from both instance and static areas directly.

• We can access static variables either by class name or by object reference but usage of class name is recommended.

• But within the same class it is not required to use class name we can access directly.

For the static variables it ¡s not required to perform initialization explicitly, JVM will always provide default values. Static variables also known as class level variables or fields.

Local variables:
• Some times to meet temporary requirements of the programmer we can declare variables inside a method or block or constructors such type of variables are called local variables or automatic variables or temporary variables or stack variables.

•Local variables will be stored inside stack.

• The local variables will be created as part of the block execution in which it ¡s declared and destroyed once that block execution completes. Hence the scope of the local variables is exactly same as scope of the block ¡n which we declared.

• It is never recommended to perform initialization for the local variables inside logical blocks because there is no guarantee of executing that block always at runtime.

• It is highly recommended to perform initialization for the local variables at the time of declaration at least with default values.

Note:
The only applicable modifier for local variables is final. If we are using any other modifier we will get compile time error.

Var-arg Method

• Until 1.4v we can’t declared a method with variable no of arguments.
• If there is a change in no of arguments compulsory we have to define a new method.
• This approach increases length of the code and reduces readability.
• But from 1.5 version onwards we can declare a method with variable no. Of arguments such type of methods are called var-arg methods.

We can declare a var-arg method as follows.

methodOne (int… x)

We can call or invoke this method by passing any no of int values including zero number also.

Output:
var-arg method
var-arg method
var-arg method

Internally var-arg parameter implemented by using single dimensional array hence within the var-arg method we can differentiate arguments by using index.

Case 1:
Which of the following var-arg method declarations are valid?
1. methodOne(int… x) (valid)
2. methodOne(int …x) (valid)
3. methodOne(int…x) (valid)
4. methodOne(int x…) (invalid)
5. methodOne(int. ..x) (invalid)
6. methodOne(int .x..) (invalid)

Case 2:
We can mix var-arg parameter with general parameters also.
methodOne(int a,int… b)  // valid
method One(String s,int… x) //valid

Case 3:
If we mix var-arg parameter with general parameter then var arg parameter should be the last parameter.

method One(int a,int… b) //valid
methodOne(int… a,int b) //(invalid)

Case 4:
Within the var-arg method we can take only one var-arg parameter. i.e., ¡f we are trying to more than one var-arg parameter we will get CE.
method One(int… a, int… b) //(invalid)

Case 5:

In general var-arg method will get least priority that is if no other method matched then only var-arg method will get the chance this is exactly same as default case inside a switch.

Case 6:
For the var-arg methods we can provide the corresponding type array as argument.

Case 7:

Output:
Compile time error
Cannot declare both methodOne(int…) and methodOne(int []) in Test

Main Method

Whether the class contains main() method or not, and whether it is properly declared or not, these checking’s not responsibilities of the compiler, at runtime JVM is responsible for this. If JVM unable to find the required main() method then we will get runtime exception saying NoSuchMethodError: main.

Example:
class Test{  }

Output:
javac Test.java

java Test R.E: NoSuchMethod Error: main

At runtime JVM always searches for the main() method with the following prototype.

If we are performing any changes to the above syntax the the code won’t run and wilt get Runtime exception saying NoSuchMethodError.

Even though above syntax is very strict but the following changes are acceptable to main() method

1. The order of modifiers is not important that is instead of public static we can take static public.

2. We can declare String[] in any acceptable form , String[] args , String[]args, String args[].

3. Instead of args we can use any valid java identifier.

4. We can replace String[] with var-arg parameter.
Example: main(String… args)

5. main method can be declared with the following modifiers. final, synchronized, strictfp.

Output:
valid main method

Which of the following main () method declarations are valid?
1. public static void main(String args){} (invalid)
2. public synchronized final strictfp void main(String[] args){} (invalid)
3. public static void Main(String… args){} (invalid)
4. public static mt main(Stringfi args){} //int return type we can’t take //(invalid)
5. public static synchronized final strictfp void main(String… args){}(valid)
6. public static void main(String… args){}(valid)

7. public void main(String[] args){}(invalid)

Case 1:
Overloading of the main method is possible but JVM always calls string[] argument main method only.

Output:
String[] array main method

class Test { }

1.6 version:
javac Test.java
java Test
RE: NoSuchMethodError:main

1.7 version:
javac Test.java
java Test Error: main method not found in class Test,please define the main method as public static void main(String[] args)

Case 2:
From 1.7 version onwards to start program execution compulsory main method should be required, hence even though the class contains static block if main method not available then won’t be executed.

1.6 version

javac Test.java

java Test

output:
static block
RE: NoSuchMethodError:main

Error: main method not found in class Test, please define the main method as public static void main(String[] args)

Various Memory area present inside JVM

1. Class level binary data including static variables will be stored in method area.

2. Objects and corresponding instance variables will be stored in Heap area.

3. For every method the JVM will create a Runtime stack all method calls performed by that Thread and corresponding local variables will be stored in that stack. Every entry in stack is called Stack Frame or Action Record.

4. The instruction which has to execute next will be stored in the corresponding PC Registers.

5. Native method invocations will be stored ¡n native method stacks.