[Go to site: main page, start]

0% found this document useful (0 votes)
14 views56 pages

Comprehensive Java Programming Guide

java_tutorials

Uploaded by

neelkamal72809
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views56 pages

Comprehensive Java Programming Guide

java_tutorials

Uploaded by

neelkamal72809
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

java_tutorials

Java is a class-based, object-oriented programming language that is designed to have as few


implementation dependencies as possible.
It is intended to let application developers Write Once and Run Anywhere (WORA), meaning that
compiled Java code can run on all platforms that support Java without the need for recompilation.
java was developed by James Gosling at Sun Microsystems Inc. in May 1995 and later acquired by
Oracle Corporation and is widely used for developing applications for desktop, web, and mobile
devices.
it was originally called oak by james Gosling.

Key Features of Java

1. Platform Independent :

Compiler converts source code to byte code and then the JVM executes the bytecode generated by the compiler.
This byte code can run on any platform be it Windows, Linux, or macOS which means if we compile a program
on Windows, then we can run it on Linux and vice versa. Each operating system has a different JVM, but the
output produced by all the OS is the same after the execution of the byte code. That is why we call java a
platform-independent language.

2. Object-Oriented Programming :

Java is an object-oriented language, promoting the use of objects and classes. Organizing the program in the
terms of a collection of objects is a way of object-oriented programming, each of which represents an instance of
the class.

The four main concepts of Object-Oriented programming are:

Abstraction
Encapsulation
Inheritance
Polymorphism

3. Simplicity :

Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It eliminates complex
features like pointers and multiple inheritances, making it easier to write, debug, and maintain code.

4. Robustness :

Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort into
checking errors as early as possible, that is why the java compiler is able to detect even those errors that are not
easy to detect by another programming language. The main features of java that make it robust are garbage
collection, exception handling, and memory allocation.

5. Security :

In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it


shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack
corruption or buffer overflow are impossible to exploit in Java. Also, java programs run in an environment that is
independent of the os(operating system) environment which makes java programs more secure.

6. Distributed :

We can create distributed applications using the java programming language. Remote Method Invocation and
Enterprise Java Beans are used for creating distributed applications in java. The java programs can be easily
distributed on one or more systems that are connected to each other through an internet connection.

7. Multithreading :

As we know, java code written on one machine can be run on another machine. The platform-independent
feature of java in which its platform-independent bytecode can be taken to any platform for execution makes
java portable. WORA(Write Once Run Anywhere) makes java application to generates a ‘.class’ file that
corresponds to our applications(program) but contains code in binary format. It provides architecture-neutral
ease, as bytecode is independent of any machine architecture. It is the primary reason java is used in the
enterprising IT industry globally worldwide.
9. High Performance :

Java architecture is defined in such a way that it reduces overhead during the runtime and at some times java
uses Just In Time (JIT) compiler where the compiler compiles code on-demand basis where it only compiles
those methods that are called making applications to execute faster.

How Java Code Executes?

The execution of a Java application code involves three main steps:

1. Creating the Program :

Java programs are written using a text editor or an Integrated Development Environment (IDE) like IntelliJ
IDEA, Eclipse, or NetBeans. The source code is saved with a .java extension.

2. Compiling the Program


The Java compiler (javac) converts the source code into bytecode, which is stored in a .class file. This
bytecode is platform-independent and can be executed on any machine with a JVM.

3. Running the Program

The JVM executes the compiled bytecode, translating it into machine code specific to the operating system and
hardware.

Essential Java Terminologies You Need to Know :


Before learning Java, one must be familiar with these common terms of Java
1. Java Virtual Machine(JVM) :

The JVM is an integral part of the Java platform, responsible for executing Java bytecode. It ensures that the
output of Java programs is consistent across different platforms.

Writing a program is done by a java programmer like you and me.


The compilation is done by the JAVAC compiler which is a primary Java compiler included in the Java
development kit (JDK). It takes the Java program as input and generates bytecode as output.
In the Running phase of a program, JVM executes the bytecode generated by the compiler.

The Java Virtual Machine (JVM) is designed to run the bytecode generated by the Java compiler. Each operating
system has its own version of the JVM, but all JVMs follow the same rules and standards. This means Java
programs can run the same way on any device with a JVM, regardless of the operating system. This is why Java
is called a platform-independent language.

2. Bytecode

Bytecode is the intermediate representation of Java code, generated by the Java compiler. It is platform-
independent and can be executed by the JVM.

3. Java Development Kit(JDK)

While we were using the term JDK when we learn about bytecode and JVM. So, as the name suggests, it is a
complete Java development kit that includes everything including compiler, Java Runtime Environment
(JRE), Java Debuggers, Java Docs, etc. For the program to execute in java, we need to install JDK on our
computer in order to create, compile and run the java program.

4. Java Runtime Environment (JRE)

JDK includes JRE. JRE installation on our computers allows the java program to run, however, we cannot
compile it. JRE includes a browser, JVM, applet support, and plugins. For running the java program, a computer
needs JRE.
5. Garbage Collector

In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has a program
called Garbage Collector. Garbage Collectors can recollect the objects that are not referenced. So Java makes
the life of a programmer easy by handling memory management. However, programmers should be careful
about their code whether they are using objects that have been used for a long time. Because Garbage
cannot recover the memory of objects being referenced.

6. ClassPath

The Classpath is the file path where the java runtime and Java compiler look for .class files to load. By default,
JDK provides many libraries. If you want to include external libraries they should be added to the classpath.

Differences between Java and C++ are as follows:

Sl. No. Parameters Java C++


1. Founder Java was developed by James C++ was developed by Bjarne
Gosling at Sun Microsystems. Stroustrup at Bell Labs in 1979 as an
extension of the C language.
2. First Release On May 23, 1995 In October 1985
3. Stable Release Java SE 18 was released on 22 C++20 released on 15th December
March 2022 2020
4. Official Website [Link]/java [Link]
5. Influenced By: Java was Influenced by Ada 83, C++ was Influenced by Influenced by
Pascal, C++, C#, etc. languages. Ada, ALGOL 68, C, ML, Simula,
Smalltalk, etc. languages.
6. Influenced to: Java was influenced to develop C++ was influenced to develop C99,
BeanShell, C#, Clojure, Groovy, Java, JS++, Lua, Perl, PHP, Python,
Hack, J#, Kotlin, PHP, Python, Rust, Seed7, etc. languages.
Scala, etc. languages.
7. Platform Platform-independent, Java Platform dependent, should be
Dependency bytecode works on any operating compiled for different platforms.
system.
8. Portability It can run on any OS hence it is C++ is platform-dependent. Hence it
portable. is not portable.
9. Compilation Java is both Compiled and C++ is a Compiled Language.
Interpreted Language.
10. Memory Memory Management is System Memory Management in C++ is
Management Controlled. Manual.
Sl. No. Parameters Java C++
11. Virtual Keyword It doesn’t have a Virtual It has Virtual keywords.
Keyword.
12. Multiple Inheritance It supports only single It supports both single and multiple
inheritance. Multiple Inheritance.
inheritances are achieved
partially using interfaces.
13. Overloading It supports only method It supports both method and operator
overloading and doesn’t allow overloading.
operator overloading.
14. Pointers It has limited support for It strongly supports pointers.
pointers.
15. Libraries It doesn’t support direct native It supports direct system library calls,
library calls but only Java Native making it suitable for system-level
Interfaces. programming.
16. Libraries Libraries have a wide range of C++ libraries have comparatively
classes for various high-level low-level functionalities.
services.
17. Documentation It supports documentation It doesn’t support documentation
Comment comments (e.g., /**.. */) for comments for source code.
source code.
18. Thread Support Java provides built-in support
C++ doesn’t have built-in support for
for multithreading. threads, depends on third-party
threading libraries.
19. Type Java is only an object-oriented C++ is both a procedural and an
programming language. object-oriented programming
language.
20. Input-Output Java uses the (System C++ uses cin for input and cout for an
mechanism class): [Link] for input output operation.
and [Link] for output.
21. goto Keyword Java doesn’t support goto C++ supports goto keyword.
Keyword
22. Structures and Java doesn’t support Structures C++ supports Structures and Unions.
Unions and Unions.
23. Parameter Passing Java supports only the Pass by C++ supports both Pass by Value and
Value technique. pass by reference.
24. Inheritance Tree All classes in Java are subclasses A fresh inheritance tree is always
of the Object class, hence Java created in C++.
only ever follows a single
inheritance tree.
25. Global Scope It supports no global scope. It supports both global scope and
namespace scope.
26. Object Management Automatic object management It supports manual object management
with garbage collection. using new and delete.
27. Call by Value and Java supports only call by value. C++ both supports call by value and
Call by reference call by reference.
28. Hardware Java is not so interactive with C++ is nearer to hardware.
hardware.
29. Language Used for Internet and Android games, Game engines, Machine learning,
Mobile applications, Healthcare Operating systems, Google Search
and research computation, Cloud Engine, Web browsers, Virtual Reality
Sl. No. Parameters Java C++
applications, Internet of Things (VR), Game development, Medical
(IoT) devices, etc. technology, Telecommunications,
Databases, etc.
30. Application built Wikipedia, LinkedIn, Android Mozilla Firefox, Amazon, Apple OS,
OS, Uber, and Minecraft, Spotify, Adobe Photoshop, and
Youtube.

Structure of Java Program :

A basic Java program consists of several components that create a functional application. W:e can learn about
basic Java Syntax using the following program:
Terminologies of a Basic Java Program

1. Class Declaration: Every Java program starts with a class declaration using the class keyword. “A class is a
blue print of an object” and we can also define class as a logical template that share common properties and
methods.

2. Object: The object is an instance of a class. It is an entity that has behavior and state.

Example: Dog, Cat, Monkey etc. are the object of “Animal” class.
Behavior: Running on the road.

3. Main Method: The public static void main(String args[]) method is the entry point where the program
starts execution.
4. Statements: Each line of code inside the method must end with a semicolon(;)

Java Syntax Key Elements :

1. Comments in Java :

There are three types of comments in Java.

Single line Comment

// This is a single-line comment

Multi-line Comment

/* This is a multi-line comment */

Documentation Comment

It is also known as doc comment

/** This is a doc comment */


2. Source File Name

Source File Name Rule in Java :

1. When There is a public class in the file


The name of a source file must exactly match the name of the public class name with the extension of . java
Example: Assume you have a public class name GFG.

Note:

GFG. java this is a Valid Syntax


[Link] this is a Invalid Syntax

2. When There is no public class in the file


The source file name can be anything, but it must have the .java extension.

Here, the class in not declared as public so you can make the file name anything
like [Link], [Link] etc

3. Case Sensitivity

Java is a case-sensitive language, which means that the identifiers AB, Ab, aB , and ab are different in Java.

4. Class Names

The first letter of the class should be in Uppercase (lowercase is allowed but discouraged).
If several words are used to form the name of the class, each inner word’s first letter should be in
Uppercase. Underscores are allowed, but not recommended. Also allowed are numbers and currency
symbols, although the latter are also discouraged because they are used for a special purpose (for inner and
anonymous classes).
5. Method Names :

All the method names should start with a lowercase letter (uppercase is also allowed but lowercase is
recommended).
If several words are used to form the name of the method, then each first letter of the inner word should be
in Uppercase. Underscores are allowed, but not recommended. Also allowed are digits and currency
symbols.

6. Identifiers in Java :

Identifiers are the names of local variables, instance and class variables, and labels, but also the names for
classes, packages, modules and methods. All Unicode characters are valid, not just the ASCII subset.
All identifiers can begin with a letter, a currency symbol or an underscore ( _ ). According to the
convention, a letter should be lower case for variables.
The first character of identifiers can be followed by any combination of letters, digits, currency symbols
and the underscore. The underscore is not recommended for the names of variables. Constants (static final
attributes and enums) should be in all Uppercase letters.
Most importantly identifiers are case-sensitive.

A keyword cannot be used as an identifier since it is a reserved word and has some special meaning.
7. White spaces in Java

A line containing only white spaces, possibly with the comment, is known as a blank line, and the Java compiler
totally ignores it.

8. Access Modifiers

These modifiers control the scope of class and methods.

Access Modifiers: default, public, protected, private.


Non-access Modifiers: final, abstract, static, transient, synchronized, volatile, native.

10. Java Keywords

Keywords or Reserved words are the words in a language that are used for some internal process or represent
some predefined actions. These words are therefore not allowed to use as variable names or objects.

abstract assert boolean break


byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while

Java Keywords List & usage:


Keyword Usage
abstract Specifies that a class or method will be implemented later, in a subclass
assert Assert describes a predicate placed in a Java program to indicate that the developer thinks
that the predicate is always true at that place.
boolean A data type that can hold True and False values only
break A control statement for breaking out of loops.
byte A data type that can hold 8-bit data values
case Used in switch statements to mark blocks of text
catch Catches exceptions generated by try statements
char A data type that can hold unsigned 16-bit Unicode characters
class Declares a new class
continue Sends control back outside a loop
default Specifies the default block of code in a switch statement
do Starts a do-while loop
double A data type that can hold 64-bit floating-point numbers
else Indicates alternative branches in an if statement
enum A Java keyword is used to declare an enumerated type. Enumerations extend the base class.
extends Indicates that a class is derived from another class or interface
final Indicates that a variable holds a constant value or that a method will not be overridden
finally Indicates a block of code in a try-catch structure that will always be executed
float A data type that holds a 32-bit floating-point number
for Used to start a for loop
if Tests a true/false expression and branches accordingly
implements Specifies that a class implements an interface
import References other classes
instanceof Indicates whether an object is an instance of a specific class or implements an interface
int A data type that can hold a 32-bit signed integer
interface Declares an interface
long A data type that holds a 64-bit integer
native Specifies that a method is implemented with native (platform-specific) code
new Creates new objects
null This indicates that a reference does not refer to anything
package Declares a Java package
private An access specifier indicating that a method or variable may be accessed only in the class it’s
declared in
protected An access specifier indicating that a method or variable may only be accessed in the class it’s
declared in (or a subclass of the class it’s declared in or other classes in the same package)
public An access specifier used for classes, interfaces, methods, and variables indicating that an
item is accessible throughout the application (or where the class that defines it is accessible)
return Sends control and possibly a return value back from a called method
short A data type that can hold a 16-bit integer
static Indicates that a variable or method is a class method (rather than being limited to one
particular object)
strictfp A Java keyword is used to restrict the precision and rounding of floating-point calculations to
ensure portability.
super Refers to a class’s base class (used in a method or class constructor)
switch A statement that executes code based on a test value
Keyword Usage
synchronized Specifies critical sections or methods in multithreaded code
this Refers to the current object in a method or constructor
throw Creates an exception
throws Indicates what exceptions may be thrown by a method
transient Specifies that a variable is not part of an object’s persistent state
try Starts a block of code that will be tested for exceptions
void Specifies that a method does not have a return value
volatile This indicates that a variable may change asynchronously
while Starts a while loop
sealed The sealed keyword is used to declare a class as “sealed,” meaning it restricts which classes
can extend it.
permits The permits keyword is used within a sealed class declaration to specify the subclasses that
are permitted to extend it.

Java Data Types :

Data types in Java are of different sizes and values that can be stored in the variable that is made as per
convenience and circumstances to cover up all test cases. Java has two categories in which data types are
segregated.

1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double. The Boolean with
uppercase B is a wrapper class for the primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
Primitive Data Types in Java
Primitive data are only single values and have no special capabilities. There are 8 primitive data types. They are
depicted below in tabular format below as follows:

Type Description Default Size Example Literals Range of values


boolean true or false false 8 bits true, false true, false
twos-complement 0 8 bits (none) -128 to 127
byte
integer
Unicode character \u0000 16 bits ‘a’, ‘\u0041’, characters
‘\101’, ‘\\’, ‘\’, ‘\n’, representation of
char
‘β’ ASCII values
0 to 255
twos-complement 0 16 bits (none) -32,768 to 32,767
short
integer
twos-complement 0 32 bits -2,-1,0,1,2 -2,147,483,648
int intger to
2,147,483,647
twos-complement 0 64 bits -2L,-1L,0L,1L,2L -9,223,372,036,854,
integer 775,808
long to
9,223,372,036,854,
775,807
Type Description Default Size Example Literals Range of values
IEEE 754 floating 0.0 32 bits 1.23e100f , -1.23e- upto 7 decimal
float
point 100f , .3f ,3.14F digits
IEEE 754 floating 0.0 64 bits 1.23456e300d , upto 16 decimal
double point -123456e-300d , digits
1e1d
Non-Primitive (Reference) Data Types
The Non-Primitive (Reference) Data Types will contain a memory address of variable values because the
reference types won’t store the variable value directly in memory. They are strings, objects, arrays, etc.

1. Strings

Strings are defined as an array of characters. The difference between a character array and a string in Java is, that
the string is designed to hold a sequence of characters in a single variable whereas, a character array is a
collection of separate char-type entities. Unlike C/C++, Java strings are not terminated with a null character.

2. Class

A Class is a user-defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can include these
components, in order:

1. Modifiers : A class can be public or has default access. Refer to access specifiers for classes or interfaces
in Java
2. Class name: The name should begin with an initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends.
A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
5. Body: The class body is surrounded by braces, { }.

3. Object

An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists of :

1. State : It is represented by the attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by the methods of an object. It also reflects the response of an object to other
objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other objects.

4. Interface

Like a class, an interface can have methods and variables, but the methods declared in an interface are by default
abstract (only method signature, no body).

Interfaces specify what a class must do and not how. It is the blueprint of the class.
An Interface is about capabilities like a Player may be an interface and any class implementing Player
must be able to (or must implement) move(). So it specifies a set of methods that the class has to
implement.
If a class implements an interface and does not provide method bodies for all functions specified in the
interface, then the class must be declared abstract.
A Java library example is Comparator Interface . If a class implements this interface, then it can be used to
sort a collection.

5. Array

An Array is a group of like-typed variables that are referred to by a common name. Arrays in Java work
differently than they do in C/C++. The following are some important points about Java arrays.

In Java, all arrays are dynamically allocated. (discussed below)


Since arrays are objects in Java, we can find their length using member length. This is different from
C/C++ where we find length using size.
A Java array variable can also be declared like other variables with [] after the data type.

Java Variables :

Variables are the containers for storing the data values or you can also call it a memory location name for the
data. Every variable has a:
Data Type – The kind of data that it can hold. For example, int, string, float, char, etc.
Variable Name – To identify the variable uniquely within the scope.
Value – The data assigned to the variable.

Types of Java Variables :


Now let us discuss different types of variables which are listed as follows:

1. Local Variables
2. Instance Variables
3. Static Variables

1. Local Variables

A variable defined within a block or method or constructor is called a local variable.

The Local variable is created at the time of declaration and destroyed after exiting from the block or when
the call returns from the function.
The scope of these variables exists only within the block in which the variables are declared, i.e., we can
access these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined scope.

EXAMPLE : 01
EXAMPLE :02
2. Instance Variables

Instance variables are non-static variables and are declared in a class outside of any method, constructor, or
block.

As instance variables are declared in a class, these variables are created when an object of the class is
created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access
specifier, then the default access specifier will be used.
Initialization of an instance variable is not mandatory. Its default value is dependent on the data type of
variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.
3. Static Variables

Static variables are also known as class variables.

These variables are declared similarly to instance variables. The difference is that static variables are
declared using the static keyword within a class outside of any method, constructor, or block.
Unlike instance variables, we can only have one copy of a static variable per class, irrespective of how
many objects we create.
Static variables are created at the start of program execution and destroyed automatically when execution
ends.
Initialization of a static variable is not mandatory. Its default value is dependent on the data type of
variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.

Scope of Variables in Java :-


The scope of variables is the part of the program where the variable is accessible.

Java Scope of Variables

Java Scope Rules can be covered under the following categories.

Instance Variables
Static Variables
Local Variables
Parameter Scope
Block Scope

1. Instance Variables – Class Level Scope

These variables must be declared inside class (outside any function). They can be directly accessed anywhere in
class. Let’s take a look at an example:

2. Static Variables – Class Level Scope


Static Variable is a type of class variable shared across instances. Static Variables are the variables which once
declared can be used anywhere even outside the class without initializing the class. Unlike Local variables it
scope is not limited to the class or the block.

3. Method Level Scope – Local Variable

Variables declared inside a method have method level scope and can’t be accessed outside the method.
Note: Local variables don’t exist after method’s execution is over.

4. Parameter Scope – Local Variable

Here’s another example of method scope, except this time the variable got passed in as a parameter to the
method:

The above code uses this keyword to differentiate between the local and class variables.

Example of Method and Parameter Scope:


5. Block Level Scope

A variable declared inside pair of brackets “{” and “}” in a method has scope within the brackets only.
Java Operators :-

Java operators are special symbols that perform operations on variables or values. They can be classified into
several categories based on their functionality. These operators play a crucial role in performing arithmetic,
logical, relational, and bitwise operations etc.
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator

1. Arithmetic Operators

Arithmetic Operators are used to perform simple arithmetic operations on primitive and non-primitive data
types.

* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or negate a value.

- , Negates the value.


+ , Indicates a positive value (automatically converts byte, char, or short to int).

++ , Increments by 1.
Post-Increment: Uses value first, then increments.
Pre-Increment: Increments first, then uses value.
-- , Decrements by 1.
Post-Decrement: Uses value first, then decrements.
Pre-Decrement: Decrements first, then uses value.
! , Inverts a boolean value.
3. Assignment Operator

‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left associativity, i.e. value
given on the right-hand side of the operator is assigned to the variable on the left, and therefore right-hand side
value must be declared before using it or should be a constant.
The general format of the assignment operator is:

In many cases, the assignment operator can be combined with others to create shorthand compound statements.
For example, a += 5 replaces a = a + 5. Common compound operators include:

+= , Add and assign.


-= , Subtract and assign.

*= , Multiply and assign.


/= , Divide and assign.

%= , Modulo and assign.


4. Relational Operators

Relational Operators are used to check for relations like equality, greater than, and less than. They return
boolean results after the comparison and are extensively used in looping statements as well as conditional if-else
statements. The general format is

Relational operators compare values and return boolean results:

== , Equal to.
!= , Not equal to.
< , Less than.
<= , Less than or equal to.

> , Greater than.


>= , Greater than or equal to.
5. Logical Operators :

Logical Operators are used to perform “logical AND” and “logical OR” operations, similar to AND gate and OR
gate in digital electronics. They have a short-circuiting effect, meaning the second condition is not evaluated if
the first is false.
Conditional operators are:
&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa.

6. Ternary operator

The Ternary Operator is a shorthand version of the if-else statement. It has three operands and hence the name
Ternary. The general format is :
7. Bitwise Operators :

Bitwise Operators are used to perform the manipulation of individual bits of a number and with any of the
integer types. They are used when performing update and query operations of the Binary indexed trees.

& (Bitwise AND) – returns bit-by-bit AND of input values.


| (Bitwise OR) – returns bit-by-bit OR of input values.
^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
~ (Bitwise Complement) – inverts all bits (one’s complement).

8. Shift Operators
Shift Operators are used to shift the bits of a number left or right, thereby multiplying or dividing the number by
two, respectively. They can be used when we have to multiply or divide a number by two. The general format :

<< (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.
9. instanceof operator

The instance of operator is used for type checking. It can be used to test if an object is an instance of a class, a
subclass, or an interface. The general format ,
Precedence and Associativity of Java Operators
Precedence and associative rules are used when dealing with hybrid equations involving more than one type of
operator. In such cases, these rules determine which part of the equation to consider first, as there can be many
different valuations for the same equation. The below table depicts the precedence of operators in decreasing
order as magnitude, with the top representing the highest precedence and the bottom showing the lowest
precedence.
Interesting Questions About Java Operators :

1. Precedence and Associativity

There is often confusion when it comes to hybrid equations which are equations having multiple operators. The
problem is which part to solve first. There is a golden rule to follow in these situations. If the operators have
different precedence, solve the higher precedence first. If they have the same precedence, solve according to
associativity, that is, either from right to left or from left to right. The explanation of the below program is well
written in comments within the program itself.
2. Be a Compiler

The compiler in our systems uses a lex tool to match the greatest match when generating tokens. This creates a
bit of a problem if overlooked. For example, consider the statement a=b+++c; too many of the readers might
seem to create a compiler error. But this statement is absolutely correct as the token created by lex is a, =, b, ++,
+, c. Therefore, this statement has a similar effect of first assigning b+c to a and then incrementing b. Similarly,
a=b+++++c; would generate an error as the tokens generated are a, =, b, ++, ++, +, c. which is actually an error
as there is no operand after the second unary operand.
3. Using + over ()

When using the + operator inside [Link]() make sure to do addition using parenthesis. If we write
something before doing addition, then string addition takes place, that is, associativity of addition is left to right,
and hence integers are added to a string first producing a string, and string objects concatenate when using +.
Therefore it can create unwanted results.
Java User Input :

The most common way to take user input in Java is using Scanner class which is part of [Link] package. The
scanner class can read input from various sources like console, files or streams.

Follow these steps to take user input using Scanner class:

Import the Scanner class using import [Link];


Create the Scanner object and connect Scanner with [Link] by passing it as an argument i.e. Scanner
scn = new Scanner([Link]);
Print a message to prompt for user input and you can use the various methods of Scanner class like
nextInt(), nextLine(), next(), nextDouble etc according to your need.

Scanner class provides some methods to read different data types:

Method Description
nextBoolean() Used for reading Boolean value.
nextByte() Used for reading Byte value.
Method Description
nextDouble() Used for reading Double value.
nextFloat() Used for reading Float value.
nextInt() Used for reading Int value.
nextLine() Used for reading Line value.
nextLong() Used for reading Long value.
nextShort() Used for reading Short value.

Example 2: Here, we are taking multiple user inputs like string, float, double etc. and using the above mentioned
methods of Scanner Class.
Another method to take user input is using BufferedReader Class. It is a simple class that is used to read a
sequence of characters. It provides several methods, including:

read(): Reads a single character.


read(char[] cbuf): Reads an array of characters.
readLine(): Reads an entire line of text.

BufferedReader vs Scanner Class


Aspects BufferedReader Scanner
Primary Use Efficient reading of character streams. Reading formatted input (e.g., integers, strings).
Aspects BufferedReader Scanner
Speed Faster for large input as it does less Slower due to parsing overhead
parsing. (e.g., nextInt(), nextFloat()).
Exception Throws checked exceptions No checked exceptions; easier to use.
Handling (e.g., IOException).
Flexibility Allows reading larger input efficiently. Best suited for reading simple data types.
Thread Safety Synchronized, making it thread-safe. Not thread-safe by default.
Common Use Used for reading large input efficiently. Commonly used for smaller, formatted input.

You might also like