Java Main Notes Part1
Java Main Notes Part1
What is Java?
● Java is one of the most popular programming languages in the world for building web
applications, mobile apps, enterprise software, and back-end APIs. It has been a popular
choice among developers from the day it was first release with millions of Java
applications in use today.
● Approximately 90% of Fortune 500 companies rely on Java for their technology needs.
Major companies like Twitter, Netflix, Alibaba, Uber, LinkedIn, YouTube, Spotify, and
PayPal utilize Java to power their services. In fact, Java supports over 52% of the
world’s back-end web services.
● According to Oracle, Java runs on around 4 billion mobile phones and over 130 million
TV devices. Given its presence across a wide range of devices—from mobile phones to
spacecraft—demand for skilled Java developers remains high.
History of Java
● Java was created by James Gosling in 1995 at a company called Sun Microsystems.
● The development of Java began as part of a project called the Green Project, led by
James Gosling and a team of engineers at Sun Microsystems. Initially, the goal was to
create a programming language for digital devices like set-top boxes. The language was
originally named Oak, inspired by an oak tree outside Gosling’s office. However, due to
trademark conflicts with other programming languages, the name was later changed to
Java. The new name was inspired by Java coffee, a favorite among the team, known
for its energizing quality, reflecting the language's dynamism and simplicity.
● On May 23, 1995, Sun Microsystems announced Java publicly at the SunWorld
conference, which marked the language's initial release.
● In 2004, Java was the leading programming language globally. That same year, Java
made its way to space! The Spirit Rover, which was part of NASA's Mars Exploration
Rover mission, used Java to help explore the surface of Mars. The rover's onboard
systems ran Java code to control its movements and perform various tasks during its
mission.
● In August 2017, Oracle announced its plan to release new versions of Java every six
months.
Java 23 2024 Finalized Foreign Function & Memory API, Primitive Type
Patterns (preview)
What is LTS?
○ LTS versions are versions of Java that are supported for a longer period (typically
8 years of public support and 5 years of extended support) by Oracle. These
versions receive regular updates, including bug fixes, security patches, and
performance improvements during their support cycle.
○ LTS versions are intended for organizations and enterprises that need stability
and reliability for their production systems. They are often chosen for large-scale
applications where long-term stability is essential.
● Non-LTS:
○ Non-LTS versions of Java are released every six months as part of the regular
Java release cycle. These versions are supported for a shorter period (usually 6
months) and are intended for developers who want to try out the latest features
and improvements.
○ Non-LTS versions are suitable for developers and organizations who are
interested in exploring new features and don’t require long-term support. They
are less stable for large-scale production systems due to their shorter support
lifespans.
Features of Java:
● Example: A USB drive works on both Windows and Mac because it follows a
universal standard, like Java bytecode.
2. Object-Oriented
● Example: A car has properties (color, model) and behaviors (start, stop), similar
to how Java organizes code
4. Simple
5. Robust
● Java handles errors through exceptions and has strong memory management,
reducing crashes.
● Example: Like seat belts in a car, exception handling ensures safety during
unexpected errors.
6. Secure
● Java uses a virtual environment (JVM) and restricts direct memory access,
protecting against viruses.
7. Multithreaded
● Example: A music app can download a song while playing another one.
8. Distributed
● Example: JIT works like a chef preparing food only when ordered, making things
faster and more efficient.
11.Portable - Java programs can run on various devices without modification. - Example:
Like carrying your email account on different devices with the same login credentials.
Categorisation of Java:
Java SE (Standard Edition) Core Java programming for Create desktop apps, console
building standalone programs, and perform basic
applications. operations like file handling,
database connectivity, and
multithreading.
Java EE (Enterprise Edition) Tools for building large-scale, Build enterprise applications
distributed, and secure web like e-commerce systems,
applications. banking software, and web
services using Servlets, JSP,
and EJB
● Java Standard Edition comes in the form of a specification, and the implementation of
this specification is the JDK software, also known as Java SDK (Java Standard
Development Kit).
This JDK software is used for developing and executing Java applications.
1. OpenJDK:
● Other JDK vendors typically base their JDK distributions on OpenJDK, making
necessary changes or improvements while maintaining compatibility with the
TCK (Technology Compatibility Kit), which ensures that the JDK adheres to Java
standards.
● Website: [Link]
● While Oracle JDK was free for personal use and development, starting with Java
11, Oracle began charging for production use of Oracle JDK under a
subscription-based model. It offers paid support, updates, and bug fixes.
● Website: [Link]
● Website: [Link]
● Red Hat provides long-term support for its OpenJDK builds and offers
subscription-based services, including security patches, updates, and
performance enhancements.
Conclusion:
There are several JDK vendors in the Java ecosystem, each providing different levels of
support, performance, and stability. While OpenJDK is the reference implementation, other
vendors like Oracle, Adoptium, Amazon Corretto, Red Hat, and IBM offer customized
distributions to cater to enterprise needs or specific use cases. Developers can choose a vendor
based on their requirements for support, security, and performance.
Installing JDK
● Download JDK: Visit the official Oracle website or Amazon-corretto to download the
latest version of the JDK.
● Install JDK: Follow the installation instructions for your operating system (Windows,
macOS, or Linux).
After installation, verify the proper installation by typing the following command in the terminal:
java -version
javac -version
Note: In the latest versions of JDK, the JAVA_HOME environment variable is typically set
automatically during installation. However, if the JAVA_HOME variable is not set or if the
command does not work after installation, you may need to manually configure the
JAVA_HOME path and add the bin folder location to the system's environment variables.
2. Adding the bin directory inside the JDK folder to the system's PATH environment
variable to allow command-line access to Java tools.
● The JRE is the environment needed to execute Java applications. It includes the
JVM and Java libraries necessary for running Java programs.
● Other Tools: Tools like javadoc (documentation generator) and jdb (Java
debugger).
1. JVM (Java Virtual Machine): Core component that runs Java bytecode.
2. Java Class Libraries: Pre-written classes for tasks like string handling, input/output,
and more. Examples include:
Note: Since Java 9, only the JDK is offered, not the JRE separately. This change reduces the
Java installation size by eliminating duplicate files. If needed, the JRE separately, Organization,
or Developers can build their own custom JRE using the jlink option introduced in Java 9.
Basic Steps To Develop a Java Program:
● In the Compilation phase, The java compiler compiles our code into a different format
called Java bytecode.
● This JRE has a software component called JVM (Java Virtual Machine), which takes
our Java bytecode and translates it to the native code for the underlying OS.
● If we are in the Window Operating-system, this JVM will convert our java byte-code to
the window Operating-system understandable native code, and if we are in the Linux
environment, then this JVM will convert our java byte-code to the Linux OS
understandable native code. With this architecture only, our Java applications are
portable or platform-independent.
We can write a Java program on a Windows machine and execute it in Linux or macOS,
or any other OS that has JRE.
● A method is a block of code that performs a well-defined task. example: a method for
adding 2 numbers, a method for validating user input, a method for calculating interest,
etc.
returnType methodName(){
//method body
}
● Some methods return some value, whereas some methods do not return
any value.
● For the method that does not return any value, we apply void as a return
type.
● void is a reserved keyword in Java; the method name should be proper and
descriptive.
● Example:-
void calculateInterest(){
}
● We can pass some parameters to this method also; we use parameters to pass the
value to our method. For example, amount, rate of interest, duration, etc., and inside the
pair of parentheses { }, we write the actual implementation of Java code.
● Every Java program should have at least one method. And that method is called
the main method.
● Whenever we execute a Java program, the main method gets called, and the code
inside this main method gets executed.
● These methods don't exist as their own; they always belong to a class.
● Every Java program should have at least one class, which contains the main method.
[Link]
javac [Link]
● Here, class is a keyword by which we define a class in Java. We should give a proper
descriptive name to the class.
● An access modifier is a special keyword that determines if other classes and methods in
this program can access these classes and methods.
We have various access modifiers, such as public, private, and so on. Most of the time,
we use the public access modifier.
● So, the basic structure of a Java program contains a class, and inside the class, we have
a main method.
Inside Java programming, we have a concept called a package. We use the package to
group related classes, so as our application grows, we are going to end up with many
classes, so we should properly organize these classes inside different packages.
● By convention, the base package for a Java project is the domain name of your
company in reverse. It does not mean we should have an actual domain registered. This
is just a way to create a namespace for our classes.
Example: [Link];
● So every class we create in our Java application should belong to a package. We are
going to talk about packages in more detail in our upcoming session.
Note: All Java files should have a .java extension. And every statement in the Java application
should be terminated with a semicolon.
● The static is a keyword; we will talk about this keyword later. For now, just remember
that the main method in our program should always be static. The return type of this
method is void, which means this method is not going to return any value.
● In the main method, we have one parameter; we can use this parameter to pass values
to our program. We will talk about this parameter in our upcoming session.
[Link]("Hello World");
● Here, System is a predefined Java class, which belongs to [Link] package. Inside
this class, we have various members, out is a member (field) who belongs to this
System class.
● The type of this out field is the PrintStream class. This PrintStream is another
predefined class in Java. The println method belongs to the PrintStream class.
So here we are calling or executing the println method inside our main method.
● Inside the parentheses of this println method, we can pass any value that we want to
print on the terminal or console.
● Here, “Hello World” is textual data, in Java whenever we deal with textual data, we
should always surround it with double-quotes. which is known as a string.
Inside an IDE software, all the application development environments, like an editor, terminal,
code intelligence, etc., are available in one place. With the help of an IDE software, our
application development speed and productivity will be improved.
There are many IDE software are there like:
IntelliJ IDEA
Eclipse (STS)
NetBeans
Eclipse Installation:
[Link]
● Install Eclipse: Follow the instructions for your operating system to install the Eclipse
IDE for Java Developers. This IDE includes the necessary tools to write, compile, and
run Java programs.
Create and Run Your First Java Program (Hello World) in Eclipse
● Check the option public static void main(String[] args) to add the main method
automatically.
● Click Finish
[Link]
package [Link];
public class Demo{
public static void main(String[] args){
[Link]("Hello World");
}
}
Java has provided the following list of tokens to prepare Java applications.
1. Identifiers
2. Variables
3. Literals
5. Operators
1. Identifiers:
● An identifier is the name used to identify a variable, method, class, interface, or any
other user-defined item in Java.
● Identifiers can contain letters (a-z, A-Z), digits (0-9), the underscore (_), and
the dollar sign ($).
● Identifiers cannot be the same as Java keywords (e.g., int, class, public,
if, etc.).
● Reserved words like true, false, and null also cannot be used as identifiers.
4. Length:
● Identifiers can be of any length, but it's best practice to use meaningful names for
clarity.
● Choose meaningful names that describe the role of the identifier in your program
(e.g., studentName, calculateArea).
● Use camelCase (starting with a lowercase letter) for variable names, method
names, and package names:
● PascalCase (starting with an uppercase letter) is generally used for class and
interface names:
■ Example: Student, ShapeArea.
● Avoid using single letters like x, y, or z unless they represent a commonly known
concept (e.g., mathematical formulas or loop variables).
4. Consistency:
● Valid Identifiers:
○ studentName
○ firstName
○ calculateArea
○ _myVariable
○ $accountBalance
● Invalid Identifiers:
○ 123abc (starts with a digit)
○ class (reserved keyword)
○ public (reserved keyword)
○ @myVariable (contains an invalid character)
○ my-variable (contains a hyphen, which is not allowed)
● The underscore (_) and the dollar sign ($) are allowed in identifiers but are rarely used
in modern Java development.
● Dollar sign ($): Often used in automatically generated names (e.g., for inner
classes).
● Underscore (_): In recent Java versions, the underscore is discouraged for
variable names and class names.
2. Java Variables:
● A variable in Java is a container used to store data values. Before using a variable, you
must declare it, defining both the type and the name. The data type specifies what kind
of data the variable will store (e.g., integer, string, or boolean )
Declaration of Variables:
● dataType: Specifies the type of the data (e.g., int, float, char, String)
● variableName: The name of the variable (e.g., age, height, result)
● value: The initial value of the variable (e.g., 25, 5.6, 700)
Example:
//Here we have declared a variable age and assigned the value 32 in a single
statement. //We can divide it into multiple statements.
int age; //variable declaration
age = 32; //initialization of this variable
Example:
[Link]("Masai");
Here, Masai is the hard-coded value. If we want to print Masai in multiple places, for example,
10 times, and later if we want to change the Masai to MasaiSchool, then we need to change it at
multiple places.
So to solve this, we should follow the coding standards and store this Masai in a variable like
And use this variable name in multiple places instead of the hard-coded value.
[Link](companyName);
3. Literals:
A literal is a constant value that is directly represented in the source code. It represents fixed
values like numbers, characters, or boolean values used in expressions or assignments.
Types of Literals
Example of Literals:
● In Java, a keyword is a reserved word that has a specific meaning and purpose in the
programming language. These keywords cannot be used as identifiers (such as variable
names, method names, or class names) in the code because they are already
predefined with a particular meaning in the Java language. If a keyword is used as an
identifier, it will result in a compilation error. This ensures that the keywords maintain
their intended functionality and are not overwritten or confused with user-defined names.
Example:
Data Types:
● Java is strictly a typed programming language, whereas in Java applications, before
representing data, we have to confirm which type of data we are representing. In this
context, to represent the type of data, we have to use "data types".
1. Primitive Data Types: Basic data types that store values directly.
2. Reference Data Types: These store references (or memory addresses) to objects.
a. Integers:
b. Real-numbers:
c. Characters
1. char (2 bytes or 16 bits) the default value is empty space \u000
d. Boolean
Note: All the decimal point values are, by default, treated as double in Java.
Reference (Non-Primitive) Data Types:
● Non-primitive data types, also known as reference types, are objects that are created
using classes, and they hold references (addresses) to the data rather than the data
itself. They are more complex than primitive types and are used to store large amounts
of data.
● Float can store up to 7 decimal digits, while double can store up to 15 decimal digits.
● By default, any decimal point value is treated as a double. To explicitly specify a value
as a float, you need to postfix it with f or F. Optionally, you can also postfix a decimal
value with D or d to specify it as a double.
● In general, double is the better choice when higher precision, a wider range of values,
and greater accuracy are required.
Experiment:
float x = 5.55f;
double y = 5.55;
[Link](x == y); //
Note: 5.55f will be stored in memory as the nearest representable value, and actually it
will be stored as: 5.55000019073486328125
float f = 5.55f;
[Link](f); // 5.55
[Link]((double) f); // 5.550000190734863
BigDecimal:
● BigDecimal is a Java class used to perform exact and precise decimal calculations.
● [Link]
● Unlike float and double, BigDecimal does NOT use binary floating-point
representation.
Example:
● Banking systems
● Financial calculations
● Currency conversions
[Link]([Link](b)); //0.3
[Link](b); // 13.0
[Link](b); // 8.0
[Link](b); // 26.25
[Link](b); // 4.2
● Starting from Java 7, underscores can be used within numeric literals to improve the
readability of the code. However, the compiler will remove the underscores internally
when processing the value.
By following these rules, you can use underscores effectively to improve the readability of large
numeric values in your code.
● Apart from the Decimal number format, we can also define values in the following
formats by using integer and floating primitive data types.
● A literal can also be expressed in the binary number format. Every integer literal
in binary starts with either 0b or 0B.
[Link](myBinaryNumber);
● Here's an example to illustrate the process to convert the octal number 1101, or
0B1101, into decimal
(1*2^0)+(0x2^1)+(1x2^2) +(1*2^3)
=1+0+4+8 =13
● If a literal starts with a zero and has at least two digits, it is treated as an octal
number. In the following line of code, a decimal value of 25 (031 in octal) is
assigned to the variable myNumber:
● Here's an example to illustrate the process to convert the octal number 346, or
0346, into decimal.
(6x8^0)+(4x8^1)+(3x8^2)
= (61)+(4x8)+(3x64)
= 230
● Every literal in the hexadecimal number format commences with either Ox or OX,
signifying zero followed by an uppercase or lowercase 'X’. These literals must
consist of at least one hexadecimal digit. The hexadecimal number format
employs 16 digits, encompassing 0-9 and A-F (or a-f), with the case of letters A-F
being insignificant.
(3x 16^0)+(10x16^1)+(1*16^2)
=3+(10*16)+(1*256)
= 3+160+265
= 419
3. Boolean type:
● The boolean data type in Java represents two possible values: true or false. These
values are used to represent logical conditions and decisions in programming.
● A boolean variable is typically used in control flow statements (like if, while, for,
etc.) to evaluate a condition. Based on the result of that condition, different code
statements can be executed.
boolean hasChildren; // Represents whether someone has children (true/false)
● The char data type in Java is used to store a single character. The character must be
enclosed in single quotes (e.g., 'M').
● The char type in Java can store values ranging from 0 to 65535. It is a 16-bit Unicode
value that represents a character.
● A char in Java represents a single 16-bit Unicode character, which allows for the
storage of not just standard ASCII characters but also extended characters, including
emojis, international symbols, and more.
○ A - Z (65 - 90)
○ a - z (97 - 122)
Example:
char ch = 'M';
char z = 456; // Valid because the numeric value 456 corresponds to a Unicode character
char c = 65500; // Valid because 65500 is within the Unicode range (0 to 65535)
String text = "I love coding! \u2764"; // Unicode for heart symbol (❤)
[Link](text);
Experiment:
char a = 'M';
char b = 'P';
[Link](a + b); // This will print the sum of the ASCII values of 'M' and 'P'.
\\ - Backslash, Prints \
Example:
[Link]("Name\tAge\tCity");
[Link]("Ravi\t25\tDelhi");
Output:
Ravi 25 Delhi
● Data types help determine the memory size required to store a variable. Each
data type has a predefined memory size, ensuring that the appropriate amount of
memory is allocated for different types of values.
Example:
int i = 10; // The 'int' data type allocates 4 bytes of memory to store the value 10.
● Java is a strongly typed language, meaning variables are strictly associated with
specific data types. This ensures that only compatible values can be assigned to
a variable, reducing the risk of type errors.
Example:
int i = 10;
// i = "Hello"; // Compilation error: incompatible types
● Data types define the valid range of values a variable can hold. For instance, the
byte type can store values from -128 to 127. Assigning a value outside this
range will result in a compilation error.
Example:
byte b = 130; //Invalid assignment, as 'byte' can only store values in the range of
-128 to 127.
● Choosing the appropriate data type can help optimize the memory and
performance of an application. Smaller data types, such as byte or short,
consume less memory and may provide faster processing, especially when
dealing with large datasets.
Example:
byte b = 100; // Uses less memory (1 byte) compared to an 'int' (4 bytes).
Wrapper classes:
● In Java, wrapper classes are classes that provide a way to use primitive data types
(such as int, char, boolean, etc.) as objects. Each of the eight primitive data types in
Java has a corresponding wrapper class in the [Link] package.
● Wrapper classes allow you to treat primitive types as objects, which is useful when
working with Java collections (such as ArrayList) or when needing to pass primitive
data types as objects.
Primitive Data Types Wrapper classes
byte [Link]
short [Link]
int [Link]
long [Link]
float [Link]
double [Link]
char [Link]
boolean [Link]
● Wrapper classes provide several utility methods to perform operations on primitive data
types, such as finding the minimum and maximum values for a particular data type,
among other useful functions.
Example:
[Link]:
package [Link];
public class Main{
public static void main(String[] args){
[Link](Byte.MIN_VALUE+"----->"+Byte.MAX_VALUE);
[Link](Short.MIN_VALUE+"---->"+Short.MAX_VALUE);
[Link](Integer.MIN_VALUE+"----->"+Integer.MAX_VALUE);
[Link](Long.MIN_VALUE+"----->"+Long.MAX_VALUE);
[Link](Float.MIN_VALUE+"----->"+Float.MAX_VALUE);
[Link](Double.MIN_VALUE+"----->"+Double.MAX_VALUE);
//[Link](Character.MIN_VALUE+"----->"+Character.MAX_VALUE); unused charecter
//[Link](Boolean.MIN_VALUE+"----->"+Boolean.MAX_VALUE); Error
[Link]([Link]); //16
[Link]([Link]('M'));
[Link]([Link]('a'));
}
}
● There are many other uses of wrapper classes as well. like Autoboxing, Auto-unboxing,
Parsing a string, etc. We will discuss them in the upcoming sessions.
Example:
int x = 10;
Example:
double a = 9.78;
[Link](b); // Output: 9
● Here, a double is cast to an int, which results in the decimal part being
truncated.
Examples:
1.
float f = 123; //implicit casting
float f2 = (float)12.45;
//or
float f2 = 12.45f;
2.
long longVal = 12345L;
int intVal = (int) longVal; // Explicit casting from long to int
[Link](intVal); // Output: 12345
3.
char charVal = 'A';
int x= charVal; // Casting char to int
[Link](x); // Output: 65 (ASCII value of 'A')
4.
int a = 10;
//byte b = a; //Error
byte b = (byte)a;
[Link](b);
5.
int x = 130;
byte b = (byte)x;
[Link](b); // -126
//Data types range will work like a circle
6.
byte b = 65;
char c = (char) b;
[Link](c); //A
7.
char c = 'a';
byte b = (byte) c;
[Link](b); // 97
● short range is :
● Minimum value = -32,768
● Maximum value = 32,767
Example:
1. Implicit casting can be done when the data type is smaller and is being converted to a
larger type (e.g., int to long or float).
2. Explicit casting is required when a larger data type is being converted to a smaller type
(e.g., double to int ).
3. In Java, we cannot typecast any data type value to any other data type. Typecasting can
only be performed between compatible or equivalent data types. For example, we
cannot typecast a boolean to an int, because these are not compatible types.
Example:
boolean a = true;
● An Operator in Java is like a symbol that carries out a specific action on one, two, or
three operands and generates a result.
Example:
int result = 2 + 3;
● In the above expression, + and = are the operators, and the operands are 2 and 3.
● Variables can also be used in places or literals as an operand.
Example:
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
○ These operators are used to compare two values. They return a boolean result
(true or false).
&&, Logical short-circuit AND: returns true when both conditions are true.
||, Logical short-circuit OR: returns true if at least one condition is true.
|, Logical OR:
<< (Left shift) – Shifts bits left, filling 0s (multiplies by a power of two).
>> (Signed right shift) – Shifts bits right, filling 0s (divides by a power of two), with the
leftmost bit depending on the sign.
>>> (Unsigned right shift) – Shifts bits right, filling 0s, with the leftmost bit always 0.
++, Increments by 1.
--, Decrements by 1.
○ The ternary operator is a shorthand for the if-else statement. It takes three
operands and follows the format:
Note: + Operator in Java is the overloaded operator; if both operands are numbers, then
it will perform addition, whereas if at least one operand is a String, then it will perform the
concatenation.
Example:
[Link](10+10); //20
[Link]("Hello"+10); //Hello10
[Link]("Hello"+10+10);
[Link](10+10+"Hello");
● When performing arithmetic operations between variables of different data types in Java,
type promotion happens automatically to ensure the operation is safe. The result type
is determined by the maximum of the involved data types. The general rule for
determining the result type is:
Example:
byte b2 = 20;
byte x= 10;
byte y = (byte)(x+1);
Example: / division operator
[Link](14/2); //7
[Link](14/3); //4
[Link](14/0); //ArithmaticException
[Link](25.0/2.0); //12.5
[Link](40.5/8); //5.0625
[Link](40.5/8.0); //5.0625
[Link](40.5/0); //Infinity
[Link](-40.5/0); //-Infinity
[Link](0.0/0); //NaN
Task: Using arithmetic operators in Java, write a program that calculates the total cost of items
and applies a discount of 10%.
[Link]:
package [Link];
}
Example: You are organizing a party and need to divide 50 guests into 6 groups. The modulus
operator helps you find how many people will be in the last group (remainder after division).
int groups = 6;
1. Multiplication (*), Division (/), and Remainder (%) have the same level of
precedence and are evaluated first.
2. Addition (+) and Subtraction (-) have the next level of precedence and are evaluated
after multiplication, division, and remainder.
3. The evaluation flow for operators of the same precedence is from left to right.
Example:
int result = 10 + 2 * 5 - 3 / 1 % 2
//10 + 10 - 3 % 2
//10 + 10 - 1
//20-1
//19
//str = str + 9;
str+=9;
[Link](str); //Hello9
byte b = 10;
[Link](b); //30
boolean a= true;
[Link](a == true); //true
Example: Check if a student has scored enough marks to pass the exam (passing marks
50).
[Link](marks >= 50); // Output: false (False means the student has failed the exam)
[Link](!true); //false
boolean a= true;
[Link](!a); //false
boolean isEligible = (age >= 18) || (income > 30000);//At least one condition must be true
int num = 7;
// Output: true (True means the number is not divisible by both 3 and 4)
int x= 10;
//x = x+1;
//x +=1;
++x; //preincrement
[Link](x); //11
Note: This operator will work only on variables, but not on the values.
Example:
int x = 10;
int y = 10;
[Link](x++); //
[Link](++y); //
int a =20;
int b= a++;
[Link](a); //
[Link](b); //
[Link](num1); //
[Link](num2); //
● The ternary operator is a shorthand for if-else statements. It is used to return a value
based on a condition.
int age = 18;
[Link](result);
1. && short-circuit logical AND is used for only boolean values, whereas & logical AND
can be used for boolean as well as for bitwise operations
2. && short-circuit logical AND will evaluate the second expression if the first operand is
true. whereas & logical AND will evaluate both the operands.
Example:
int x = 10;
[Link]("Hello");
else{
[Link]("Hi");
[Link](x);
1.
& Bitwise AND: Compares each bit of two numbers. If both bits are 1, the result is 1;
Otherwise, it is 0.
| Bitwise OR: Compares each bit of two numbers. If either of the bits is 1, the
result is 1.
3.
^ Bitwise XOR: Compares each bit of two numbers. If the bits are different, the
4.
~ Bitwise NOT: Inverts all the bits of the operand. This is also called the 1's
complement
[Link](result); // Output: -6
Rule: ~n = -(n + 1)
5.
<< Left Shift: Shifts the bits of the number to the left, filling with 0s at the right side. This
6.
>> Right Shift(signed): Shifts the bits of the number to the right. This effectively divides
the number by 2 for each shift.
7.
>>> Right Shift(unsigned): The Unsigned Right Shift operator (>>>) shifts the bits of
a number to the right, but always fills the leftmost bits with 0, regardless of the sign.
● For positive numbers, >> and >>> give the same result
● For negative numbers, >>> converts the result into a large positive number.
Example:
int x = -10;
Here:
MSB = 0
The number will be positive, and it will be a very big number.
2147483643