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

Java Note

In Java, identifiers must follow specific rules. They can include letters, numbers, and other characters but not special characters or spaces. Identifiers cannot be reserved keywords. There are also recommendations on length and avoiding predefined class names to reduce confusion. The document provides examples and lists the valid and invalid identifier rules.

Uploaded by

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

Java Note

In Java, identifiers must follow specific rules. They can include letters, numbers, and other characters but not special characters or spaces. Identifiers cannot be reserved keywords. There are also recommendations on length and avoiding predefined class names to reduce confusion. The document provides examples and lists the valid and invalid identifier rules.

Uploaded by

Ujjal Mandal
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 25

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

In a Java program, an identifier is a name used for identification purposes. It can


represent various entities such as class names, variable names, method names, and
label names.
*/

//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)
*/

// Rules to define java identifiers:

/*
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.

While there is no enforced limit, it is generally considered good practice to keep


identifiers concise and meaningful. Longer identifiers can lead to increased
cognitive load for developers trying to understand the code, especially when
reading it or debugging.

Example:

```java
// Recommended: concise and meaningful
int totalScore;

// Not recommended: excessively long


int thisIsAVeryLongVariableNameThatShouldBeAvoidedForTheSakeOfReadability;
```

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.

*/

/*

In Java, a valid identifier must adhere to the following rules:


1. It must consist of characters [A-Z] or [a-z], numbers [0-9], underscore (_), or
a dollar sign ($).
2. It cannot contain special characters like @, &, *, etc.
3. It cannot contain spaces.
4. It should not start with a number.
5. It should be between 4 and 15 characters in length, although there is no strict
limit.
6. It cannot be a Java reserved keyword or a query language keyword.

Examples of valid identifiers:


- `ujjalMandal`
- `number123`
- `_variable`
- `$totalAmount`

Examples of invalid identifiers:


- `@ujjalMandal` (contains a special character)
- `ujjal Mandal` (contains a space)
- `123ujjalMandalNames can contain letters, digits, underscores, and dollar signs
Names must begin with a letter
Names should start with a lowercase letter, and cannot contain whitespace
Names can also begin with $ and _ (but we will not use it in this tutorial)
Names are case-sensitive ("myVar" and "myvar" are different variables)
Reserved words (like Java keywords, such as int or boolean) cannot be used as names
` (starts with a number)
- `int` (Java reserved keyword)
- `SELECT` (query language keyword)

*/

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------------------------------------------
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
==

In java some identifiers are reserved to associate some functionality or meaning


such
type of reserved identifiers are called reserved words.

Reserved words (53)


-------------------
1.> Keywords(50)
a.> Used Keywords (48)

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.

Here is a list of reserved words in Java:

abstract continue for new switch


assert default if package synchronized
boolean do goto private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
_ (underscore)

Here is a list of reserved words in Java:

Reserved words for data types: (8)


1) byte
2) short
3) int
4) long
5) float
6) double
7) char
8) boolean
Reserved words for flow control:(11)
1) if
2) else
3) switch
4) case
5) default
6) for
7) do
8) while
9) break
10) continue
11) return
Keywords for modifiers:(11)
1) public
2) private
3) protected
4) static
5) final
6) abstract
7) synchronized
8) native
9) strictfp(1.2 version)
10) transient
11) volatile
Keywords for exception handling:(6)
1) try
2) catch
3) finally
4) throw
5) throws
6) assert(1.4 version)
Class related keywords:(6)
1) class
2) package
3) import
4) extends
5) implements
6) interface
Object related keywords:(4)
1) new
2) instanceof
3) super
4) this

Reserved literals:

Void return type keyword:


If a method won't return anything compulsory that method should be declared with
the
void return type in java but it is optional in C++.
1) void
Unused keywords:
goto: Create several problems in old languages and hence it is banned in java.
Const: Use final instead of this.
By mistake if we are using these keywords in our program we will get compile time
error.

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

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)

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 |
| +-----+----+ +-----+----+
+-----------+------------+-------------+
| | | |

+--+---+ +--+---+ +---+---+ +---+---+


| byte | | short| | int | | long |
+------+ +------+ +-------+ +-------+

Here is the corrected diagram with annotations:

```
+--------+--------+
| Data Types |
+--------+--------+
|
+----------------+-----------------+------------------
+-----------------+
|
|
+--------+--------+
+--------+--------+
| Primitive | |
Reference |
| Data Types | |
Data Types |
+--------+--------+
+--------+--------+
|
|
+-----------+------------+
+---------+--------+
| | | |
|
+--+---+ +--+---+ +---+---+ |
|
| NDT | | CD | | BDT | +
Class Types +
+------+ +------+ +-------+ |
Interface |
|
| Array |
|
+------------------+
+

\|/

+-------+-------+---------+----+

| |
+---+---+----+ +---+---+---+
| Integral | | Floating |
+-------+----+ +-------+---+

| |+--------
+------+-------+
| |
|
+ +---+---+--+
+-----+----+
| | float |
| double |
| +-----+----+ +-----+----+
+-----------+------------+-------------+
| | | |

+--+---+ +--+---+ +---+---+ +---+---+


| byte | | short| | int | | long |
+------+ +------+ +-------+ +-------+
```

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.

*/

//Integral data types : (byte , short , int , long )

/*
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);

// Uncommenting the lines below will result in compilation errors

// byte B = -128; // Valid: Assigning the minimum value of byte


// 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
}
}

*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.
*/

/*

Floating Point Data Types: Float and Double

- 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

//boolean b = "True";// error: incompatible types: String cannot be


converted to boolean
System.out.println(b);

//
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.

Here are the details of the `char` data type:

- **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

//1.increment & decrement operators


//2. arithmetic operators
//3. string concatenation operators
//4. Relational operators
//5. Equality operators
//6. instanceof operators
//7. Bitwise operators
//8. Short circuit operators
//9. type cast operators
//10. assignment operator
//11. conditional operator
//12. new operator
//13. [ ] operator
//14. Precedence of java operators
//15. Evaluation order of java operands
//16. new Vs newInstance( )
//17. instanceof Vs isInstance( )
//18. ClassNotFoundException Vs NoClassDefFoundError

//1.increment & decrement


operators

//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 |
*******************************************************************

In these expressions, x is initially set to 10. The values of y are determined by


whether the increment or decrement operator is applied before or after the
variable, affecting the value assigned to y and the final value of x after the
operation.

*/

/*
//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

final int x = 10;


x=11;
//int y = x++;
System.out.println("values of x : "+x);// error: cannot assign a value
to final variable x

*/
/*
int x1 = 10;
x1++;
System.out.println("values of x1 : "+x1);//11

final int x1 = 10;


x1++;
System.out.println("values of x1 : "+x1);// error: cannot assign a
value to final variable x1
}
}
*/

//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
=====

/*

In **Java**, the **increment (++) operator** is a **unary operator** used to


increase the value of a variable by **1**. It operates on a **single operand** and
can be applied to various data types, including integers, floating-point numbers,
and characters. Let's explore the details:

1. **Pre-Increment Operator** (`++x`):


- When the increment operator is used **in front of an operand**, it is called
the **pre-increment operator**.
- Syntax: `++x`
- Effect: It increments the value of the variable `x` by **1** before using it
in an expression.
- Example:
```java
class PreIncrement {
public static void main(String[] args) {
int x = 10;
int y = ++x;
System.out.println("y value is: " + y);
}
}
// Output: y value is: 11
```
- Explanation: In the above example, the initial value of `x` is **10**.
Applying the pre-increment operator to `x` increases its value by **1** (i.e.,
**11**), and that incremented value is assigned to the variable `y`.

2. **Post-Increment Operator** (`x++`):


- When the increment operator is used **after an operand**, it is called the
**post-increment operator**.
- Syntax: `x++`
- Effect: It assigns the current value of the variable `x` to another variable
(e.g., `y`) and then increments `x` by **1**.
- Example:
```java
class PostIncrement {
public static void main(String[] args) {
int x = 10;
int y = x++;
System.out.println("y value is: " + y);
}
}
// Output: y value is: 10
```
- Explanation: In this case, the initial value of `x` is **10**. The post-
increment operator assigns the current value of `x` (which is **10**) to `y`, and
then `x` is incremented by **1**. Hence, when displaying the value of `y`, it shows
**10**.

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)

byte + byte = int


byte + short = int
short + short = int
byte + long = long
short + long = long
short + long = long
long + double = double
float + long = float
char + char = int
char + int = int
char + double = double

System.out.println('a' + 'b'); // output : 195


System.out.println('a' + 1); // output : 98
System.out.println('a' + 1.2); // output : 98.2

*/

/*
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

-->Hence , if infinity is the result we won't get any ArithmeticException in


floating
point arithmetics
Ex :
System.out.println(10/0.0); // output : infinity
System.out.println(-10/0.0); // output : - infinity

-->NaN(Not a Number) in integral arithmetic (byte , short , int , long) there is no


way to represent undefine the results. Hence the result is undefined we will get
ArithmericException in integral arithmetic
System.out.println(0/0); // output RE : ArithmeticException / by zero
But floating point arithmetic (float , double) there is a way to represents
undefined the results .
For the Float , Double classes contains a constant NaN , Hence the result is
undefined we won't get ArithmeticException in floating point arithmetics .
System.out.println(0.0/0.0); // output : NaN
System.out.println(-0.0/0.0); // output : NaN

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

}
}

/*

*/

/*

*/

//3. string concatenation operators


//4. Relational operators
//5. Equality operators
//6. instanceof operators
//7. Bitwise operators
//8. Short circuit operators
//9. type cast operators
//10. assignment operator
//11. conditional operator
//12. new operator
//13. [ ] operator
//14. Precedence of java operators
//15. Evaluation order of java operands
//16. new Vs newInstance( )
//17. instanceof Vs isInstance( )
//18. ClassNotFoundException Vs NoClassDefFoundError

You might also like