Java Note
Java Note
//Identifier :
/*
A name in a Java program is called an identifier, which can be used for
identification purposes. It may represent a class name, variable name, method name,
or label name.
OR
//Example -->
class identifiersNamingRule{
public static void main(String[] args){
int x = 10;
System.out.println("identifiersNamingRule is Class Name");
System.out.println("main--> (main method)");
System.out.println("String--> (Predefined Class name)");
System.out.println("args--> (String variables)");
System.out.println("System--> (Predefined class)");
System.out.println("out -->(Variable name)");
System.out.println("println--> (method)");
System.out.println("x is a variable and 10 is variable value");
}
}
/*
Here -->
identifiersNamingRule-->(Class name)
main--> (main method)
String--> (Predefined Class name)
args--> (String variables)
System--> (Predefined class)
out -->(Variable name)
println--> (method)
x-->(Variable)
*/
/*
Rule 1 :
--------
The only allowed characters in java identifiers are:
1) Letters 'a' to 'z'
2) Letters 'A' to 'Z'
3) Digits '0' to '9'
4) Underscore '_'
5) Dollar sign '$'
If any other character is used, a compile-time error will occur.
Example:
1) total_number - valid
2) Total# - invalid
Rule 2 :
--------
Identifiers are not allowed to starts with digit.
Example:
1) ABC123---------valid
2) 123ABC---------invalid
Rule 3 :
--------
Java identifiers are case-sensitive, as Java itself is a case-sensitive language.
Example:
```java
class Test {
int number = 10;
int Number = 20;
int NUMBER = 20; // We can differentiate with case.
int NuMbEr = 30;
}
```
In the above example, `number`, `Number`, `NUMBER`, and `NuMbEr` are all considered
different identifiers due to their case differences.
Rule 4 :
--------
There is no length limit for java identifiers but it is not recommended to take
more than 15 lengths.
OR
==
In Java, there is no explicit limit on the length of identifiers, meaning you can
theoretically use identifiers of any length. However, it is not recommended to use
excessively long identifiers, as they can make your code harder to read and
maintain.
Example:
```java
// Recommended: concise and meaningful
int totalScore;
In the above example, the first identifier `totalScore` is concise and descriptive,
making it easier to understand its purpose. On the other hand, the second
identifier is excessively long and cumbersome to read. It is better to avoid such
lengthy identifiers in favor of shorter, more meaningful ones.
Rule 5 :
--------
We cannot use reserved words as identifiers in Java. Reserved words are part of the
Java language and have predefined meanings, so they cannot be used for naming
variables, classes, methods, or other identifiers.
Example:
```java
int if = 10; // Invalid
```
In the above example, `if` is a reserved word in Java used for conditional
statements, so it cannot be used as a variable name. Attempting to do so will
result in a compilation error.
Rule 6 :
Rule 7 :
--------
While it is technically legal to use predefined Java class names and interface
names as identifiers, it is not considered good programming practice. Doing so can
lead to confusion and make the code harder to understand, as it may override the
standard meaning of those identifiers.
Example 1:
```java
class Test {
public static void main(String[] args) {
int String = 10;
System.out.println(String);
}
}
```
Output:
```
10
```
Example 2:
```java
class Test {
public static void main(String[] args) {
int Runnable = 10;
System.out.println(Runnable);
}
}
```
Output:
```
10
```
In both examples, the code compiles and executes without error, but it is not
recommended to use `String` or `Runnable` as variable names, as they are predefined
class and interface names in Java. It is better to choose descriptive and
meaningful names for variables that do not conflict with the names of existing
classes or interfaces.
*/
/*
*/
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------------------------------------------
Reserved words:
---------------
Reserved words in Java are predefined keywords that have special meanings and
cannot be used as identifiers. These words are part of the Java language syntax and
are reserved for specific purposes. Attempting to use reserved words as identifiers
will result in a compilation error.
OR
==
b.>Unused keywords(2)
> 1. goto
> 2. cont
2.>Reserved Literals(3)
> 1. true
} (value for boolean data type
> 2. false
> 3. null (default value for object reference)
Note : _ (underscore)
> 1. The keyword _ (underscore) is reserved for possible future
use in parameter declarations.
Reserved literals:
Reserved literals:
1) true values for boolean data type.
2) false
3) null----------------- default value for object reference.
Note : _ (underscore)
> 1. The keyword _ (underscore) is reserved for possible future use in
parameter declarations.
Enum:
This keyword introduced in 1.5v to define a group of named constants
Example:
enum Beer
{
KF, RC, KO, FO;
}
Conclusions :
1. All reserved words in java contain only lowercase alphabet symbols.
2. New keywords in java are:
3. strictfp-----------1.2v
4. assert-------------1.4v
5. enum--------------1.5v
6. In java we have only new keyword but not delete because destruction of useless
objects is the responsibility of Garbage Collection.
7. instanceof but not instanceOf
8. strictfp but not strictFp
9. const but not Constant
10. syncronized but not syncronize
11. extends but not extend
12. implements but not implement
13. import but not imports
14. int but not Int
These reserved words have specific meanings in Java and are used for defining
classes, variables, methods, control flow statements, and other language
constructs. It is important to avoid using these words as identifiers in your Java
programs to prevent compilation errors and maintain code clarity.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------------------------------------------
// Data types:
// ===========
/*
*Every variable has a type, every expression has a type and all types are strictly
define more over every assignment should be checked by the compiler by the type
compatibility hence java language is considered as strongly typed programming
language
*
*OR
*
*In Java, every variable, expression, and data has a specific type, and these types
are strictly defined. This means that each element in a Java program must have a
clearly defined data type, and the compiler checks for type compatibility during
compilation. As a result, Java is considered a strongly typed programming language.
*
*Q.> Java is pure object oriented programming or not?
*
*Java is not considered as pure object oriented programming language because
several oops features (like multiple inheritance, operator overloading) are not
supported by java moreover we are depending on primitive data types which are non
objects.
+--------+--------+
| Data Types |
+--------+--------+
|
+----------------+-----------------+------------------
+-----------------+
|
|
+--------+--------+
+--------+--------+
| Primitive | |
Reference |
| Data Types | |
Data Types |
+--------+--------+
+--------+--------+
|
|
+-----------+------------+
+---------+--------+
| | | |
|
+--+---+ +--+---+ +---+---+ |
|
| NDT | | CD | | BDT | +
Class Types +
+------+ +------+ +-------+ |
Interface |
|
| Array |
|
+------------------+
+
\|/
+-------+-------+---------+----+
| |
+---+---+----+ +---+---+---+
| Integral | | floating |
+-------+----+ +-------+---+
| |+--------
+------+-------+
| |
|
+ +---+---+--+
+-----+----+
| | float |
| double |
| +-----+----+ +-----+----+
+-----------+------------+-------------+
| | | |
```
+--------+--------+
| Data Types |
+--------+--------+
|
+----------------+-----------------+------------------
+-----------------+
|
|
+--------+--------+
+--------+--------+
| Primitive | |
Reference |
| Data Types | |
Data Types |
+--------+--------+
+--------+--------+
|
|
+-----------+------------+
+---------+--------+
| | | |
|
+--+---+ +--+---+ +---+---+ |
|
| NDT | | CD | | BDT | +
Class Types +
+------+ +------+ +-------+ |
Interface |
|
| Array |
|
+------------------+
+
\|/
+-------+-------+---------+----+
| |
+---+---+----+ +---+---+---+
| Integral | | Floating |
+-------+----+ +-------+---+
| |+--------
+------+-------+
| |
|
+ +---+---+--+
+-----+----+
| | float |
| double |
| +-----+----+ +-----+----+
+-----------+------------+-------------+
| | | |
Explanation:
- The diagram shows the hierarchy of data types in Java.
- At the top level, we have "Data Types", which encompasses both primitive and
reference data types.
- Under "Data Types", we have two main branches: "Primitive Data Types" and
"Reference Data Types".
- "Primitive Data Types" further branches into "Numeric Data Type (NDT)",
"Character Data Type (CD)", and "Boolean Data Type (BDT)".
- "NDT" includes integral and floating-point data types.
- "Integral" includes data types byte, short, int, and long, each with its size and
range specified.
- "Floating" includes data types float and double, also with their respective sizes
and ranges.
- "Reference Data Types" includes "Class Types", "Interface", and "Array", which
represent non-primitive data types in Java.
- "Class Types" and "Interface" are subclasses of "Reference Data Types",
representing classes and interfaces defined in Java, respectively.
- "Array" represents arrays, which are collections of elements of a specific data
type.
*/
/*
Byte
=====
*Size: 1byte (8bits)
*Maxvalue: +127
*Minvalue:-128
*Range:-128to 127[-2^7 to 2^7-1]
*
*The byte data type in Java has a size of 1 byte (8 bits), with a maximum value of
+127 and a minimum value of -128. The *range of values that can be represented by a
byte is from -128 to +127.
*
*The most significant bit in a byte acts as the sign bit, where "0" indicates a
positive number and "1" indicates a *negative number. Positive numbers are
represented directly in memory, while negative numbers are represented in 2's
*complement form.
*
*Example:
*
*class dataTypes {
public static void main(String[] args) {
// Print the maximum and minimum values of byte
System.out.println("byte max value : " + Byte.MAX_VALUE);
System.out.println("byte min value : " + Byte.MIN_VALUE);
*The byte data type is best suited for handling data in terms of streams, either
from files or from the network. It *provides a compact representation of data and
is commonly used in situations where memory efficiency is crucial.
*/
/*
//byte test cases
class dataTypes{
public static void main(String[] args){
//byte b=127;//max. value
System.out.println("byte max value : " + Byte.MAX_VALUE);
System.out.println("byte min value :" + Byte.MIN_VALUE);
//byte B=-128;//min. value
//byte x=128; // error: incompatible types: possible lossy conversion
from int to byte
//byte X=12.8; // error: incompatible types: possible lossy conversion
from double to byte
//byte y=true; // error: incompatible types: boolean cannot be
converted to byte
// byte y=True; // error: cannot find symbol symbol: variable
True // location: class dataTypes
byte y="True"; // error: incompatible types: String cannot be
converted to byte// byte y="True";
System.out.println();
System.out.println( );
}
}
*/
/*
Short Data Type:
- Usage: Short is the least commonly used data type in Java.
- Size: 2 bytes
- Range: -32768 to 32767 (-2^15 to 2^15-1)
- Example:
```
short s = 130;
short s = 32768; // C.E: possible loss of precision -->this error before java 1.8
short s = true; // C.E: incompatible types
```
- Short data type is best suited for 16-bit processors like 8086. However, since
these processors are outdated, the corresponding short data type is rarely used in
modern programming.
*/
/*
//short test cases
class dataTypes{
public static void main(String[] args){
//short s=32767; //max. value
//short s=32768; //error: incompatible types: possible
lossy conversion from int to short
//short s=-32768; //O/P --> -32768 //min. value
//short s= 12.3; //error: incompatible types: possible
lossy conversion from double to short
//short s= 12.3f; //error: incompatible types: possible
lossy conversion from float to short
//short s=true; //error: incompatible types:
boolean cannot be converted to short
//short s=True; //error: error: cannot find symbol
symbol: //variable True //location:class dataTypes
short s="True"; // error: incompatible types:
String cannot be converted to short //short s="True";
System.out.println("short max value : "+Short.MAX_VALUE);
System.out.println("short min value :"+Short.MIN_VALUE);
System.out.println(s);
}
}
*/
/*
Int Data Type:
-=-=-=-=-=-=-=-=-=-
- Usage: Int is the most commonly used data type in Java.
- Size: 4 bytes
- Range: -2147483648 to 2147483647 (-2^31 to 2^31-1)
*/
/*
//int test case
class dataTypes{
public static void main(String[] args){
//int i = 2147483647; //int max value
//int i = 2147483648; //error: integer number too large
//int i = -2147483648; //int min value
//int i = 2147483648L; //error: incompatible types: possible
lossy conversion from long to int
//int i = true; //error: incompatible types: boolean
cannot be converted to int
//int i = "True"; //error: incompatible types: String
cannot be converted to int
//int i = True; //error: cannot find symbol//variable
True //location: class dataTypes
//int i = 12.8; //error: incompatible types: possible
lossy conversion from double to int
//int i = 12.8f; //error: incompatible types:
possible lossy conversion from float to int
//System.out.println("i="+i);
System.out.println("max value of int : "+Integer.MAX_VALUE);
System.out.println("min value of int :"+Integer.MIN_VALUE);
}
}
*/
/*
Long Data Type:
-=-=-=-=-=-=-=-=-=-
- Usage: Whenever the int data type is insufficient to hold large values, the long
data type should be used.
- Example: For instance, when dealing with the number of characters present in a
large file, the return type of the length() method is long.
```
long l = f.length(); // 'f' is a file object
```
- Size: 8 bytes
- Range: -2^63 to 2^63-1
- Note: Byte, short, int, and long data types can represent whole numbers. For
representing real numbers, floating-point data types should be used.
*/
/*
//long test case
class dataTypes{
public static void main(String[] args){
//long l = true; //error: incompatible types: boolean
cannot be converted to long
//long l = "true"; //error: incompatible types: String
cannot be converted to long
long l = true; //error: incompatible types: String
cannot be converted to long
System.out.println(l);
System.out.println("max value of long : "+Long.MAX_VALUE);//
9223372036854775807
System.out.println("min value of long :"+Long.MIN_VALUE); // -
9223372036854775808
}
}
*/
/*
- Note:
Byte, short, int, and long data types can represent whole numbers. For representing
real numbers, floating-point data types should be used.
*/
/*
- Float:
- Usage: If we require 5 to 6 decimal places of accuracy, we should use the float
data type.
- Size: 4 bytes
- Range: -3.4e38 to 3.4e38
- Precision: Single precision
- Double:
- Usage: If we require 14 to 15 decimal places of accuracy, we should use the
double data type.
- Size: 8 bytes
- Range: -1.7e308 to 1.7e308
- Precision: Double precision
*/
/*
//floating-point test case
class dataTypes{
public static void main(String[] args){
float f = 123.1234567890f;
double d = 123.1234567890;
System.out.println(f); // O/P---> 123.12346
System.out.println(d); // O/P---> 123.123456789
System.out.println("float max value :"+Float.MAX_VALUE);
System.out.println("float min value :"+Float.MIN_VALUE);
System.out.println("***********************************");
System.out.println("double max value :"+Double.MAX_VALUE);
System.out.println("double min value :"+Double.MIN_VALUE);
}
}
*/
/*
Boolean Data Type:
-=-=-=-=-=-=-=-=-=-
- Size: Not applicable (virtual machine dependent)
- Range: Not applicable, but allowed values are true or false.
*/
/*
//Boolean test case
class dataTypes{
public static void main(String[] args){
//boolean b = True; //error: cannot find symbol
//boolean b = 0; //error: incompatible types: int cannot be converted
to boolean
//boolean b = true;
//boolean b = 1.2; //error: incompatible types: double cannot be
converted to boolean
//boolean b = 1.2f; //error: incompatible types: float cannot be
converted to boolean
//
int x =0;
if(x) // error: incompatible types: int cannot be converted to boolean
{
System.out.println("false");
}
else
{
System.out.println("Hello");
}
}
}
*/
/*
The `char` data type in Java is used to represent Unicode characters. Unlike older
languages like C and C++, where characters are ASCII code based and limited to 256
characters, Java supports Unicode, which allows the representation of characters
from different writing systems around the world.
- **Size:** 2 bytes
- **Range:** 0 to 65535
Example:
```java
char ch1 = 97; // Assigning the Unicode value for character 'a'
char ch2 = 65536; // Compile-time error: possible loss of precision
```
In Java, 2 bytes are used to store `char` data type values to accommodate the
larger range of Unicode characters. Each Unicode character is represented by a
unique integer value within the range of 0 to 65535.
+-----------+---------+-------------+------------------+-------------
+-----------------------------+----------------+
| Data Type | Size | Range |
Corresponding Wrapper Class | Default Value |
+-----------+---------+----------------------------------------------
+-----------------------------+----------------+
| byte | 1 byte | -128 to 127 | Byte
| 0 |
| short | 2 bytes | -32768 to 32767 | Short
| 0 |
| int | 4 bytes | -2147483648 to 2147483647 | Integer
| 0 |
| long | 8 bytes | -9223372036854775808 to 9223372036854775807 | Long
| 0 |
| float | 4 bytes | approximately -3.4e38 to 3.4e38 | Float
| 0.0 |
| double | 8 bytes | approximately -1.7e308 to 1.7e308 | Double
| 0.0 |
| boolean | N/A | true or false | Boolean
| false |
| char | 2 bytes | 0 to 65535 | Character
| '\u0000' |
+-----------+---------+-------------+------------------+-------------
+-----------------------------+----------------+
*/
class dataTypes{
public static void main(String[] args){
//char ch1=1;
//int x = 0xFACE;
//int x = 0xBEER; // error: ';' expected // at R location
//System.out.println(x);
System.out.println("max value of char :"+
(int)Character.MAX_VALUE);
System.out.println("min value of char :"+
(int)Character.MIN_VALUE);
}
}
/*
class Test3{
public static void main(String[] args){
int x = 10;
int y = 01023;
int z=0x1023;
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
}
class Test3{
public static void main(String[] args){
char ch='\u0061';
System.out.println(ch);
}
}
*/
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------------------------------------------
//OPERATORS &
ASSIGNMENTS
//Increment & decrement operators we can apply only for variables but not for
constant values.Other wise we will get compile time error .
/*
class operatorInJava{
public static void main(String[] args){
int x = 10;
int y = x++;//post increment
int y1 = ++x;//pre increment
//System.out.println("values of x : "+x);
System.out.println("values of y : "+y);//10
System.out.println("values of y1 : "+y1);//11
}
}
*/
/*
class operatorInJava{
public static void main(String[] args){
int x = 10;
//int y = x--; //post decriment
int y1 = --x; //pre decriment
//System.out.println("values of x : "+x);//10
//System.out.println("values of y : "+y);//10
System.out.println("values of y1 : "+y1);//9
}
}
*/
/*
The table below illustrates the use of increment and decrement operators:
*******************************************************************
| Expression | Initial value of x | Value of y | Final value of x |
|------------|--------------------|------------|------------------|
| y = ++x | 10 | 11 | 11 |
| y = x++ | 10 | 10 | 11 |
| y = --x | 10 | 9 | 9 |
| y = x-- | 10 | 10 | 9 |
*******************************************************************
*/
/*
//Increment & decrement operators we can apply only for variables but not for
constant values.other wise we will get compile time error .
//e.g-->
class operatorInJava{
public static void main(String[] args){
int x = 10;
int y = 10--;
System.out.println("values of y : "+y);// error: unexpected type
}
}
*/
/*
//We can't perform nesting of increment or decrement operator, other wise we will
get compile time error
class operatorInJava{
public static void main(String[] args){
int x = 10;
int y = ++(++x);//error: unexpected type int y = ++(++x); required:
variable found: value
//^
System.out.println("values of y : "+y);
}
}
*/
/*
//For the final variables we can't apply increment or decrement operators ,other
wise we will get compile time error
class operatorInJava{
public static void main(String[] args){
/*
int x = 10;
x=11;
//int y = x++;
System.out.println("values of x : "+x);//11
*/
/*
int x1 = 10;
x1++;
System.out.println("values of x1 : "+x1);//11
//We can apply increment or decrement operators even for primitive data types
except boolean .
/*
class operatorInJava{
public static void main(String[] args){
int x = 10;x++;
System.out.println("value of x :"+x);//11
char ch = 'a';ch++;
char ch1 = 'A';ch1++;
System.out.println("value of ch :"+ch);//b
System.out.println("value of ch1 :"+ch1);//B
double d = 10.5;d++;
System.out.println("value of d :"+d);//11.5
//boolean b = true;b++;
//System.out.println(b);//error: bad operand type boolean for unary
operator '++' boolean b = true;b++;
//^
}
}
*/
/*
//Difference between b++ and b = b+1?
//Note:If we are applying any arithmetic operators b/w 2 operands 'a' & 'b' the
result type is max(int , type of a , type of b)
//byte a = 10;
//byte b = 20;
//byte c = a+b;
//System.out.println(c);// error: incompatible types: possible lossy conversion
from int to byte byte c = a+d;
class operatorInJava{
public static void main(String[] args){
byte b = 10;
b=b+1;
//b=(byte)(b+1);//if we will typecast the it will not show any error
System.out.println(b);// error: incompatible types: possible lossy
conversion from int to byte
//System.out.println(b);// 11 (After type cast output)
//byte b1 = 10;
//b1++;
//System.out.println(b1);//11
//byte a = 10;
//byte d = 20;
//byte c = (byte)(a+d);
//System.out.println(c);// error: incompatible types: possible lossy
conversion from int to byte, byte c = a+d;
}
}
//In the case of Increment & Decrement operators internal type casting will be
performed automatically by the compiler
//b++; => b=(type of b)b+1;
*/
/*
//To avoid above error we can do type casting for a+d then we do not get the error
class operatorInJava{
public static void main(String[] args){
byte b1 = 10;
b1++;
System.out.println(b1);//11
byte a = 10;
byte d = 20;
byte c = (byte)(a+d);
System.out.println(c);//30
}
Note
=====
/*
Remember, the increment operator is a handy tool for loops, counters, and other
situations where you need to modify a variable's value concisely!
*/
*/
//2. arithmetic operators (+,
-, *, /, %)
/*
If we apply any Arithmetic operation b/w 2 variables a & b, the result type is
always max(int , type of a , type of b)
*/
/*
In integral arithmetic (byte , int , short , long) there is no way to represents
infinity , if infinity is the result we will get the ArithmeticException / by zero
System.out.println(10/0); // output RE : ArithmeticException / by zero
But in floating point arithmetic(float , double) there is a way represents
infinity.
System.out.println(10/0.0); // output : infinity
ArithmeticException :
1. It is a RuntimeException but not compile time error
2. It occurs only in integral arithmetic but not in floating point arithmetic.
3. The only operations which cause ArithmeticException are : ' / ' and ' % '
*/
class operatorInJava{
public static void main(String[] args){
System.out.println('a'+'b');//195
System.out.println('a'+0.97);//97.97
System.out.println('a'+1.89);//98.89
System.out.println(0.0/0);//NaN
System.out.println(-10/0.0);//-Infinity
//System.out.println(10/0);//Exception in thread "main"
java.lang.ArithmeticException: / by zero at
operatorInJava.main(operatorInJava.java:215)
//System.out.println(10/0.0);//Infinity
//System.out.println(10/0);//Exception in thread "main"
java.lang.ArithmeticException: / by zero at
operatorInJava.main(operatorInJava.java:217)
//System.out.println(10/0);//Exception in thread "main"
java.lang.ArithmeticException: / by zero at
operatorInJava.main(operatorInJava.java:218)
//for any x value including NaN the following expration return "false"
System.out.println(10 < Float.NaN ); // false
System.out.println(10 <= Float.NaN ); // false
System.out.println(10 > Float.NaN ); // false
System.out.println(10 >= Float.NaN ); // false
System.out.println(10 == Float.NaN ); // false
System.out.println(Float.NaN == Float.NaN ); // false
//for any x value including NaN the following expration return "true"
System.out.println(10 != Float.NaN ); // true
System.out.println(Float.NaN != Float.NaN ); // true
}
}
/*
*/
/*
*/