0% found this document useful (0 votes)
17 views63 pages

Language Fundamentals

The document covers the fundamentals of Java programming, including identifiers, reserved words, data types, literals, arrays, and types of variables. It explains the rules for defining identifiers, the significance of reserved words, and the characteristics of various data types such as byte, short, int, long, float, double, boolean, and char. Additionally, it discusses array creation and initialization, as well as the distinction between primitive and reference variables, and the types of variables based on their behavior and declaration position.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views63 pages

Language Fundamentals

The document covers the fundamentals of Java programming, including identifiers, reserved words, data types, literals, arrays, and types of variables. It explains the rules for defining identifiers, the significance of reserved words, and the characteristics of various data types such as byte, short, int, long, float, double, boolean, and char. Additionally, it discusses array creation and initialization, as well as the distinction between primitive and reference variables, and the types of variables based on their behavior and declaration position.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Language Fundamentals

1. Identifier
2. Reserved Words
3. Data Types
4. Literals
5. Arrays
6. Types of variables
7. Var -arg method
8. Main Method
9. Command line Arguments
10. Java Coding Standards
Identifier
• A name in java program is called identifier.
• It may be class name, method name,
variable name and label name.

public class Main


{
public static void main ( String [] args ) {
int x =10;
System.out.println("Hello Softronix");
}
}

So here, number of identifiers are 5.


Rules to define Java Identifiers
• The only allowed characters in java identifiers are
a. a to z
b. A to Z
c. 0 to 9
d. _
e. $
• If we are using any other character we will get compile time
error.

Example:
1. Total_number ►valid
2. Total# ►invalid
Rules to define Java Identifiers
• There is no length limit for java identifiers but it is not
recommended to take more than 15 lengths.

• We can’t use reserved words as identifiers.

Example:
int if = 10 ►invalid
Rules to define Java Identifiers
• All predefined java class names and interface names we use as
identifiers.

Example:
Integer
Reserved words
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:


1. byte
2. short
3. int
4. long
5. float
6. double
7. char
8. boolean
Reserved words
Reserved words for flow control:
1. if
2. else
3. switch
4. case
5. default
6. for
7. do
8. while
Reserved words
Keywords for exception handling:

1. try
2. catch
3. finally
4. throw
5. throws
6. assert (1.4v)
Reserved words
Class related keywords:

1. class
2. package
3. import
4. extends
5. implements
6. interface

Object related keywords:


1. new
2. instanceof
3. super
4. this
Reserved words
Reserved literals:
1. true ►values for boolean data type.
2. false ►values for boolean data type.
3. null ►default value for object reference.
Keywords for modifiers:
1. public
2. private
3. protected
4. static
5. final
6. abstract
7. synchronized
8. native
Data Types
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
language.

● Java is pure object oriented programming or not?


➢ Java is not considered as pure object oriented programming
language
because several oops features (like multiple inheritance, operator
overloading) are not supported by java moreover we are depending
on
primitive data types which are non objects.
Data Types
Diagram:

Note:
Except Boolean and char all remaining data types are considered as
signed data types
because we can represent both “+ve” and”-ve” numbers.
Data Types
byte:
❏ Size: 1 Byte (8 bits)
❏ Max-value: +127
❏ Min-value: -128
❏ Range: 128 to 127 [-27 to 27 -1]
Example:
byte b=10; ► ✔
byte b2=130; ►C.E: possible loss of precision
byte b=10.5 ►C.E: possible loss of precision
byte b=true; ►C.E: incompatible types
byte b="durga"; ►C.E: incompatible types
Data Types
B. short:
❏ Size: 2 Bytes
❏ Range: -32768 to 32767 (-215 to 215 -1)
Example:
short s=130; ► ✔
short s=32768; ►C.E: possible loss of precision
short s=true; ►C.E: incompatible types
Data Types
C. Int:
❏ Size: 4 bytes
❏ Range: -2147483648 to 2147483647 (-231 to 231 -1)

Example:
int i=130; ► ✔
int i=10.5; ►C.E: possible loss of precision
int i=true; ►C.E: incompatible types

● This is most commonly used data type in java.


Data Types
D. long:
❏ Size: 8 bytes
❏ Range:-263 to 263 -1

Example:
long l= 13l;

● To hold the no. Of characters present in a big file int may not
enough hence the return type of length() method is long.

long l=f.length() ; ►f is a file

● Whenever int is not enough to hold big values then we should go


for long data type.
Data Types
E. Floating Point Data types:

Float Double
If we want to 5 to 6 decimal places of If we want to 14 to 15 decimal places
accuracy then we should go for float. of accuracy then we should go for
double.
Follows Single Precision (less accuracy) Follows Double precision (high accuracy)
Size: Size:
4 bytes 8 bytes
Range: Range:
-1.7e38 to 1.7e38 -3.4e38 to 3.4e38
Data Types
F. boolean data type:

❏ Size: Not applicable (virtual machine dependent)


❏ Range: Not applicable but allowed values are true or false.

Example 1:
boolean b=true; ► ✔
boolean b=True; ►C.E:cannot find symbol
boolean b="True"; ►C.E:incompatible types
boolean b=0; ►C.E:incompatible types
Data Types
G. Char data type:

❏ Size: 2 bytes
❏ Range: 0 to 65535

Example 1:
Example:
char ch1=97; ►✓
char ch2=65536; ►C.E:possible loss of precision
Summary Data Types
Data Type Size Range Wrapper class Default Value
byte 1 byte -27 to -27 -1 Byte 0
(-128 to 127)
short 2 byte -215 to -215 -1 Short 0
(-32768 to
32767)
int 4 byte -231 to -231 -1 Integer 0
(-2147483648
to
-2147483647)
long 8 byte -261 to -261 -1 Long 0
float 4 byte -3.4e38 to Float 0.0f
3.4e38
double 8 byte -1.7e308 to Double 0.0
1.7e308
boolean Not applicable true/false Boolean false
char 2 byte 0 to 65535 Character 0 (Blank Space)
Literals
Literals

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


literal.

Example:
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 0 to 9.


Example: int x=10;

2. Boolean literals:
The only allowed values for the boolean type are true (or)
false where case is important.
Example:
1. boolean b=true; ►valid
2. boolean b=0; ►Invalid ►C.E:incompatible types
3. boolean b=True; ►Invalid ►C.E:cannot find symbol True
4. b="true"; ►Invalid ►C.E:incompatible types
D. Char
Literals

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


within single quotes.

Example:
1. char ch='a'; ►valid
2. char ch=a; ►Invalid ►C.E:cannot find symbol a
3. char ch="a"; ►Invalid ►C.E:incompatible types
4. char ch='ab'; ►Invalid ►C.E:unclosed character literal
Literals

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

Example:
String s="bhaskar"; ►Valid
Literals

Diagram:
Arrays
1. Introduction
2. Array declaration
3. Array construction
4. Array initialization
5. Array declaration, construction, initialization in a
single line.
6. length Vs length() method
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.

➤ Arrays may be stored in contiguous memory [consecutive memory


locations].

➤ 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 is to use
arrays concept compulsory we should know the size in advance which
may not possible always.
Syntax:
datatype[] arrayName = new datatype[length]; OR
datatype arrayName[] = new datatype[length];

//[length] = Length of the array


Syntax:
datatype[] arrayName = new datatype[length]; OR
datatype arrayName[] = new datatype[length];

//[length] = Length of the array


Array declarations:
A. Single dimensional array declaration:

Example:
1. int[] a;
►recommended to use because name is clearly
separated from the type
2. int []a;
3. int a[];

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

Example:
1. int[] a; ►valid
2. int[5] a; ►invalid
B. Two dimensional array declaration:

Example:
int[][] a;
int [][]a;
int a[][];
int[] []a;
int[] a[];
int []a[];
Array construction:

Every array in java is an object hence we can create by using new operator

Example:
int[] a=new int[3];
Array construction:

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

Example:
int[] a=new int[3];
int[] a=new int[]; ►C.E:array dimension missing

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

int[] a=new int[0];


System.out.println(a.length); ►Output:0

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

Example:
int[] a=new int[-3]; ►R.E:NegativeArraySizeException
Array construction:

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

Example:

1. int[] a=new int['a']; ►Valid


byte b=10;
2. int[] a=new int[b]; ►Valid
3. short s=20;
int[] a=new int[s]; ►Valid
4. int[] a=new int[10l]; ►Invalid ►C.E:possible loss of precision
5. int[] a=new int[10.5]; ►Invalid ►C.E:possible loss of precision
Array construction:

Rules
4. The maximum allowed array size in java is maximum value of int size
[2147483647].

Example:
1. int[] a1=new int[2147483647]; ►Valid
2. int[] a2=new int[2147483648]; ►Invalid ►C.E:integer number too large: 2147483648
Two dimensional array creation :
> In java multidimensional arrays are implemented as array of arrays approach
but not matrix form.
> The main advantage of this approach is to improve memory utilization

Example 1:
int[][] a=new int[2][];
a[0]=new int[3];
a[1]=new int[2];

Example 2:
int[][][] a=new int[2][][];
a[0]=new int[3][];
a[0][0]=new int[1];
a[0][1]=new int[2];
a[0][2]=new int[3];
a[1]=new int[2][2];
Array initialization:
> Whenever we are creating an array every element is initialized with default
value automatically.

Example 1:

int[] a=new int[3];

System.out.println(a[0]); ►0

> Once we created an array all its elements by default initialized with default
values. If we are not satisfied with those default values then we can replays with
our customized values.

Example 2:
int [][] a= new int [2] [3];

2 = base array size


length Vs length():

>
length:
It is the final variable applicable only for arrays.
It represents the size of the array.

Example:
int[] x=new int[3];
System.out.println(x.length());//C.E: cannot find symbol

System.out.println(x.length);//3
length() method:

It is a final method applicable for String objects.


It returns the no of characters present in the String

Example:
String s="bhaskar";
System.out.println(s.length);//C.E:cannot find symbol
System.out.println(s.length());//7
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.


new int[]{10,20,30,40};(valid)
new int[][]{{10,20},{30,40}};(valid)
At the time of anonymous array creation we can't specify the size otherwise we
will get compile time error.
Example:
new int[3]{10,20,30,40};//C.E:';'
expected(invalid) new int[]{10,20,30,40};(valid)
Based on our programming requirement we can give the name for anonymous
array then it is no longer anonymous.
Example:
int[] a=new int[]{10,20,30,40};(valid)
Example:
class Test
{
public static void main(String[] args)
{
System.out.println(sum(new int[]{10,20,30,40}));//100
}
public static int sum(int[] x)
{
System.out.println(a[0]+a[1]);
{
Types of Variables
Division 1:

Based on the type of value represented by a variable all variables are


divided into 2 types. They are:

1. Primitive variables:

Primitive variables can be used to represent primitive values.

Example: int x=10;

2. Reference variables:

Reference variables can be used to refer objects.

Example: Student s=new Student();

Diagram:
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.
Example:
class Test
{
boolean b;
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.b);//false
}
}
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.
Example:
class Test
{
static int i=10;
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.i);//10
System.out.println(Test.i);//10
System.out.println(i);//10
}
}

For the static variables it is not required to perform initialization explicitly, JVM will always provide default
values.
Example:
class Test
{
static String s;
public static void main(String[] args)
{
System.out.println(s);//null
}
Example:
class Test
{
int x=10;
static int y=20;
public static void main(String[] args)
{
Test t1=new Test();
t1.x=888;
t1.y=999;
Test t2=new Test();
System.out.println(t2.x+"----"+t2.y);//10----999
}
}

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 is declared
and destroyed once that block execution completes. Hence the scope of the local
variables is exactly same as scope of the block in which we declared.

Example 1:
class Test
{
public static void main(String[] args)
{
int i=0;
for(int j=0;j<3;j++)
{
i=i+j;
}
}}
Example 2:
class Test
{
public static void main(String[] args)
{
try
{
int i=Integer.parseInt("ten");
}
catch(NullPointerException e)
{
System.out.println(i)
}
}
}
 The local variables will be stored on the stack.
 For the local variables JVM won't provide any default values compulsory we
should perform initialization explicitly before using that variable.
 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.
Whether the class contains main() method or not,
and whether it is properly declared or not,
these checking's are 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: NoSuchMethodError: main
At runtime JVM always searches for the main() method with the following prototype.
If we are performing any changes to the above syntax then the code won't run and will
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
o String[] args
o String []args
o 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.
6. class Test {
7. static final syncronized strictfp public void main(String... ask){
8. System.out.println("valid main method");
9. }
10. }
11. output :
12. 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 int main(String[] 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.

Example:
class Test
{
public static void main(String[] args)
{
System.out.println("String[] array main method"); //overloaded
methods
}
public static void main(int[] args)
{
System.out.println("int[] array main method");
}
}
Output:
String[] array main method
Various Memory areas present inside JVM :

1. Class level binary data includung 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 in native method stacks.

You might also like