Comprehensive Java Programming Guide
Comprehensive Java Programming Guide
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.
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 :
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.
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.
The JVM executes the compiled bytecode, translating it into machine code specific to the operating system and
hardware.
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.
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.
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.
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.
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(;)
1. Comments in Java :
Multi-line Comment
Documentation Comment
Note:
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
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.
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:
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.
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.
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
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
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.
Instance Variables
Static Variables
Local Variables
Parameter Scope
Block 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:
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.
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.
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.
++ , 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:
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
== , Equal to.
!= , Not equal to.
< , Less than.
<= , Less than or equal to.
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.
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
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 :
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.
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: