0% found this document useful (0 votes)
16 views

Java Notes

Uploaded by

555bsyadav555
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java Notes

Uploaded by

555bsyadav555
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

1.

Identifiers:
Identifier is a name assigned to the programming elements like variables, methods,
classes, abstract classes, interfaces,.....
EX:
int a=10;
int ---> Data Types
a ---> Variable [Identifier]
= ---> Operator
10 ---> Constant
; ---> Terminator (Special Symbol)

To provide identifiers in java programming, we have to use the following rules and
regulations:
i. The only allowed characters in java identifiers are:
1) a to z
2) A to Z
3) 0 to 9
4) _
5) $
Ex.:-
int eno=111; // Valid
int 9eno=999; // Invalid
String _eaddr="Jai"; // Valid
float $esal=50000.0f; // valid
String emp9No="E-9999"; // Valid
String emp_Name="Dinesh"; // Valid
float emp$Sal=50000.0f; // Valid

ii. Identifiers do not allow all operators and all special symbols except '_'
and '$' symbols.
Ex.:-
int empNo=111; // valid
int emp+No=111; // Invalid
String emp*Name="Dinesh"; // Invalid
String #eaddr="Jai"; // Invalid
String emp@Jai="Dinesh"; // Invalid
float emp.Sal=50000.0f; // Invalid
String emp-Addr="Jai"; // Invalid
String emp_Addr="Jai"; // Valid
iii. java identifiers are case sensitive up course java language itself treated
as case sensitive language.
Ex.:-
class Test{
int number=10;
int Number=20;
int NUMBER=20; // We can differentiate with case.
int NuMbEr=30;
}
iv. We can’t use reserved words as identifiers.
Ex.:-
int if=10; // invalid
v. Identifiers do not allow spaces in the middle.
Ex.:-
concat() // Valid
forName() // Valid
for Name() // Invalid
getInputStream() // valid
get Input Stream() // Invalid
vi. Identifiers should not be duplicated with in the same scope, identifiers may
be duplicated in two different scopes.
Ex.:-
class A {
int i=10; // Class level
short i=20; // Error
double f=33.33; // No Error
void m1() {
float f=22.22f; // local variable
double f=33.33; // Error
long i=30; // No Error
}
}

vii. identifiers are not allowed to starts with digit.


Example:
int ABC123 = 10; // valid
int 123ABC = 30; // invalid

viii. In java applications, we can use all predefined class names and interface
names as identifiers.
EX1:
int Exception=10;
System.out.println(Exception);
Status: No Compilation Error
Output: 10

EX2:
String String="String";
System.out.println(String);
Status: No Compilation Error
Output: String

EX3:
int System=10;
System.out.println(System);
Status: Compilation Error

Reason: Once if we declare "System" [Class Name] as an integer variable then we


must use that "System" name as integer variable only in the remaining program, in
the remaining program if we use "System" as class name then compiler will rise an
error. In the above context, if we want to use "System" as class name then we have
to use its fully qualified.

Note: Specifying class names and interface names along with package names is
called as Fully Qualified Name.

EX:
java.io.BufferedReader
java.util.ArrayList

EX:
int System=10;
java.lang.System.out.println(System);
System=System+10;
java.lang.System.out.println(System);
System=System+10;
java.lang.System.out.println(System);
Status: No Compilation Error
Output: 10
20
30

ix. Along with the above rules and regulations, JAVA has provided a set of
suggestions to use identifiers in java programs. In java applications, it is
recommended to provide identifiers with a particular meaning.
EX:
String xxx="abc123"; // Not Recommended
String accNo="abc123"; // Recommended

x. In java applications, we don’t have any restrictions over the length of the
identifiers, we can declare identifiers with any length, but it is
Recommended to provide length of the identifiers around 10 symbols.

EX:
String permanentemployeeaddress="Jai"; // Not Recommended
String permEmpAddr="Jai"; // Recommended

xi. If we have multiple words with in a single identifier then it is Recommended


to separate multiple words with special notations like '_' symbols.

EX:
String permEmpAddr="Jai"; // Not Recommended
String perm_Emp_Addr="Jai"; // Recommended

Which of the following are valid java identifiers?


2. Keywords / Reserved Words:-
➢ In java, some words are reserved to represent some meaning and
functionality, such type of words is called reserved words.
➢ In java, we have 53 reserved words.
➢ Among 53 keywords, we have 50 keywords and 3 literals.
➢ Among 50 keywords we have 48 used keywords and 2 unused keywords.

i. Keywords for data Types (Total: 8):-


byte, short, int, long, float, double, Boolean, char
ii. Keywords for flow control (Total: 11):-
if, else, switch, case, default, while, do, for, break, continue,
return
iii. Keywords for modifiers (Total: 11):-
public, private, protected, static, final, abstract, synchronized,
native, strictfp (JDK 1.2), transient, volatile
iv. Keywords for exception handling (Total: 6):-
try, catch, finally, throw, throws, assert (JDK 1.4)
v. Class related keywords (Total: 6):-
class, interface, extends, implements, package, import
vi. Object related keywords(Total: 4):-
new, instanceof, super, this
vii. void return type keywords(Total: 1):-
void
➢ In java, return type is mandatory. If a method would not return anything
than we have to declare that method with void return type.
➢ But in C language, return type is optional and default return type is integer.
viii. Unused Keywords (Total: 2):-
goto, const
I. goto:- Usage of goto created several problems in old languages
and hence goto keyword is banned in java.
II. const:- use of final instead of const.
Note:- goto and const are unused keywords and if try to use, we will get compile
time error.
ix. Keywords for reserved literals (Total: 3):-
true, false : (Used for Boolean data types)
➢ null: null is default for object reference.
x. enum Keyword (Total: 1):-
enum (JDK 1.5)
➢ We can use enum to define a group of named constants.
Ex.:-
enum month{Jan, Feb, Mar……}
Which of the following list contains only java reserved words?
1) final, finally, finalize (invalid)//here finalize is a method in Object class.
2) throw, throws, thrown(invalid)//thrown is not available in java
3) break, continue, return, exit(invalid)//exit is not reserved keyword
4) goto, constant(invalid)//here constant is not reserved keyword
5) byte, short, Integer, long(invalid)//here Integer is a wrapper class
6) extends, implements, imports(invalid)//imports keyword is not available
in java
7) finalize, synchronized(invalid)//finalize is a method in Object class
8) instanceof, sizeOf(invalid)//sizeOf is not reserved keyword
9) new, delete(invalid)//delete is not a keyword
10) None of the above(valid)
Which of the following are valid java keywords?
1) public(valid)
2) static(valid)
3) void(valid)
4) main(invalid)
5) String(invalid)
6) args(invalid)

3. Data Types:-
➢ Every variable has a type; every expression has a type and all types are strictly
defined more over every assignment should be checked by the compiler by
the type compatibility hence java language is considered as strongly typed
language.
Ex.:-
i = 10; > invalid, no data type representation.
int i=10;--> Valid, data type is represented.
➢ Because of above reasons we can conclude java language is strongly/ Strictly
typed programming language.
➢ In java applications, data types are able to provide the following advantages:
i. We are able to identify memory sizes to store data.
EX:-
int i=10; // int will be provided 4 bytes of memory.
ii. We are able to identify range values to the variable to assign.
EX:-
byte b=130; > Invalid
byte b=125; > Valid
Reason: 'byte' data type is providing a particular range for its variables like -128 to
127, in this range only we have to assign values to byte variables.
FAQ: 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.
➢ To prepare java applications, JAVA has provided the following data types.

Primitive Data Types / Primary Data types Numeric Data Types:


1) Integral data types: -

Sr. No. Data Size Range Default Wrapper


Type (Byte) Value Class

1. byte 1 -128 to 127 0 Byte


2. short 2 -32768 to 0 Short
32767

3. int 4 -2147483648 0 Integer


to 2147483647

4. long 8 -263 to 263-1 0 Long

Note:- default data type of all integral constants is integer.


2) Non-Integral Data Types: -

Sr. Data Type Size Range Default Wrapper


No. (Byte) Value Class

1. float 4 -1.7e38 to 1.7e38 0.0 Float

2. double 8 -3.4e308 to 3.4e308 0.0 Double

➢ float data type can hold 5 to 6 digits after point(.) while double data type
can hold 14 to 15 digits after point (.).
➢ float data type supports single precision while double data type supports
double precision. Here precision indicates accuracy.
3) Non-Numeric Data types: -

Sr. Data Size Range Default Wrapper


No. Type (Byte) Value Class

1. Char 2 0 to 65535 ‘ ‘ (Space Character


Character)

2. boolean 1 (Bit) True or false false Boolean


➢ Except Boolean and char data types, remaining data types are considered
as signed data types, because we can represent both positive and negative
numbers.
➢ Old languages (C, C++) are ASCII code based and the number of allowed
different ASCII code characters are less than or equal to 256.
➢ To represent these 256 characters, 8 bits are enough hence the size of char
in old languages 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, so we should
go for 16 bits hence the size char in java is 2 bytes.
Ex.:- boolean data type: -
int x = 0;
if(x){
System.out.println(“Hello”);
}
else{
System.out.println(“Hi”);
}
Output: CE: Type mismatch: cannot convert from int to
boolean

If we want to identify range values for variables on the basis of data types then we
have to use the following formula:
-2n-1 to 2n-1 - 1
Here 'n' is no. of bits.
EX:-
Data Type: byte
size= 1 byte = 8 bits.
-28-1` to 28-1-1
-27 to 27 - 1

-128 to 128 – 1
-128 to 127
Note:- This formula is applicable upto Integral data types, not applicable for other
data types.

➢ To identify "min value" and "max value" for each and every data type, JAVA
has provided the following two constant variables from all the wrapper
classes.
MIN_VALUE and MAX_VALUE

Note:- Classes representation of primitive data types are called as Wrapper Classes
Primitive Data Types Wrapper Classes
byte java.lang.Byte
short java.lang.Short
int java.lang.Integer
long java.lang.Long
float java.lang.Float
double java.lang.Double
char java.lang.Character
boolean java.lang.Boolean

EX:-
class Test{
public static void main(String[] args){
System.out.println(Byte.MIN_VALUE+"----->"+Byte.MAX_VALUE);
System.out.println(Short.MIN_VALUE+"----->"+Short.MAX_VALUE);
System.out.println(Integer.MIN_VALUE+"----->"+Integer.MAX_VALUE);
System.out.println(Long.MIN_VALUE+"----->"+Long.MAX_VALUE);
System.out.println(Float.MIN_VALUE+"----->"+Float.MAX_VALUE);
System.out.println(Double.MIN_VALUE+"----->"+Double.MAX_VALUE);
System.out.println(Character.MIN_VALUE+"----->"+Character.MAX_VALUE);
//System.out.println(Boolean.MIN_VALUE+"----->"+Boolean.MAX_VALUE);
}
}

byte:
Size: 1byte (8bits)
Maxvalue: +127
Minvalue:128
Range: -128to 127 [-27 to 27-1]

The most significant bit acts as sign bit. “0” means “+ve” number and “1” means “–
ve” number.
“+ve” numbers will be represented directly in the memory whereas “–ve” numbers
will be represented in 2’s complement form.
Ex:-
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
byte data type is best suitable if we are handling data in terms of streams either
from the file or from the network.

short:
The most rarely used data type in java is short.
Size: 2 bytes
Range: -32768 to 32767 [-215 to 215-1]
Ex.:-
short s=130;
short s=32768;// C.E: possible loss of precision
short s=true;// C.E: incompatible types
Short data type is best suitable for 16-bit processors like 8086 but these processors
are completely outdated and hence the corresponding short data type is also out
data type.

int:
This is most commonly used data type in java.
Size: 4 bytes
Range: -2147483648 to 2147483647 [-231 to 231-1]
Ex.:-
int i=130;
int i=10.5;// C.E: possible loss of precision
int i=true;// C.E: incompatible types

long:
Whenever int is not enough to hold big values then we should go for long data type.
Ex.:-
To hold the no. Of characters present in a big file and int may not enough hence
the return type of length() method is long.
long l=f.length();//f is a file
Size: 8 bytes
Range: -263 to 263-1
Note: All the above data types (byte, short, int and long) can be used to represent
whole numbers. If we want to represent real numbers then we should go for
floating point data types.

Floating Point Data types:


Float double

If we want to 5 to 6 decimal If we want to 14 to 15 decimal places


places of accuracy then we of accuracy then we should go for
should go for float. double.

Size: 4 bytes. Size: 8 bytes.

Range: -3.4e38 to 3.4e38. Range: -1.7e308 to1.7e308.

float follows single precision. double follows double precision.

boolean data type:


Size: Not applicable (virtual machine dependent)
Range: Not applicable but allowed values are true or false.
Which of the following boolean declarations are valid?
Ex. 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
Ex. :-

Char data type:


In java we are allowed to use any worldwide alphabets character and java is
Unicode based to represent all these characters one byte is not enough compulsory
we should go for 2 bytes.
Size: 2 bytes
Range: 0 to 65535 Example:
Ex.:-
char ch1=97;
char ch2=65536;//C.E: possible loss of precision
Non-Primitive / User Defined / Secondary Data types:
➢ No fixed memory allocation for User defined data types like all classes, all
abstract classes, all interfaces, all arrays, etc.
4. Literals:
Literal is a constant assigned to the variables.
EX:
int a=10;
int ---> Data Types
a ---> Variables/ Identifier
= ---> Operator
10 ---> Constant [Literal].
; ---> Special Symbol.
To prepare java programs, JAVA has provided the following set of literals:
i. Integer / Integral Literals:
➢ For integral data types(byte, short, int, long), we can specify literal value
in the following base:-
I. Decimal Form (Base 10):-
❖ Allowed digits are 0-9.
Ex.:-
int x = 10;
II. Octal Form (Base 8):-
❖ Allowed digits are 0-7.
❖ Literal value should be prefixed with 0.
Ex.:-
int x = 010;
III. Hexadecimal Form(Base 16):-
❖ Allowed digits are 0-9, A-F (Both Lower case or Upper case
can be used).
❖ The literal value should be prefixed with 0x or 0X.
Ex.:-
int x = 0x10;
Questions: Find the Valid / Invalid-
int a = 10;// Valid
int a = 0789;// CE: Integer number is too large
int a = 0777;//Valid
int a = 0xFace;// Valid
int a = 0xFava;// CE: ‘;’ expected

There is no direct way to specify byte and short literal explicitly but indirectly we
can specify. Whenever we assign integral literal to the byte variable, and if the value
comes within the range of byte then compiler treats it automatically as byte literal.
Similarly short literal also works.
Ex.:-
byte b = 127;// OK (Range: -128 to 127)
byte b = 128;// CTE: Cannot convert int to byte
short s = 32767;// OK (Range: -32768 to 32767)
short s = 32768;// CTE: Cannot convert int to short
ii. Floating Point Literals:
➢ By default, every floating-point literal is of double type and hence we
cannot assign directly to the float variable.
➢ But we can specify floating point literal as float type by suffixed with f
or F.
Ex.:-
float f = 123.456;// CTE: Cannot convert double to float
float f = 123.456f;//OK
double d = 123.456;//OK
➢ We can specify explicitly floating-point literal as double type by suffixed
with d or D, but this convention is not required. It happens implicitly.
Ex.:-
double d = 12345.6789D;// No need to use D
float f = 12345.1234d;// CTE: Type mismatch: cannot convert from
double to float
➢ We can specify floating point literals only in decimal form and we can’t
specify in octal and hexa-decimal forms.
Ex.:-
double d = 123.456;//OK
double d = 0123.456;//OK (0123.456 will treated as decimal)
double d = 0x123;// OK (Convert it into decimal)
double d = 0x123.456;// CTE: error: malformed floating point literal
➢ We can assign integral literal directly to floating point variables and that
integral literal can be specified either in decimal or octal or hexa-
decimal forms.
Ex.:-
double d = 10;//OK Output: 10.0
double d = 0786;//(CE: Integer Number too Large)
double d = 0786.0;// OK
double d = 0777;// OK (0777 comes under 0-7)
double d = 0xFace;// OK
double d = 0xFace.0;// CE: malformed floating-point literal
➢ We cannot assign floating point literals to integral types.
Ex.:-
double d = 10;//OK
int i = 10.0.;// CE: Possible loss of precision (found: double,
required: int)
➢ We can specify floating point literal even in exponential(exponent)
form.
Ex.:-
double d = 1.2e3;//OK 1.2e3 means 1.2*103
float f = 1.2e3;// CE: Possible loss of precision (found: double,
required: float)
float f = 1.2e3f;//OK
iii. Boolean Literals:
➢ The only allowed values for Boolean data type are true or false.
boolean ---> true, false
Ex.:-
1) boolean b=true;// (valid)
2) boolean b=0;// C.E: incompatible types(invalid)
3) boolean b=True;// C.E: cannot find symbol(invalid)
4) boolean b="true";// C.E: incompatible types(invalid)

iv. Character Literals:-


➢ We can specify char literal as single character within single quotes (‘ ‘).
Ex.:-
char ch = ‘a’;// OK
char ch = a; // CE: cannot find symbol: Variable a, location: class
Test
char ch = “a”;// CE: Incompatible type (found: String, required:
char)
char ch = ‘ab’;// CE-1: Unclosed char literal, CE – 2: Unclosed char
literal, CE – 3: not a statement

➢ We can specify char literal as integral literal which represents Unicode


value of the character and that integral literal can be specified either in
decimal or octal or hexa-decimal forms but allowed range is 0 to 65535.
Ex.:-
char ch = 97;//OK Allowed Range: 0 to 65535
char ch = 0xFace;// OK Valid Hexa-Decimal value
char ch = 0777;// OK Valid Ocatal Value
char ch = 65536;// CE: Possible loss of Precision (found:
Integer, required: char)
➢ We can represent char literal in Unicode representation which is
nothing but ‘\uxxxx’ (4 digit hexa-decimal number).
Ex.:-
char ch = ‘\u0061’;
System.out.println(ch);//a(because decimal of ‘\u0061’ is 97

➢ Every escape character is a valid char literal.


Ex.:-
char ch = ‘\n’;//OK
char ch = ‘\t’;//OK
char ch = ‘\m’;// CE: illegal escape character
Escape character chart:-

Escape Character Description

\n New Line

\t Horizontal Tab

\r Carriage Return

\b Back Space

\f Form Feed

\’ Single Quote Symbol

\” Double Quote Symbol

\\ Back Slash Symbol

Question:- Which of the following are valid?


a. char ch = 65536;//Invalid (Out of Range)
b. char ch = 0xJava; // Invalid (Out of Range)
c. char ch = \uFace; // Invalid (Single Quotes missing)
d. char ch = ‘\uBee’;// Valid
e. char ch = ‘\m’;// Invalid (illegal escape character)
f. char ch = ‘\iFace’;// Invalid ( \u is valid but \i not valid)

v. String Literals:
➢ Any sequence of characters within double quotes is treated as string
literal.
Ex.:-
String s = “Java”;
JDK 1.7 version enhancement with respect two literals:-

vi. Binary Literals:-


➢ For integral data types until 1.6 version, we can specify literal value in
the following ways (Decimal form, Octal form, Hexa-Decimal form). But
from JDK 1.7 version onward we can specify literal value even in binary
form also.
❖ Allowed digits are 0 and 1.
❖ Literal value should be prefixed with 0b or 0B.
Ex.:-
int i = 0B1111;
System.out.println(i);// 15

vii. Usage of underscore symbol (_) in numeric literal:-


➢ Form JDK 1.7 version onwards, we can us underscore symbol (_)
between digits of numeric literal.
Ex.:-
double d = 123456.789;
double d = 1_23_456.7_8_9;// OK, Indian People read this like one
Lakh twenty three thousand four fifty six…..
double d = 123_456.7_8_9;//OK, American People read this one
twenty three thousand four fifty six…..
➢ The main advantage of this approach is readability of the code will be
improved.
➢ At the time of compilation this underscore symbol (_) will be removed
automatically hence after compilation the above line will become: -
Double d = 123456.789;
➢ We can use more than one underscore symbol (_) between digits also.
Ex.:-
double d = 1__23_4_5__6.7_8_9;//OK
double d = 1___23___4_5__6.7_8_9;//OK

➢ We can use underscore symbol only between the digits if we use


anywhere else we will get compile time error.
Ex.:-
double d = _1_23_4_5_6.7_8_9;
double d = 1_23_4_5_6_.7_8_9;
double d = 1_23_4_5_6.7_8_9_;

You might also like