Sei sulla pagina 1di 55

National Institute of Research & Advisory

Java
oriented and secure programming language. Java is a programming language and a
Java is a high level, robust, object-oriented
platform.

OOPs (Object-Oriented
Oriented Programming System)
Object means a real-world Object-Oriented Programming is a
world entity such as a pen, chair, table, computer, watch, etc. Object
methodology or paradigm to design a program using classes and objects.

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.

oriented programming language because several OOP’s features are not


Java is not considered as pure object--oriented
satisfied by java (like operator overloading, multiple inheritance etc.). Moreover, we are depending on primitive data
types in Java which are non-objects.
Language Fundamental
 Identifiers: - A name in java program is called identifier, which is used for identification purpose. It can be class
name, method name, variable name or label name.

public class Test


{

public static void main(String[] args)


{
int x=10;

In the above example contains 5 identifiers (Test, main, String, args and x)

 Rules for defining java identifiers :-


a) The only allowed characters in java identifiers are both uppercase letters (A to Z), & lowercase letters (a to z),
digits (0 to 9), $ and Underscore ( _ ). If we are using any other character then we will get compilation time
error.

Example:
total_number // valid
total# // invalid

b) The first letter of an identifier should be either a latter or an underscore (Identifiers can’t start with digit).

Example:
total123 // valid
123total // invalid

c) Java identifiers are case sensitive of course java language itself considered/ treated as case sensitive
programming language.

public class Test


{
public static void main(String[] args)
{
int number=10;
int Number=20;
int NUMBER=30;

In this example we can differentiate number, Number and NUMBER with respect to case.
d) There is no length limit for java identifiers but it is not recommended to take too lengthy identifiers.
e) We can’t use reserved words as identifiers.

Example:
int x = 10; // valid
int if = 20; // invalid

f) All predefine java class name and interface names we can use as identifiers.

public class Test public class Test


{ {

public static void main(String[] public static void main(String[]


args) args)
{ {
int String=888; int runnable=999;
System.out.println(String); System.out.println(runnable);

} }

} }
Output: 888 Output: 999

All predefine java class name and interface names we can use as identifiers. Even though it is valid but it is not a
good programming practices because it reduces readability and creates confusion.

Que: - Which is valid or invalid identifiers?


total_number valid all@hands invalid
total# invalid Java2share valid
123total invalid java2share valid
total123 valid Integer valid
ca$h valid Int valid
_$_$_$_$_ valid int valid
 Reserved Words: In java va some words are reserved word to represent some meaning or functionality such types
of words are called reserved words.

None of these reserved words can be used as variable names in java programming.
a) Keywords for data types: 8 keywords for data types

 byte: The Java byte keyword is a primitive data type. It is used to declare variables.
vari It can also be used with
8 bit signed two's complement integer.
methods to return byte value. It can hold an 8-bit
 short: The Java short keyword is a primitive data type. It is use
usedd to declare variables. It can also be used with
methods. It can hold a 16-bit
bit signed two's complement integer.
 int: The Java int keyword is a primitive data type. It is used to declare variables. It can also be used with
32 bit signed two's complement integer.
methods to return integer type values. It can hold a 32-bit
 long: The Java long keyword is a primitive data type. It is used to declare variables. It can also be used with
methods. It can hold a 64-bit
bit two's complement integer.
 float: The Java float keyword single-precision 32--bit IEEE 754 floating point. It is
ord is a primitive data type. It is a single
used to declare the variables and methods. It represents the fractional numbers.
 double: The Java double keyword is a primitive data type. It is a double-precision
double precision 64-bit IEEE 754 floating
point. It is used to declare the variables and methods. It generally represents the decimal numbers.
 boolean: The boolean keyword is used to declare a variable as a boolean type. It can hold True and False values
only. Its default value is false. It is generally associated with conditional statements.
 char: The Java char keyword is a primitive data type. It is used to declare the character-type
character variables and
methods. It is capable of holding the unsigned 16-bit
16 Unicode characters.
b) Keywords for flow control: 11 keywords for flow control
 if: Java if keyword tests the condition. It executes the if block if condition is true.
 else: Java else keyword is used to indicate the alternative branches in an if statement.
 switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch
statement tests the equality of a variable against multiple values.
 default: A Java default keyword is an access modifier. If you didn't assign any access modifier to variables,
methods, constructors and, classes, by default, it is considered as default access modifier.
 while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If
the number of iteration is not fixed, it is recommended to use while loop.
 do: Java do keyword is used in control statement to declare a loop. It can iterate a part of the program several
times.
 for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly
when some conditions become true. If the number of iteration is fixed, it is recommended to use for loop.
 break: Java break keyword is used to break loop or switch statement. It breaks the current flow of the program at
specified condition.
 continue: Java continue keyword is used to continue the loop. It continues the current flow of the program and
skips the remaining code at the specified condition.
 return: Java return keyword is used to return from a method when its execution is complete.

c) Keywords for modifiers: 11 keywords for modifiers and if with count default then 12 keywords

 public: Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It
has the widest scope among all other modifiers.
 private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be
accessed only in the class in which it is declared.
 protected: Java protected keyword is an access modifier. It can be accessible within package and outside the
package but through inheritance only. It can't be applied on the class.
 static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in
Java is used for memory management mainly.
 final: Java final keyword is used to indicate that a variable holds a constant value. It is applied with a variable. It
is used to restrict the user.
 abstract: Java abstract keyword is used to declare abstract class. Abstract class can provide the implementation
of interface. It can have abstract and non-abstract methods.
 synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded
code.
 native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java
Native Interface).
 strictfp (Introduce in 1.2 version): Java strictfp is used to restrict the floating-point calculations to ensure
portability.
 transient: Java strictfp is used to restrict the floating-point calculations to ensure portability.
 volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
d) Keywords for exception handling: 6 keywords for exception handling
 try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be
followed by either catch or finally block.
 catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the
try block only.
 finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always executed
whether exception is handled or not.
 throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to
throw custom exception. It is followed by an instance.
 throws: The Java throws keyword is used to declare an exception. Checked exception can be propagated with
throws.
 assert (Introduce in 1.4 version):

e) Class related keywords (6 keywords):

 class: A Java class keyword is the most common keyword which is used to declare a new Java class. A class is a
container that contains the block of code that includes field, method, constructor, etc.
 interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
 extends: Java extends keyword is used to indicate that a class is derived from another class or interface.
 implements: Java implements keyword is used to implement an interface.
 package: Java package keyword is used to declare a Java package that includes the classes.
 import: Java import keyword makes classes and interfaces available and accessible to the current source code.
f) Object related keywords (4 keywords):
 new: Java new keyword is used to create new objects.
 instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or
implements an interface.
 super: Java super keyword is a reference variable that is used to refer parent class object. It can be used to
invoke immediate parent class method.
 this: Java this keyword can be used to refer the current object in a method or constructor.
{delete keyword not there in java}
g) Void return type keyword : In java return type is mandatory if a method won’t return anything then we have to
declare that method with void return type. But in c language return type is optional and the default return type is
int.

h) Unused keywords (2 keywords) :

 goto: Usage of goto created several problems in old language and hence sum people banned this keyword in java.
 const: Use final instead of const.
Note: goto and const are unused keywords and if we are trying to use we will get compile time error.
i) Reserved word literals (3) :-
 true and false: value are for boolean data type.
 null: default value for object reference.
j) enum keyword (Introduce in 1.5 version) :- We can use enum to define a group of named constant.
Example:

enum month{

JAN, FEB… DEC;

Conclusions:-

 All 53 reserved words in java contain only lowercase alphabet symbols.


 In java we have only new keyword and there is no delete keyword because destruction of useless objects is
responsibility of garbage collector.
 strictfp : 1.2 version, assert : 1.4 version, enum : 1.5 version the following are new keywords in java.
 Data Types: In Java, every variable and every expression are of some type. Each and every data type is clearly
defined; every assignment should be checked by compiler for type compatibility.

Because of above reasons we can conclude that Java language is strongly typed programming language.
Data types specify the different sizes and values that can be stored in the variable. There are two types of data
types in Java:

 Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
double
 Non-primitive data types: The non-primitive
non data types include Classes, Interfaces, and Arrays.
Arrays

Note: Except boolean and char remaining data types are considered as signed data types because we can
represent both positive and negative numbers.

 Integral Data Types

 byte: The most significant bit as sign bit,0 means positive number and 1 means negative numbers.
Positive number will be represent directly in the memory where as negative number will be represent in the two's
complement form.

Size : 1 byte (8 bits)


Max Value : +127
Min Value : -128
Range : -𝟐𝟕 to 𝟐𝟕 -1
1 = [ - 128 to 127 ]

byte is the best choice if we want to handle data in terms of streams either from the file or from the network (files
supported form or network supported form is byte).
Representation of byte data type in memory:

a) Positive Number

b) Negative Number
two's complement of 127 i.e. -128

Example:
byte b = 10; // valid
byte b = 127; // valid
byte b = 128; // invalid { ce:: incompatible types: possible lossy conversion from int to byte }
byte b = 10.5; // invalid { ce: incompatible types: possible lossy conversion from double to byte }
byte b = true; // invalid lean cannot be converted to byte }
{ ce: incompatible types: boolean
byte b = “Ajay”; // invalid { ce:: incompatible types: String cannot be converted to byte }

 short: This is the most rarely used data type in java. Java came in 1995, that time we have 8085, 8086 micro
processors, 16 bit processor is very famous.
Size : 2 byte (16 bits)
Range : -𝟐𝟏𝟓 to 𝟐𝟏𝟓 -1
1 = [ -32768 to 32767 ]

16 bit processors like 8085 but these processors are completely outdated and
short data type is best suitable for 16-
hence corresponding short data type is also outdated data type.
Example:
short s = 32767; // valid

short s = 32768; ce incompatible types: possible lossy conversion from int to short }
// invalid { ce:

short s = 10.5; ce: incompatible types: possible lossy conversion from double to short }
// invalid { ce:

short s = true; // invalid { ce: incompatible types: boolean cannot be converted to short }
 int: The most commonly and generally used data type in java is int. The int data type is generally used as a
default data type for integral values unless if there is no problem about memory.
Size : 4 byte (32 bits)
Range : -𝟐𝟑𝟏 to 𝟐𝟑𝟏 -1 = [ -2147483648 to 2147483647 ]
Example:
int i = 2147483647; // valid
int i = 2147483648; // invalid { ce: integer number too large: 2147483648 }
int i = 2147483647l; // invalid { ce: incompatible types: possible lossy conversion from long to int }
int i = true; // invalid { cr: incompatible types: boolean cannot be converted to int }

 long: Sometimes int may not enough to hold big values then we should go for long type.
The number of characters present in a big file may exceed int range hence the return type of length method
is long but not int.

long l = f.length( ) ;

Size : 8 byte (64 bits)


Range : -𝟐𝟔𝟑 to 𝟐𝟔𝟑 -1
Note: All the above data types ( byte, short, int, long ) meant/used for only represent integral values, if we want
to represent floating point values then we should go for floating point data type.

 Floating point data types


 floot: If we want 5 to 6 decimal places of accuracy then we should go for float, float follows single precision
Size : 4 byte (32 bits)
Range : -3.4e38 to 3.4e38 = [-3.4 x𝟏𝟎𝟑𝟖 𝐭𝐨 𝟑. 𝟒 𝐱 𝟏𝟎𝟑𝟖 ]

 double: If we want 14 to 15 decimal places of accuracy then we should go for double, double follows double
precision
Size : 8 byte (64 bits)
Range : -1.7e308 to 1.7e308 = [-1.7 x𝟏𝟎𝟑𝟎𝟖 𝐭𝐨 𝟏. 𝟕 𝐱 𝟏𝟎𝟑𝟎𝟖 ]

 Non- Numeric Data Types


 boolean:
Size : Not Applicable [ Virtual Machine(VM) Dependent ]
Range : Not Applicable [ Allowed value are true/ false ]
Example:
boolean b = true; // valid
boolean b = 0; // invalid { ce: incompatible types: int cannot be converted to Boolean }
boolean b = True; // invalid { ce: cannot find symbol, symbol: variable True, location: class Test }

boolean b = “True”; // invalid { ce: incompatible types: String cannot be converted to boolean}

 char: Old languages like ( C or C++ ) are ASCII code based and the number of allowed different ASCII code
are less than or equal to 256.
Size : 2 byte (16 bits)
Range : 0 to 65535

To represent these 256 characters 8 bits are enough hence the size of char in old language is 1 byte.
But java is UNICODE based and the number of different UNICODE characters is greater than 256 and less than
or equal to 65536. To represent these many characters 8 bits may not enough compulsory we should go for 16
bits hence the size of char in java is 2 bytes.
1 bits: 2 character [ 0, 1]
2 bits: 4 character [ 00, 01, 10, 11]
3 bits: 8 character
4 bits: 16 character
5 bits: 32 character
6 bits: 64 character
7 bits: 128 character
8 bits: 256 character
 Summary of java primitive data types :

Note : null is the default value for object reference and we can’t apply for primitives if we are trying
to use for primitive then we will get compile time error.
Example:
char ch = null ; // invalid { ce: incompatible types: <null> cannot be converted to char }
found: null type , required: char
 Literals in java: A constant value which can be assigned to the variable is named /called as a literal.

Name of variable/ identifier

int x = 10 ;

Data type/ keyword Constant value/ literal

 Integral Literals: For integral data type (byte, short, int, long) we can specify literal value in the following base:

 Decimal form (base 10): Allowed digits are 0 to 9.

int x = 10;

 Octal form (base 8): Allowed digits are 0 to 7. Literal value should be prefixed with 0.

int x = 010;

 Hexadecimal form (base 16): Allowed digits are 0 to 9, a to f. For extra digit ( a to f ) we can use both lower
case and upper-case characters, this is one of very few areas where java is not case sensitive. The literal should
be prefixed with 0x or 0X.

int x = 0x10;

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

Which of the following declarations are valid?

int x = 10; // valid { 10 }


int x = 0786; // invalid { ce: integer number too large: 0786 }

int x = 0777; // valid { 511}

int x = 0XFace; // valid { 64206 }

int x = 0xBeef; // valid { 48879 }

int x = 0XBeer; // invalid { ce: expected }


Notes:
 Programmer having the choice to specify the value either Decimal, Octal and Hexadecimal but JVM will always
provide the value in only decimal.
Example:

Output: 34

 By default every integral literal is of int type but we can specify explicitly as long type by suffixed
with l or L.
Example:
int x = 10 ; // valid
long l = 10L ; // valid
int x = 10L ; // invalid { ce: incompatible types: possible lossy conversion from long to int }
long l : 10 ; // valid

 There is no direct way to specify byte and short literal explicitly but indirectly we can specify. Whenever we are
assigning integral literal to the byte variable and if the value within the range of byte then compiler treats it
automatically as byte literal similarly short literal also.
Example:
byte b = 10 ; // valid

byte b = 127 ; // valid

byte b = 128 ; // invalid { ce: incompatible types: possible lossy conversion from int to byte }

short s = 32767 ; // valid

short s = 32768 ; //invalid { ce: incompatible types: possible lossy conversion from int to short }
 Floating Point Literals

 By default, every floating-point literal is of double type and hence we can’t assign directly to the float variable.
But we will specify floating-point literal as float data type by suffixed with f or F.

Example:
float f = 123.456 ; // invalid { ce: incompatible types: possible lossy conversion from double to 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 off course this convention
is not required.

Example:

double d = 123.456D; // valid

float f = 123.456d; // invalid { ce: incompatible types: possible lossy conversion from double to float }

 We can specify floating point literal 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 { It is decimal literal but not octal literal }
double d = 0x123.456 ; // invalid { ce: malformed floating point literal }

 We can assign integral literal directly to floating-point variables and such integral literal can be specified either
in decimal, octal, or hexadecimal form.
Example:
double d = 0786 ; // invalid { integer number too large }
double d = 0XFace ; // valid
double d = 0786.0 ; // valid
double d = 0xface.0 ; // invalid { malformed floating point literal }
double d = 10 ; // valid
double d = 0777 ; // valid

 We can’t assign floating-point literals to integral types.


Example:
double d = 10 ; // valid
int x = 10.0 ; // invalid { incompatible types: possible lossy conversion from double to int }
 We can specify floating point literal even in exponential form.
Example:
double d = 1.2e3; // valid { Output is 1200.0 }
float f = 1.2e3; // invalid { incompatible types: possible lossy conversion from double to float }
float f = 1.2e3F; // valid { Output is 1200.0 }

 boolean literals: The only allowed values for boolean data type are true or false.
boolean b = true ; // valid
boolean b = 0 ; // invalid { ce: incompatible types: int cannot be converted to boolean }
boolean b = True ; // invalid {ce: cannot find symbol, symbol: variable True,
True location: class Test}
boolean b = “ true” ; // invalid { ce: incompatible types: String cannot be converted to boolean}
boolean

Example:

{Compile time error: incompatible types: int cannot be converted to boolean}

 char literals: We can specify char literal as single character within single quotes.

Example:
char ch = ‘a’ ; // valid
char ch = a; // invalid { ce: cannot find symbol, symbol: variable aa, location: class Test }
char ch = “a” ; // invalid {ce: incompatible types: String cannot be converted to char }
char ch = ‘ab’ ; // invalid { compile time error are given below in picture }
 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, octal or hexadecimal forms. But allowed range is 0 to 65535.

Example:
char ch = 97 ; // valid { Output is a }
char ch = 0xface ; // valid { Output is ? } The corresponding characters are not available or define.

char ch= 0777 ; // valid { Output is ? } Corresponding characters is available but font is not in
my system
char ch = 65535 ; // valid { Output is ? }
char ch = 65536 ; // invalid { incompatible types: possible lossy conversion from int to char }

 We can represent char literal as in UNICODE representation which is nothing but

‘\uxxxx’

4- digit hexadecimal number


Example:
Char ch = ‘\u0061’;
Sopln(ch) =a

 Every escape character is a valid char literal.

Example:
char ch = ‘\n’ ; // valid
char ch = ‘\t’ ; // valid
char ch = ‘\m’ ; // invalid {ce:
ce: illegal escape character }

 In java 8 escape characters is there.


 String literal: Any sequence of character within double quotes is treated as string literal.

Example :
String s = “Ajay”;

 In java 1.7 version enhancement with respect to literals

 Binary literals: For integral data types until 1.6 version we can specify literal value either in decimal form,
octal form or hexadecimal form. But from 1.7 version onwards we can specify literal value even in binary from
also, allowed digits are 0 and 1.

We can represent Binary Literal by prefixed with 0b or 0B.

Example:

int x = 0b1111 ; or int x = oB1111;

System.out.println(x); // output: 15

 Usage of underscore symbols in numeric literals: From 1.7 version onwards we can use ( _ ) symbol
between digits of numeric literal. The main advantage of this representation is that the readability of the code
will be improved.

Example:

double d = 123456.789;

double d = 1_23_456.7_8_9;

double d = 123_456.7_8_9;

At the time of compilation there underscore symbol will be removed automatically hence after compilation
above line become

double d = 123456.789;

We can use more than one underscore ( _ ) symbols also between the digits. We can use ( _ ) symbol only
between the digits if we are using anywhere else we will get compile time error.

Example :

double d = 1_ _2_ 3_ _4_5_6.7_8_9;

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: 8 byte long value we can assign to 4 byte float variable because both are following different memory
representation internally.

Example :

float f = 10l;

System.out.println(f); // output : 10.0

Byte short

Byte
 Array: An array is an indexed collection of fixed number of homogeneous data elements. The main
values by using single variable, so that readability of the
advantage of array is we can represent huge number of values
code will be improved.

But the main disadvantage of array is fixed in size i.e. once we create an array there is no chance of increase or
decrease the size based on our requirement hence to use arrays concept compulsory we should know the size in
advance, which may not possible always.

int[ ] x = new int [ 10 ]

 Array Declaration:

 One Dimensional Array Declaration:

Example:
int[ ] x; // { This one is recommended because name is clearly separated from type. }
int [ ]x;
int x[ ];

Note: At the time of declaration we can’t specify the size otherwise we will get compile time error.
Example:
int[6] x ; // invalid

int[ ] x ; // valid

 Two Dimensional Array Declaration


eclarations:
Example:

int[ ][ ] x; int[ ] [ ]x ;
int [ ][ ]x ; Valid int[ ] x[ ] ; Valid
int x[ ][ ] ; int []x[];

Note:: If we want to specify dimension before the variable the facility is applicable only for 1st variable in a
compile time error.
declaration, if we trying to apply for remaining variable we will get compile-time
Example: Dimension:
int[ ] a,b; // Valid ( a = 1, b = 1)
int[ ] a[ ], b; // Valid ( a = 2, b = 1)
int[ ] a[ ], b[ ]; // Valid ( a = 2, b = 2)
int[ ] [ ]a, b; // Valid ( a = 2, b = 2)
int[ ] [ ]a, b[ ]; // Valid ( a = 2, b = 3)
int[ ] [ ]a, [ ]b; // Invalid
nvalid (Compile time error)
int[ ] [ ]a ,[ ]b, [ ]c; // Invalid
nvalid (Compile time error)

 Three Dimensional Array Declarations:

int[ ][ ][ ] a; int[ ] [ ]a[ ];

int [ ][ ][ ]a; int[ ][ ] [ ]a;

int a[ ][ ][ ] ; Valid int[ ][ ] a[ ]; Valid

int[ ] [ ][ ]a ; int [ ][ ]a[ ];

int[ ] a[ ][ ] ; int [ ]a[ ][ ];

 Array creation
 One Dimensional Array Creation
reation: 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 classes are part of java language and not
available to the programmer level.
Example:
int[ ] a = new int[3];
System.out.println(a.getclass(
.out.println(a.getclass( ).getN
).getName( )); // output : [I
 Conclusion
 At the time of array creation compulsory we should specify the size otherwise we will get compile time error.

Example:
int[ ] x = new int[ ]; // invalid
int[ ] x = new int[6]; // valid

 It is legal to have an array with size 0 in java.

Example:
int[ ] x = new int[0];

 If we are trying to specify array size with some negative int value then we will get runtime exception saying
NegativeArraySizeException but there is no compile time error.

Example:
int[ ] x = new int[-3]; {re: NegativeArraySizeException}

 To specify array size the allowed data type are byte, short, char, int, if we are trying to specify any other type
then we will 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 = 30;

int[ ] x = new int[s]; // valid

int[ ] x = new int[10L]; // invalid { ce: incompatible types: possible lossy conversion from long to int }

 The maximum allowed array size in java is 2147483647, which is the maximum value of int data type.

Example:

int[ ] x = new int[ 2147483647]; // vaid { re; OutOfMemoryError: Requested array size exceeds VM limit }

int[ ] x = new int[2147483648]; // invalid {ce: integer number too large}

Even in the 1st case we may get runtime exception if sufficient heap memory not available.
 Two dimensional Array creations: In java 2 dimension array not implemented by using matrix style, sum
people followed array of arrays approach for multi-dimensional array creation. The main advantage of this
approach is memory utilization will be improved.

 Memory structure and corresponding java code-

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

Example 2: X[1]

int[ ][ ][ ] x = new int[2][ ][ ];

x[0] = new int[3][ ]; X

x[0][0] = new int[1];

x[0][1] = new int[2];


X[0] X[1]
x[0][2] = new int[3];

x[1] = new int[2][2];

 Which of the following array declaration are valid:



int[ ] a = new int[ ]; // invalid
int[ ] a = new int[3]; // valid
int [ ][ ] a = new int[ ][ ]; // invalid
int [ ][ ] a = new int[3][ ]; // valid
int [ ][ ] a = new int[ ][4]; // invalid
int [ ][ ] a = new int[3][4]; // valid
int [ ][ ][ ] a = new int[3][4][5]; // valid
int [ ][ ][ ] a = new int[3][4][ ]; // valid
int [ ][ ][ ] a = new int[3][ ][5]; // invalid
int [ ][ ][ ] a = new int[ ][4][5]; // invalid
 Array Initialization:

 Once we create an array every element by default initialize with default values.

Example1:

X 0 0 0

Output:

I@1db9742 (This value is not constant its very form system to system , version to
Output: Value of x = [I@1db9742
version ) and x[0] = 0,

toString( ) method will be called,


Note : Whenever we are trying to print any reference variable internally toString(
which is implemented by default to return the string in the following form
class_name@hash_code_in_hexadecimal_form

Example2:

Output:

Example3:

Output:

willl get runtime exception saying Null Pointer


Note: If we are trying to perform any operation on null then we wil
Exception.
 Once we create an array every array element by default initialize with default values, if we are not satisfied with
default values then we can override these values with our customizer values.

Example:

int[ ] x = new int[6];

x[0] =10;

x[1] = 20; X 0 0 0 0 0 0

x[2] = 30; Our Customize


10 20 30 40 50 60
Value
x[3] = 40;

x[4] = 50;

x[5] = 60;

x[6] = 70; // re: ArrayIndexOutOfBoundsException:

x[-6] = 80; // re: ArrayIndexOutOfBoundsException:

x[2.5] = 90; // invalid //ce: incompatible types: possible lossy conversion from double to int

Note: If we are trying to access array element with out of range index (either positive or negative int value) then,
we will get runtime exception saying ArrayIndexOutOfBoundsException.

 Array Declaration, Creation and Initialization in a single line: We can declare, create and initialize an array
in single line (Shortcut representation)

 One Dimensional Array Declaration, Creation and Initialization in a single line

int[ ] x;
x = new int [3]
X 10 20 30
x[0] = 10; int[ ] x = {10, 20, 30};
x[1] = 20;
x[3] = 30;

char[ ] ch = {‘a’, ‘e’, ‘i’, ‘o’, ‘o’}


String[ ] s = {“A”, “Ajay”, “AA”}

 Multi-Dimensional Array Declaration, Creation and Initialization in a single line: We can use this shortcut
for multi-dimensional array also.

Int[ ][ ] x = {{10,20},{30,40,50}}; X

10 20 30 40 50
Example:
Int[ ][ ][ ] x = {{{10,20,30},{40,50.60}},{{70,80},{90,100,110}}};
Sopln(x[0][1][2]); // 60
X
Sopln(x[1][0][1]); // 80
Sopln(x[1][0][0]); // RE
Sopln(x[1][2][0]); // RE
10 20 30 40 50 60 70 80 90 100 110
Sopln(x[1][1][1]); // 100
Sopln(x[2][1][0]); // RE
Note: If we want to use this shortcut compulsory we should perform all activities in single line. If we are trying
to divide into multiple lines we will get compile time error.
int[ ] x = {10, 20, 30};

int[ ] x;
ce: illegal start of expression.
x = {10, 20, 30};

 Length v/s Length ( ): Length is a final variable applicable for arrays, length variable represent the size of the
array.

int[ ] x = new int [6];


Sopln( x.length( )); // ce: Cannot find symbol
Sopln( x.length) // 6

 Length( ) is a final method applicable for string objects, length method return no of characters present in the
strings.
Example:

String s = “Ajay”;
Sopln(s.length) // invalid {cr: cannot find symbol, symbol: variable length , location: variable s of type String}
Sopln(s.length( )) // valid {output: 4}

Note: length variable applicable for arrays but not for string objects, were as length method applicable for string
objects but not for arrays.
Example:
String[ ] s = {“A”, “AA”, “AAA”};

System.out.println(s.length); // valid {Output: 3}


System.out.println(s.length()); // invalid {ce: cannot find symbol }
System.out.println(s[ ].length); // invalid {ce: cannot find symbol }
System.out.println(s[ ].length()); // // valid {Output: 3}
 In Multi-Dimensional arrays length variable represent only base size but not total size:
Example:
int[ ][ ] x = new int[6][3];

System.out.println(x.length); // 6

System.out.println(x[ ].length); // 3

 There is no direct way to find total length of multi dimensional array, but indirectly we can find as fallows...

X[0].length + x[1].length + x[2].length + ……………………

 Anonymous Array: Some time we can declare an array without name such type of nameless array are called
anonymous array.
The main purpose of anonymous arrays is just for instant use (One time usage).

We can create anonymous array as follows ….

new int [ ] {10,20,30,40}; // anonymous int array

new char [ ] { ‘x’, ‘y’, ‘z’}; // anonymous char array

new String [ ] {“Ajay”, “Java”, “Jays”}; // anonymous String array

 While creating anonymous array we can’t specify the size otherwise we will get compile time error.

new int [3] {10,20,30,40}; // invalid

new int [ ] {10,20,30,40}; // valid

 We can multidimensional anonymous array also


new int [ ][ ] {{10,20},{30,40,50}}; // anonymous multidimensional array
 Based on our requirement we can give the name for anonymous array then it’s no longer anonymous.
int[ ] x = new int [ ] {10,20,30,40};
Example:
class Test {
public static void main(String[ ] args)
{
sum(new int[ ] { 1, 2, 3 }); // // anonymous array
}
public static void sum(int[ ] a)
{
int total = 0;
// using for-each loop
for (int i : a)
total = total + i;

System.out.println("The sum is:" + total); // Output : The sum is 6


}
}
NOTE: In the above example just to call sum method we required an array but after implementing sum method,
we are not using array anymore. Hence for this one time requirement anonymous array is the best choice.

 Arrays Element Assignment:

 Case 1: In the case of primitive type arrays as array elements we can provide any type which can be implicitly
promoted to declare type.
Example 1: P fro note
int[ ] x = new int[5];
x[0] = 10;
x[1] = ‘a’;
byte b = 20;
x[2] = b;
short s = 30;
x[3] = 30;
x[3] = s;
x[4] = 10L // {ce: possible loss of precision}

Example 2: In the case of float type array the allowed data type are byte, short, char int, long and float.

 Case 2: In the case of object type arrays as arrays element we can provide either declare type object or its child
class object.
Example1:
Object[ ] a = new Object[10]; Number
a[0] = new object( );
a[1] = new String(“ajay”);
a[2] = new Integer(10); B S I L F D

Example2:
Number[ ] n = new Number [10];
n[0] = new Integer(10);
n[1] = new Double(10.5);
n[2] = new String(“ajay”); // invalid {ce: incompatible types }

 Case 3: For interface type arrays as array elements its implementation class object are allowed.
Example1:
Runnable[ ] r = new Runnable[10];
R[ ] = new Thred( );
R[1] = new String( “ajay”); // invalid {ce: incompatible types }
Array Allowed element Types
Any type which can be implicitly promoted to declared type
Primitive Arrays

Object Type Arrays Either declared type or its child class objects.

Abstract Class Type Arrays Its child class object

Interface type Arrays Its implementation class object are allowed

 Array Variable Assignment:

 Case 1: Element level promotions are not applicable at array level. For example char element can be promoted
to int type where as char arrays can't be promoted to int arrays.
Example:
int[ ] x = {10,20,30,40};
char[ ] ch = {‘a’, ‘b’, ‘c’, ‘d’};
int[ ] b = x; // valid
int[ ] c = ch; // invalid { cr: incompatible types, found: char, required: int[ ] }

 Which of the following promotion will be perform automatically.

char ------------ int // valid


char[ ] ------------ int[ ] // invalid
int ------------ double // invalid
int[ ] ------------ double[ ] // invalid
float ------------ int // invalid
float[ ] ------------ int[ ] // invalid
String ------------ object // valid
String[ ] ------------ oblect[ ] // valid

Note: But in the case of object type arrays child class type array can be promoted to parent class type array.
Example:
String[ ] s = {“A”, “B”, “C” };
Object[ ] a = s;
This is the flexibility we have in the case of object type arrays.
 Case 2: whenever we are assigning one array to another array eternal element won’t be copy just reference
variable will be reassigned.
Example:
int[ ] a = {10,20,30,40,50,60};
int[ ] b = {70,80};
1. a = b // valid
2. b = a // valid
 Case 3: Whenever we are assigning one array to another array dimension must be match for example in the place
of one dimensional int array we should provide one dimensional array only. If we are trying to provide any other
dimension then we will get compile time error.
Example:
int[ ] a = new int[3][ ];
a[0] = new int[4][3]; // invalid { }
a[0] = 10; // invalid { }
a[0] = new int[2]; // valid

Note: Whenever we are assigning one array to another array both dimension and type must be match but sizes
are not required to match.
Example 1-3 are given below
 Variable: Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.

 Java Variables: A variable is a container which holds the value while the java program is executed. A variable
is assigned with a data type.

 Types of variables in java: Variables are divided into 2 divisions in java based on values and position
declaration or behaviour.

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

a) Primitive variables: Can be used to represent primitive values.

Example:

int x = 10;

b) Reference variables: Can be used to refer objects.

Example:

student s = new student( );

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

a) Instance variables

b) Static variables

c) Local variables

 Instance variables: If the value of variable is varied from object to object such type of variable are called
instance variable.

For example if we will create a student class then every student have different name or roll number hence every
instance of student class must have separate copy of name and roll number variables so we need to declare
these variables as instance variables.

class Student

int roll;

String Name;

}
 For every
very object a separate copy of instance variable will be created.

Suppose we are creating 100 instance of Student class then 100 separate copy of instance variables are created
at the same type for each instance.

 Instance variable should be declared within the class directly but outside of any method, block, or constructor.
If it declare inside any method, block, or constructor then it treated as local variable.

 Instance variables will be created at the time of object creation and destroyed at the time
tim of object destruction
hence the scope of instance variables is exactly same as the scope of object.

 Instance variables will be stored in the heap memory as the 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 variable directly from instance area.

Example:
 For instance variables JVM (Java Virtual Machine) will always provide default
default values and we are not required
to perform initialization explicitly.
Example:

 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 then it is not recommended to
declare variable as instance variable, we have to declare such type of variables as class level by using static
modifier.

Example:

class student

String name; // instance variable

int roll; // instance variable

static collageName; // static variable

In this example collegeName is same for all instance of student class and it is sharable by all objects of student
class.
 In the case of instance variables for every
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.

 Static variable should be declared within the class directly but outside of any method, block or constructor.

 Static variables will be created at the time of class loading and destroyed at the time of class unloading hence
scope of static variable is exactly same as scope of (.) class file (dot class file).

ment on command prompt the following work done internally


Java Test (After execute this statement internally.)

1. Start JVM

2. Create & start main Thread

3. Locate Test.class file

4. Load Test.class Static variable creation

5. Execute main( ) method

6. Unload Test.class Static variable destruction


7. Terminate main Thread

8. Shut down JVM

 Static variables will be stored in method area.

 We can access static variables either by object reference or by class name but recommended to use class name.
Within the same class it is not required to use class name and we can access directly.
 We can access static variables directly from both instance and static areas.
Example:

 For static variables JVM will provide default values and we are not required to perform initialization explicitly.
Example:

 Static variables also known as class level variables or fields.


 Local variables: Sometimes to meet temporary requirement of the programmer we can declare variables inside
a method, block or constructor
ructor such type of variables are called local variables or temporary variables or stack
variables or automatic variables.

 Local variable will be stored inside stack memory.


 Local variable will be created while executing the block in which we declared it. Once block execution
utomatically local variable will be destroyed hence the scope of local variable is the block in which
completed automatically
we declared it.
Example:

Example 2: From Pic

 For local variables JVM won’t provide default values compulsory we should perform initialization explicitly
before using that variable and if we are not using then it is not required to perform initialization.
Example 1:
Example 2:

Example 3:

Example 4:

Output:
Note:

(i) 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 runtime.

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

 Thee only applicable modifier for local variable is final by mistake if we are trying to apply any other modifier
then we will get compile time error.

Example:

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:

 For instance and static variables JVM will provide default values and we are not required to perform
provide default values compulsory we should
initialization explicitly but for local variables JVM won’t provide
perform initialization explicitly before using that variable.

 Instance and static variables can be accessed by multiple threads simultaneously and hence these are not thread
for every thread a separate copy will be created and hence local variables
safe but in the case of local variable for
are thread safe.
 Every variable in java should be either instance, static or local.

 Every variable in java should be either primitive or reference hence various possible
possibl combinations of variables
in java are:

Example:

 Uninitialized Array

Note:: Once we create an array every array element by default initialized with default values irrespective of
whether it is static, local or instance array.
 var-arg method in java(Variable Number of Argument Method): Until 1.4 version
versi we can’t declare a
method with
ith variable number of argument, if there is a change in number of argument compuls
compulsory we should
go for new method. Itt increases length of the code and reduces readability to overcome this problem sun people
arg methods in 1.5 version according to this we can declare a method which can take variable
introduce var-arg
number of arguments such type of methods are called var - arg methods.

Example:

(i) void sum(int num1, int num2); //we can only do sum 2 numbers

(ii) void sum(int num1, int num2, in


int num3); // we can only do sum 3 numbers

We can call function first only when we add two numbers if we want to add more than two numbers then we
create a new function like second one for 3 numbers sum. So, for different numbers of arguments we always
var arg methods from 1.5 version onwards.
create a new function this problem can we solve by using var-arg

 We can declare a var-arg


arg method as follows :

m1( int… x )

 We can call this method by passing an number.


any number of int values including 0 number
Example1:
m1 ( ); // valid
m1 (10); // valid
m1 (10, 20); // valid
m1 (10, 20, 30, 40); // valid
Example2:

Output:
 Internally var-arg parameter will be converted into one dimensional array hence within the var-arg method we
can differentiate values by using index.
Example:

Output:

 Which of the following are valid ver-arg method declaration


m1(int… x)
m1(int …x) valid
m1(int…x)

m1(int x…)
m1(int. ..x) invalid
m1(int .x..)
 Loop holes of var-arg method:

 Case 1: We can mix var-arg


arg parameter with normal parameter.
Example:
m1(int x, int… y)
m1(String s, double… y)

 Case 2: If we mix normal parameter with var–arg


var arg parameter should be last parameter.
method then var–arg

Example:

m1(char ch, String… s) // valid

m1(double… d, String s) // invalid

 Case 3: Inside var-arg var arg parameter and we can’t take more than one var-arg
arg method we can take only one var-arg var
parameter.

Example:
m1(int… x, double… d) // invalid

 Case 4: Inside a class we can’t declare va


var-arg
arg method and corresponding one dimensional array method
simultaneously otherwise we will get compile time error.

Example:

Output:
 Case 5: 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 it is exactly same as default case inside switch.

Example:

Output:

 Equivalence between var-arg parameter and one dimensional array

 Case 1: Where ever 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: Where ever var-arg parameter present we can’t replace with one dimensional array.

Example:

m1( int… x) => m1(int[ ] x) // invalid


Note:

 m1(int… x) : We can call this method by passing a group of int value and x will become one dimensional
array.

 m1(int[ ]… x): We can call this method by passing a group of one dimensional int array and x will become two
dimensional int array.

Output:
 Java main() method: Whether class contains main method or not and whether main method is declared
according to requirement or not, these things won’t be checked by the compiler. At runtime JVM is responsible
to check these things. If JVM unable to find main method then we will get Runtime Exception saying “No such
Method Error: Main”.
Example:

class Test Output:


{ javac Test.java // valid- no compile time error
java Test //Runtime Exception: NoSuchMethod Error : main
}

At runtime J.V.M always searches for the main method with the following prototype/ Syntax of main method

public static void main(String[ ] args)


 public: To call by JVM from any where
 static: Without existing object also JVM has to call this method and main method is not related to any object.
 void: Main method won’t return anything to JVM.
 main: This is the name which is configured inside JVM.
 (String [ ] args): Command line argument.

 The above syntax is very strict and if we perform any change then we will get Run time exception saying
“No such Method Error: Main”
 Even though above syntax is very strict the following changes acceptable.
a) Instead of public static we can take static public that is the order of modifiers is not important.
b) We can declare “String[ ]” in any acceptable form- main(sting[ ] args), main(sting [ ]args) and
main(sting args[ ]).
c) Instead of args we can take any valid java identifiers, i.e- main(String[ ] Ajay).
d) We can replace String[ ] with var-arg parameter, i.e- main(String… args)
e) We can declare main method with the following modifiers also- final, synchronized and strictfp.

 Which of the main( ) method declaration are valid:

public static void main(String args) // invalid

public static void Main(String[] args) // invalid

public void main(String[ ] args) // invalid

public static int main(String[ ] args) // invalid

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


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

public static void main(String… args) // valid

static final synchronized strictfp public void main(String… Ajay) // valid

 Case 1: Overloading of the main method is possible but JVM will always call String [ ] argument main method
only. The other overloaded method we have to call explicitly then it will be executed just a normal method call.

Example:

Output:

 Case 2: Inheritance concept is applicable for the main method. Hence while executing child class if child does
not contain main method then parent class main method will be executed.
Example:
Javac p.java

p.claass c.class

Java p Java c
o/p: Parent Main o/p: Parent Main

Output:
 Case 3: It seems overriding concept applicable for main method but it is not overriding and It is method hiding.
Example:

Javac p.java

p.claass c.class

Java p Java c
o/p: Parent Main o/p: Child Main

Output:

Note: For main method inheritance and overloading concepts are applicable but overriding concept is not
applicable instead of overriding method hiding concept is applicable.

 In java 1.7 version enhancement with respect to main method:

 Until 1.6 version if the class doesn’t contain main method then we will get Runtime Exception saying “No such
Method Error: Main”.
But from 1.7 version onward instead of “No such Method Error: Main” we will get more elaborated error
information.
Example:
class Test
{

}
 From 1.7 version onward main method is mandatory to start program execution hence even do class contain
static block it won’t be executed if the class doesn’t contain main method.
Example:

Output:
In 1.6 version: Static Block
In 1.7 version onward:

Example:

Output:
Flow of version 1.6 and 1.7

Note: Without writing main method is it possible print some statement to the console- yes by using static
block but this rule is applicable until 1.6 version but from 1.7 version onward its impossible to print some
statement to console without writing main method.
 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 method.
Example:
Java Test A B C

args[0]
args[1]
args[2]
args.length = 3
The main objective of command line argument is we can customize behaviour of the main method.
Note: Why command line argument is always string form: String is most commonly use type recommended to
keeps as arguments from and string to any other type we can able to convert so sun people give the priority to
string type.
Case 1:

If we replace ≤ with < then we won’t


get aay runtime exception.

Output:

Java Test A B
A
B
R.E: ArrayIndexOutOfBoundsException

Java Test
R.E: ArrayIndexOutOfBoundsException
Case 2:

args A B C

argh X Y Z

Output:

Case 3: Within main method command line arguments are available in string foam.

Output:
Case 4: Usually space itself is the separator between command line arguments, if our command line arguments
itself contain space then we have to enclose that command line argument within double quotes.
Example:

Output:
 Java Coding Standards: Whenever
ver we are writing java code it is highly recommended to flow coding
s. Whenever we are writing any component its name should reflect the purpose of that component
standards.
(functionality). The advantage of this approach is readability and maintainability of the code will be improved.
Example:

 Coding Standards for Classes: Usually class name are nouns


nouns should starts with uppercase character and if it
contains multiple words every inner word should start with uppercase character.
Example:
String, StringBuffer, Acoount, Dog……

 Coding Standards for Interface Name: Usually Interface name adjectivess should starts with uppercase
character and if it contain multiple words every inner word should start with uppercase character.
Example:
Runnable, Serializable,, Comparable….

 Coding Standards for Method: Usually method name are either verb or verb-noun
noun combination. S
Should starts
with lowercase alphabet symbol and if it contains multiple words then every inner word should start with
uppercase character (Camel Case Convention)
Convention).
Example:
print( ), sleep( ), run( ), eat( ), start( ), getName( ), setSalary( )….

 Coding Standards for Variable: Usually variable names are noun. Should starts with lowercase alphabet
start with uppercase character (Camel
symbol and if it contains multiple words then every inner word should start
Case Convention).
Example:
Name, age, salary, mobilNumber….

 Coding Standards for Constant: Usually variable names are noun. Should contain only uppercase character
and if it contains multiple words then these words are separate with underscore symbol.
Example:
MAX_VALUE, MA_ PRIORITY, NORM_PRIORITY,
NORM MIN_PRIORITY,PI…..PI…..

Note: Usually we can declare constant with “public static final” modifiers
 Java Bean Coding Standards: A java bean is a simple java class with private property and public getter and
setter method.
Example:
Class name ends with ‘Bean’ is not official convention
from sun

 Syntax for Setter Method:


a) It’s should we public method.
b) The return type should be void.
c) Method name should be prefix with set.
d) It’s should take sum argument that is it should not be no argument method.

 Syntax for Setter Method:


a) It’s should be public method.
b) The return type should not be void.
c) Method name should prefix with get.
d) It’s should not take any argument.
Note: For Boolean property getter method name van be prefix with either get or is but recommended to use is.

Both are valid but recommended to use is

 Coding Standards for Listeners:


Case 1: To register a listener method name should be prefix with add.
Example:
public void addMyActionListerner(MyActionListerner l) // Valid

public void registerMyActionListerner(MyActionListerner l) // Invalid

public void addMyActionListerner(ActionListerner l) // Invalid


Case 2: To unregister Listeners: Method name should be prefix with remove.
Example:
public void removeMyActionListerner(MyActionListerner l) // Valid

public void unregisterMyActionListerner(MyActionListerner l) // Invalid

public void removeMyActionListerner(ActionListerner l) // Invalid

public void deleteMyActionListerner(MyActionListerner l) // Invalid

Potrebbero piacerti anche