0% found this document useful (0 votes)
15 views33 pages

Chapter 1) Language Fundamentals

Uploaded by

stalekar2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views33 pages

Chapter 1) Language Fundamentals

Uploaded by

stalekar2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

What is Java Programming Language.

Java is a programming language and a platform. Java is an platform independent, object-


oriented, class-based, secured and general-purpose, high level programming language used
for to develop console based application, web application and mobile application.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995. James Gosling is known as the father of Java.

Java Platforms

• Java platform SE (Java Standard Edition)


• Java platform EE (Java Enterprise Edition)
• Java platform ME (Java Micro Edition)
• Java platform FX
Platform : Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

Features of java
Object-Oriented
Java is an object-oriented programming language. Object-oriented programming is a
methodology in which application program can be develop using class and object. So it
simplifies software development and maintenance by providing some rules.

Basic concepts of Object-oriented programming are Class, Object, Inheritance,


Polymorphism, Encapsulation and Abstraction.

Compile And Interpreter


Java programming language has both Feature Compiler and Interpreter. Java source code
firstly compile by the compiler and convert into bytecode (.class file) and this bytecode is
converted into machine code by Java Interpreter (JVM).

Platform Independent
Java is platform independent programming language. Which is a write once, run
anywhere language. Java source code can be executed on multiple platforms. for example,
Windows, Linux, Mac/OS, etc

Java source code is compiled by the compiler and converted into bytecode. This bytecode
is a platform-independent code because it can be run on multiple platforms by the Java
Virtual Machine.

1
Difference between Java and C++

C++ Java

C++ is platform-dependent. Java is platform-independent.

C++ is mainly used for system programming. Java is mainly used for application programming.
It is widely used in console based application,
web application and mobile application.

C++ supports operator overloading. Java doesn't support operator overloading.

C++ supports pointers. Java supports pointer internally. But we cannot


declare explicit pointer.

C++ uses compiler only which converts source Java uses both compiler and interpreter. Java
code into machine code. source code is converted into bytecode at
compilation time. The interpreter executes this
bytecode at runtime.

C++ supports both call by value and call by Java supports call by value only. There is no call
reference. by reference in java.

Components Of Java
What is the JVM in Java ?
JVM stands for Java Virtual Machine is an abstract machine. It is called a virtual machine
because it doesn't physically exist. It is a specification that provides a runtime environment
in which Java bytecode can be executed. It can also run those programs which are written in
other languages and compiled to Java bytecode.

Java Virtual Machine are available for many hardware and software platforms. Java
Virtual Machine, Java Runtime Environment, and Java Development Kit are platform
dependent because the configuration of each Operating System is different from each other.
However, Java is platform independent.

The Java Virtual Machine performs Loads code, Verifies code Executes code Provides
runtime environment.

2
What is the JRE in Java ?
JRE stands for Java Runtime Environment. It is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment. It is the
implementation of Java Virtual Machine. It contains a set of libraries and other files that Java
Virtual Machine uses at runtime.

What is the JDK in Java ?


JDK stands for Java Development Kit. It is a software development environment it is used
to develop Java applications. It contains Java Runtime Environment and development tools.

The Java Development Kit is an implementation of one of the Java Platform :

• Standard Edition (Java SE),


• Enterprise Edition (Java EE),
• Micro Edition (Java ME),

The Java Development Kit contains is a Java Virtual Machine (JVM), Java Runtime
Environment (JRE), java interpreter and java compiler etc.

Difference between JVM, JRE, and JDK.

Java Virtual Machine Java Runtime Environment Java Development Kit


JVM stands for Java JRE stands for Java JDK stands for Java
Virtual Machine. JVM is Runtime Environment. It Development Kit. It contains
used for run Java bytecode. contains a set of libraries a JVM, JRE, java interpreter
.Java applications are called and other files. and java compiler.
Write Once Run Anywhere
language.

3
Chapter 1) Language Fundamentals
Tokens Of Java
Identifiers
A name in java program is called identifier. which can be used for identification purposes. it
can be variable name, method name or class name.

Rules For defining java identifiers


➢ The only allowed characters in java identifiers are
A To Z
a To z
0 To 9
$
_ (underscore)

➢ identifiers can’t start with digits.


total123 (valid)
123total (invalid).

➢ Java identifiers are case sensitive.


int number = 10;
int Number = 20;

➢ We can’t use reserved words as identifiers.


int if = 10; (invalid)

➢ Identifiers can starts with $ and underscore ( _) symbol.


_$_ (valid)
$_$ (valid)

➢ All predefined java class and interface names we use as identifiers.

4
Reserved words
Reserved words are predefined words to represent a meaning and functionality such type of
word are called reserved words.

Reserved words : 53 , Keywords : 50 , Reserved Literals : 3,

Used Keywords : 48, Unsed Keywords : 2 .

Keywords for data types (8)

1) byte
2) short
3) int
4) long
5) float
6) double
7) char
8) boolean

Keywords for flow control (11)

1) if
2) else
3) switch
4) case
5) default
6) while
7) for
8) do
9) break
10) continue
11) return

5
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 handling (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 (4)

1) new
2) instanceof
3) super
4) this

Void return type : If a method won't return anything compulsory that method should be declared
with the void return type.

1) void

6
Data Types
Data type are used to define type of variable and size of variable. There are two types of data types in
Java.

1) Primitive Data Types : Primitive type are predefined by the language and is named by a
reserved keyword.
2) Non-Primitive Data Types : Non-Primitive type are user-defined data types created by
programar or developer.

• Except Boolean and char remaining data types are considered as signed data types because
we can represent both "+ve" and"-ve" numbers.

1] Primitive Data Types


1) Numeric (Signed) data type

1. Integral data

2. Floating-point data type

2) Non-Numeric (unsigned) data type

Integer data types :


1. Byte :
Size : 1 byte ( 8 bits )
Maxvalue : +127
Minvalue : -128
Range : - 128 to 127
Example :
✓ byte b = 10;
✓ byte b = 127;
byte b = 130;
C.E :
Possible loss of precision
Found : int
Required : byte

byte b = 10.50;
C.E :
Possible loss of precision
Found : double
Required : byte

7
byte b = true;
C.E :
Incompatible types
Found : boolean
Required : byte

byte b = “Rohan” ;
C.E :
Incompatible types
Found : java.lang.String
Required : byte

2. Short :
Size : 2 byte
Maxvalue : + 32767
Minvalue : - 32768
Range : - 32768 to 32767
Example :
✓ Short s = 10;
✓ Short s = 32767;
Short s = -32768;
C.E :
Possible loss of precision
Found : int
Required : Short

Short s = 10.50;
C.E :
Possible loss of precision
Found : double
Required : Short

Short s = “Rohan” ;
C.E :
Incompatible types
Found : java.lang.String
Required : Short

8
3. int :
Size : 4 byte
Maxvalue : + 2147483647
Minvalue : - 2147483648

Example :
✓ int i = 10;
✓ int i = 2147483647;
int i = 2147483648;
C.E :
Integer Number To Larege
Short s = 10.50;
C.E :
Possible loss of precision
Found : double
Required : int

Short s = “Rohan” ;
C.E :
Incompatible types
Found : java.lang.String
Required : int

4. Long :
Size : 8 byte
Maxvalue : + 263-1
Minvalue : - 263

Example :
✓ long l = 10;
✓ long l = 2147483647;

long l= 10.50;
C.E :
Possible loss of precision
Found : double
Required : long

Short s = “Rohan” ;
C.E :
Incompatible types
Found : java.lang.String
Required : long

Note : byte, short, int and long data types can be used to represent whole numbers

9
Floating Point Data types :
Float double
1) If we want to 5 to 6 decimal places of 1) If we want to 14 to 15 decimal places of
accuracy then we should go for float. accuracy then we should go for double.
2) Size : 4 bytes. 2) Size : 8 bytes.
3) Range : -3.4e38 to 3.4e38. 3) Range : -1.7e308 to1.7e308.
4) Float follows single precision. 4) Double follows double precision.
5)
Boolean data type :
Size : Not applicable (virtual machine dependent)
Range : Not applicable but allowed values are true or false.

Example :
✓ boolean b = true;
✓ boolean b = false;

boolean b = 0;
C.E :
Incompatible types
Found : int
Required : boolean

Char data type :


In old languages like C & C++ are ASCII code based but java is Unicode based and the number
Of unicode characters are > 256 and <= 65536 to represent all these characters 1 byte is not enough
compulsory we should go for 2 bytes.

Size : 2 bytes
Range : 0 to 65535

Data Types Size Range Wrapper class Default value


byte 1 bytes -128 TO +127 Byte 0
short 2 bytes -32768 TO +32767 Short 0
int 4 bytes -2147483648 TO +2147483647 Integer 0
long 8 bytes - 263 TO + 263-1 Long 0
float 4 bytes -3.4e38 TO 3.4e38. Float 0.0
double 8 bytes -1.7e308 TO 1.7e308. Double 0.0
char 2 bytes 0 to 65535 Character 0
boolean Not applicable true or false Boolean false

10
Why is Java a strongly typed language ?
➢ Java is strongly typed language because, type checking is very strong.

Java is pure object oriented programming or not ?

➢ Java is not pure object oriented programming language because several OOP’s features (like
multiple inheritance, operator overloading) are not supported by java. moreover we are
depending on primitive data types which are non objects.

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

Integer Literals
For the integral data types byte, short, int and long we can specify literal value in Decimal
literals, Octal literals and Hexa Decimal forms.

1) Decimal literals :
Allowed digits are 0 to 9.
Example : int x = 10;

2) Octal literals :
Allowed digits are 0 to 7.
Literal value should be prefixed with 0.
Example : int x = 010;
Int x =0759 ; → integer number too large

3) Hexa Decimal literals :


The allowed digits are 0 to 9, A to F.
Literal value should be prefixed with 0x (or) 0X.
Example : int x = 0X10Ab;

By default every integral literal is int type but we can specify explicitly as long type.
Example : long x = 10L;

11
Floating Point Literals
By default every Floating point literal is double type but we can specify explicitly as float
type.

Example : float x = 10.5f;

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

Example : double d = 010.8;

Boolean literals
The only allowed values for the boolean type are true or false.

Example : boolean d = true ;

Char literals
A char literal is represented by a single character in single quotes ( ‘ ‘ ).

Example :
✓ char ch = ‘a’;
char ch = a ;
C. E :
cannot find symbol
symbol : Variable a
Location : Class ……….

Char ch = “a” ;
C. E :
Incompatible types
Found : java.lang.String
Required : char

Char ch = ‘ab’;
C. E : → Unclosed Character literal
• We can specify that integral literal in decimal, octal or hexadecimal form but allowed
values range is 0 to 65535.

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

Example :
✓ String s = “Sunil” ;

12
❖ Types of Variables

There are two division’s.

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

1. Primitive variables
2. Reference variables

1) Primitive variables : can be used to represent primitive values such type of variables
are called Primitive variables.

Example : int x = 10 ;

2) Reference variables : can be used to refer objects values such type of variables are
called Reference variables.

Example :

Student s1 = new Student ( ) ;

Division 2 : Based on the position of declaration and behaviour. all variables are divided into 3
types.

1. Instance variables.
2. Static variables.
3. Local variables.

1) Instance variables :

• If the value of a variable is different 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 should be declared with in the class directly but outside of any
method, block or constructor.
• 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 the
scope of objects.
• Instance variables will be stored on the heap as the part of object.
• We can not be access Instance variables directly from static area. But we can access by
using object reference.
• Instance variables can be access directly from Instance area.

13
Example :

class Test
{
int x = 10;
public static void main(String[] args) {
X System.out.println("X = "+x);
C.E :
on-static variable x cannot be referenced from a static context
Test t1 = new Test();
System.out.println("X = "+t1.x);
t1.M1();
}
public void M1( )
{
System.out.println("X = "+x);
}
}

• For the instance variables JVM will always provide default values. and we ate not
required to perform initialization explicity.

Example :
class Test
{
boolean b;
public static void main(String[] args)
{
Test t1 = new Test();
System.out.println("B = "+t1.b); // B = false
}
}
• Instance variables also known as object level variables.

14
2) Static variables :

• If the value of a variable is not different 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 static variables for a singal copy will be created at class level and shared by
every object of that class.
• Static variables should be declared with in the class directly but outside of any method,
constructor or block.
• 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.

java TEST
1) Start JVM.
2) Create and start Main Thread
3) Locate(find) Test.class by main Thread.
4) Load Test.class by main Thread. // static variable creation
5) Execution of main() method.
6) Unload Test.class // static variable destruction
7) Terminate main Thread.
8) Shutdown JVM.

• Static variables will be stored in method area.


• We can access static variables either by object reference or by class name .

Example :

class Test
{
static int x = 10;
public static void main(String[] args)
{
System.out.println(x);
Test t1=new Test( );
System.out.println(t1.x);
System.out.println(Test.x);
}
}

• We can access static variables directly from both static area and instance area directly.
• Static variables also known as class level variables.

15
3) Local variables :

• We can declare variables inside a method or block or constructors such type of variables
are called local variables or temporary variables.
• local variables will be created while executing the block in which we declared it. Once
block execution complete automatical local variable will be destroy. Hence the scope of
the local variables is exactly same as scope of the block in which we declared it.
• Local variables will be stored inside stack memory.

Example :

class Test
{
public static void main(String[] args)
{
Int i = 0 ;
for(int j = 0 ; j < 3 ; j++)
{
i=i+j;
}
System.out.println( “ I = “+ i );
X System.out.println( “J = “ + j);
C.E :
Cannot find symbol
Symbol : variable j
Location : class Test
}
}

• For the local variables JVM not provide any default values compulsory we should
perform initialization explicitly before using that variable.

class Test
{
public static void main(String[] args)
{
int x ;
System.out.println( “ X = “+ x );
C.E :
Variable x mighat not have been initialized
}
}

16
Note :

• The only applicable modifier for local variables is final. If we are using any other modifier
than we will get compile time error.
• If we are not declaring any modifier then by default it is default. but this rule is
applicable for only static and instance variables but not local variable.
• Instance and static variables can be accessed by multiple Threads simultaneously and
hence these are not Thread safe. but in the case of local variable for every thread a
seperat copy will be created and hence local variables are Thread safe.

Type of Variable Thread Safe


Instance No
static No
local yes

• Every variable in java should be either instance , static or local.


• Every variable in java should be either primitive or reference.
• Example :

class Test {
int x = 10 ; → instance - primitive
static String s = "Rohan"; → static - reference

public static void main(String[] args) {


int [] y = new x [ 1 ] ; → local - reference
}
}

17
❖ (Variable No Of Argument Methods) (1.5)
We can declare a method with variable number Of arguments such type of methods are
called var-arg methods.

• We can declare a var-arg method as

Syntax :

Method_Nname(data_type… variable_name)

Example :

Show(int…x)

• We can call this method by passing any number Of int values including zero number
also.

Example :
✓ Show( ) ;
✓ Show(10) ;
✓ Show(10,20) ;
✓ Show(10,20,30) ;

Example :

class Test
{
public static void main(String[] args)
{
Show(10) ;
Show(10,20) ;
Show(10,20,30) ;
}
public static void Show(int…x)
{
System.out.println( “Var- arg methods“);
}
}

Output :
Var- arg methods
Var- arg methods
Var- arg methods

18
• Internally var-arg parameter implemented by using one dimensional array. hence
within the var-arg method we can differentiate values by using index.

Example :
class Test
{
public static void main(String[] args) {
sum(10) ;
sum (10,20) ;
sum (10,20,30) ;
}
public static void sum (int…x) {
int tot = 0 ;
for(int x1 : x) {
tot +=x1;
}
System.out.println("The Sum = "+tot);
}
}
Output :
The Sum = 0
The Sum = 30
The Sum = 60
The Sum = 100

Case 1

Which of the following var-arg method declarations are valid ?

✓ sum(int... x)
✓ sum(int …x)
✓ sum(int…x)
x sum(int x…)
x sum(int. ..x)
x sum(int .x.. )

19
Case 2

We can mix var-arg parameter with normal parameters also.

Example :

✓ sum(int y, int... x);


✓ sum(String s, int …x);

Case 3

If we mix normal parameter with var-arg parameter then var-arg parameter should be the
last parameter.

Example :

x sum(int…x, int y);

✓ sum(double d, int... x);

Case 4

Inside var-args method we can take only one var-arg parameter and we can not take more
than one var-arg parameter.

Example :

x sum(int…x, int…y);

Case 5

Inside a class we can not declare var-arg method and corresponding one dimensional array
method simultaneously other ways we will get compile time error.

Example :

class Test
{
public static void M1(int...x)
{
System.out.println("Var-Arg Method");
}
public static void M1(int[ ] x)
{
System.out.println("Array Method");
}
}
C.E :
Cannot declare both M1(int...) and M1(int[]) in Test

20
Example :

public class Test


{
public static void M1(int...x)
{
System.out.println("Var - Arg Method");
}
public static void M1(int x)
{
System.out.println("Genral Method");
}
public static void main(String[] args) {
M1();
M1(10,20);
M1(10);
}
}

Output :
Var - Arg Method
Var - Arg Method
Genral Method

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.

Single dimensional array vs var-arg method


Case 1

Wherever one dimensional array present we can replace with var-arg parameter.

Example :

✓ M1(int[ ] x) → M1(int…x)
✓ main(String [ ] args) → main(String…args)

Case 2

Wherever var-arg parameter present we can not replace with one dimensional array..

Example :

X M1(int…x) → M1(int[ ] x)

21
Note :

1) M1(int…x)
we can call this method by passing a group of int values and x will become one dimensional
array.
M1(int…x) → int[ ] x

2) M1(int[ ] …x)
we can call this method by passing a group of one dimensional and x will become two
dimensional array.
M1(int[ ] …x) → int[ ][ ] x
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]);
}
}
}

Output
10
40

22
❖ Main Method
• Whether class contains main( ) method or not and whether main( ) method is declared
according to requirements or not these think won't be checked by compiler, at runtime
JVM is responsible to check this think.
• If JVM unable to find 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 as

public static void main (String[ ] args)

To call by Without existing main( ) method This is the Command


jvm from any object also JVM won't return name which line
anywhere has to call this anything to configure arguments
method JVM inside JVM

• The above syntax is very strict and if we perform any changes then we will get runtime
exception saying
NoSuchMethodError: main.

• Even though above syntax is very strict but some changes are acceptable to main( )
method.

1) Instead of public static we can take static public that is the order of modifier is
not important.
2) We can declare string[ ] in any acceptable form.
✓ main(String[ ] args)
✓ main(String [ ]args)
✓ main(String args[ ])

3) Instead of args we can take any valid java identifier.


✓ main(String[ ] xyz)

23
4) We can replace string[] with var-arg parameter.
✓ main(String… xyz)

5) We can declare main( ) method with the following modifiers.


final, synchronized, strictfp.

Example :

class HelloWorld
{
public static final synchronized strictfp void main(String...args)
{
System.out.println("Valid Main Method.!");
}
}

Output
Valid Main Method.!

Q 1) Which of the following main() method declarations are valid ?


X public static void main(String args)

X public static void Main(String[ ] args)

X public void main(String[ ] args)

X public static int main(String[ ] args)

X public final synchronized strictfp void main(String[ ] args)

/ public final synchronized strictfp void main(String[ ] args)

/ public static void main(String…X)

24
Q 2) In which of the above cases we will get compile time error ?
We won't get compile time error any anywhere but except last two case in remaining we will
get runtime exception saying : NoSuchMethodError: main.

Case 1

• Overloading of the main() method is possible but JVM is always call String[ ] array
argument main() method only.
• The other overloaded method we have to call explicitly like normal method call.
• Example :
class Test
{
public static void main(String[ ] args)
{
System.out.println("String Array ");
}
public static void main(int [ ] args)
{
System.out.println("int Array ");
}
}
Output

String Array

Case 2

• Inheritance concept is applicable for main( ) method hence while executing child class if
the child class doesn't contain main( ) method then the parent class main( ) method will
be executed.
• Example :
class Perent
{
public static void main(String[ ] args)
{
System.out.println("Perent Main");
}
}
class Child extends Perent
{
}
javac Perent.java

Perent. class Child.class

javac Perent

Output : Perent Main

javac Child

Output : Perent Main

25
Case 3
class Perent
{
public static void main(String[ ] args)
{
System.out.println("Perent Main");
}
}
class Child extends Perent
{
public static void main(String[ ] args)
{
System.out.println("Child Main");
}
}

javac Perent.java

Perent. class Child.class

javac Perent

Output : Perent Main

javac Child

Output : Child Main

• It seems overriding concept is applicable for main( ) method but it is not overriding it is
method hiding.
• Note : For main( ) method Inheritance and Overloading concept are applicable but
overriding concept is not applicable.

1.7 Version Enhansements with respect to main( )


Case 1

• Untill 1.6 version if the class doesn't contain main() method then we will get Runtime
Exception saying NosuchMethodError : main.
• But from 1.7 version onwards instead of NoSuchMethodError we will get more meaning
full description error information.
• Example :
class Test
{
}

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

26
Case 2

• From 1.7 version onwards main() method is compulsory to start program execution, hence
even though the class contains static block if won't be executed if the class doesn't main( )
method.
• Example :
class Test
{
static
{
System.out.println("Static Block.!");
}
}

1.7 version
1.6 version
javac Test.java
javac Test.java
java Test
java Test
Error : main method not found in class Test, please
Output : Static Block.!
define the main method as public static void
R.E : NosuchMethodError : main
main(String[ ] args)

Case 3
class Test
{
static
{
System.out.println("Static Block.!");
System.exit(0);
}
}

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

Case 4
class Test
{
static
{
System.out.println("Static Block.!");
}
public static void main(String[ ] args)
{
System.out.println("Main Method.");
}
}
1.6 version 1.7 version
javac Test.java javac Test.java
java Test java Test
Output : Static Block.! Output : Static Block.!
Main Method. Main Method.

27
1.6 version
Identification of static members

Execute static block and static


variable assignment

Available Not Available

Check for
Execute main() method R.E : NosuchMethodError : main
main()

1.7 version
Check for main() Not Available

Available
Error : main method
Identification of static members not found in class Test,
please define the main
method as public static
void main(String[ ] args)
Execute static block and static
variable assignment

Execute main() method

28
❖ Command line arguments
• The arguments which are passing from command prompt are called command line arguments.
• With this command line argument JVM will create an array and by passing that array as
argument. JVM will call main( ) method.
• Example :
Java Test A B C

args[0]
args[1]
args[2]

args.length ---- 3

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

Case 1

• Example :
class Test
{
public static void main(String[] args)
{
for( int i = 0 ; i < = args.length ; i++)
{
System.out.println(args[i]);
}
}
}
Output Output
javac Test . java javac Test . java Output
java Test A B C java Test A B javac Test . java
Output java Test
Output Output
A A
B B R.E :
C
R.E : R.E : ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException ArrayIndexOutOfBoundsException

• If we replace < = with < then we won't get any runtime exception.

Case 2

• Example :
class Test
{
public static void main(String[] args)
{
String [] argh = {"A" , "B" , "C"};
args = argh;
fors( String x : args)
{
System.out.println(x);
}
}
}

29
Output Output
javac Test . java javac Test . java
java Test X Y Z java Test
Output Output
A A
B B
C C

Case 3

• Within the main() method command line arguments are available in String form.
• Example :
class Test
{
public static void main(String[] args)
{
System.out.println(args[0] + args[1]);
}
}

Output

javac Test . java

java Test 10 20

Output

1020

Case 4

• Space itself separator between command line arguments if are command line argument itself
contains space than we have to enclose that command line argument with double quotes ( “ “
).
• Example :
class Test
{
public static void main(String[] args)
{
System.out.println(args[0]);
}
}

Output

javac Test . java

java Test “Note Book“

Output

Note Book

30
❖ Java coding standards

• Whenever we are writing java code, It is highly recommended to follow coding standards.
• Whenever we are writing any component (Like : class, method or variable) 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
improve.
• Example :

class A package com.durgsoft.scjpdemo;


{ class Calculator
public int m1 (int a, int b ) {
{ public static int add ( int number1 , int number2 )
return x + y ; {
} return number1 + number2 ;
} }
}
Ameerpet Coding Standards Hitech-City Coding Standards

1) Coding Standards For Classes :


• Usually class names are nouns.
• Should starts with uppercase Character and if it contains multiple words then every inner word
should starts with uppercase Character.
• Example :
String
Frame
Button Nouns
Student
Employ

2) Coding Standards For Variables :


• Usually class variable are nouns.
• Should starts with lowercase Character and if it contains multiple words then every inner word
should starts with uppercase Character. .(camel case convention)
• Example :
length
name
age Nouns
mobileNumber
accountNumber

3) Coding Standards For methods :


• Usually method names are either verbs or verb-noun combination.
• Should starts with lowercase Character and if it contains multiple words then every inner word
should starts with uppercase Character. .(camel case convention)

31
• Example :
run( )
add( )
sleep( ) VERB getName( )
println( ) setName( ) VERB - Nouns
print( ) toArray( )

4) Coding Standards For interfaces :


• Usually interface names are adjectives.
• Should starts with uppercase Character and if it contains multiple words every then inner word
should starts with uppercase Character.
• Example :
Runnable( )
Serializable( ) ADJECTIVES
Cloneable( )

5) Coding Standards For constants :


• Usually constants are nouns.
• Should contain only uppercase characters and if it contains multiple words then these words
are separated with underscore ( _ ) symbol.
• Example :

MAX_VALUE
MAX_PRIORITY Nouns
NORM_PRIORITY

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

6) Coding Standards For listeners :


Case 1 : To register a listener
Method name should be prefixed with add.
✓ public void addMyActionListener( MyActionListener l )
X public void registerMyActionListener( MyActionListener l )
X public void addMyActionListener ( ActionListener l )

Case 1 : To unregister a listener


The method name should be prefixed with remove.
✓ public void removeMyActionListener( MyActionListener l )
X public void unregisterMyActionListener( MyActionListener l )
X public void removeMyActionListener ( ActionListener l )
X public void deleteMyActionListener( MyActionListener l )

32
7) Java bean coding standards :
• A java bean is a simple java class with private properties and public getter and setter
methods.
• Example : Class name ends with bean is not
official convention frome sun
class StudentBean
{
private String name;
public void setName ( String name )
{
this.name = name ;
}
public String getName( )
{
return name;
}
}

Syntax for setter method

1. It should be public
2. The return type should be void.
3. Method name should be prefixed with set.
4. Compulsory it should take some argument.

Syntax for getter method

1. It should be public
2. The return type should not be void.
3. Method name should be prefixed with get.
4. It should not take any argument.
Note :
For the boolean properties the getter method can be prefixed with either get or is.
But recommended to use is.

Example :

private boolean empty;


Public boolean getEmpty( )
{
return empty ;
}
// valid

private boolean empty;


Public boolean isEmpty( )
{
return empty ;
}
// valid

33

You might also like