Popular
Data Science
Technology
Finance
Management
Future Tech
Java is among the most popular programming languagеs globally. It is known for its vеrsatility and use in different fields. Java is extensively used in the application dеvеlopmеnt field, automation, еtc. and learning it can еxposе onе to many job opportunities. Java frameworks like SpringBoot have made it easier to develop applications with Java.
This guidе covеrs еvеrything about Java from introduction to advancеd concepts such as thе history of Java, installation procеss, variablеs, data typеs in Java, еtc. up to objеct oriеntеd programming in Java.
Whether you are a beginner or an experienced programmer looking for new skills or career opportunities, there are several reasons why you should learn Java. Some of them include:
In 1995, James Gosling and his team at Sun Microsystems developed a language called Java, which was intended to run on any device regardless of hardware or software used underneath.
In the early 1990s, the Java project began as an undertaking named “Oak”, which was aimed at programming home appliances. Nonetheless, the project was renamed “Java” and adjusted for Web development, which was rapidly growing during that time.
Sun Microsystems became Oracle Corporation’s new owner in 2009. Now, Oracle manages regular updates and releases of new versions of Java.
Java is widely used today in Android development, enterprise applications, and large-scale systems.
Java consists of several tools that work together to enable it to function as a powerful and versatile programming language. The key ones include:
You can follow the below steps to install Java on your local machine.
Download JDK:
Java is simply designed to be able to run on all devices having Java virtual machines in them thus ensuring that its code runs anywhere.
To start with, you write your source code(mostly saved with .java extension) in a text editor or Integrated Development Environment (IDE). The next step is to compile source code using Java compiler, which will be converted into byte codes. These are saved in .class files that contain the programs’ instructions to be understood by JVM. After loading them into memory, JVM reads the .class files and prepares them for execution. Finally, JVM interprets or compiles the bytecode to machine code based on OS and hardware it’s running on using its JIT(Just-In-Time)compiler that optimises performance.
Finally, the computer processor executes the machine code, which becomes the program.
After the successful installation of Java, let’s write the first ‘Hello World’ program in Java.
First, create the test.java file and add the code below to the file. You need to ensure that the class name (‘test’) is the same as the file name if you have created the file with a different name.
The main method in the code prints the “Hello World Java” message in the output console when you execute the code.
To run the code, navigate to the file path in the terminal and execute the below command to compile the Java code. javac test.java After that, execute the below command to run the compiled code.
java test
In Java, comments are used to add notes in the code. By using the comments, you can explain each line of the code. Whenever you compile the code, it ignores the comments.
In Java, You can add comments using the below two different ways:
Let’s understand the comments using the example below.
Java is utilised in various applications as it can be used in various fields. Here are some key areas where Java is commonly applied:
Java provides straightforward ways to handle standard input and output operations. These operations allow your program to interact with users via the console.
To read input from the console, you typically use the Scanner class. Here’s how to do it:
To print output to the console, you use the System.out object and its methods. The most common methods are print and println.
Variables are fundamental to any programming language which are used to store the values. It works as a storage container, which allows you to store, update, and access values.
In the code below, we have declared the ‘num’ variable of integer data type and stored value ‘10’.
Java data types specify the type of data that a variable can hold. They are essential for defining how much memory is needed and what kind of operations can be performed on the data. In the table below, we have covered all data types of Java.
Data Type | Description | Size | Example |
byte | 8-bit integer | 1 byte | byte b = 100; |
short | 16-bit integer | 2 bytes | short s = 10000; |
int | 32-bit integer | 4 bytes | int i = 100000; |
long | 64-bit integer | 8 bytes | long l = 100000L; |
float | 32-bit floating-point | 4 bytes | float f = 10.5f; |
double | 64-bit floating-point | 8 bytes | double d = 10.5; |
char | Single 16-bit Unicode | 2 bytes | char c = ‘A’; |
boolean | true or false | 1 bit | boolean flag = true; |
Type casting is used to change the data type of the variable. It is essential when performing operations between different data types. There are two types of casting: implicit (automatic) and explicit (manual).
Implicit casting happens automatically when converting a smaller data type to a larger data type. The data loss doesn’t occur in this process.
From Type | To Type |
byte | short, int, long, float, double |
short | int, long, float, double |
int | long, float, double |
long | float, double |
float | double |
Explicit casting is required when converting a larger data type to a smaller data type. It involves a potential loss of data and must be done manually using parentheses.
From Type | To Type |
double | float, long, int, short, byte |
float | long, int, short, byte |
long | int, short, byte |
int | short, byte |
short | byte |
Arrays are used to store the multiple values of the same data type in a single variable. They are a fundamental data structure that provides a way to organise data efficiently. The array index always starts from 0, which you can use to update and access array elements.
You can use the below syntax to declare the array.
Let’s look at the below code to use array in Java. In the code below, we have declared the ‘numbers’ array and initialised it with the five numbers. After that, we used the array indexes to access the first and second elements of the array.
In every programming language, strings are important and are used to store and manipulate text data. The string is a data type and sequence of characters. It is a non-primitive data type.
You can use two different ways to declare the string:
Data structures allow developers to organise and manage data efficiently. Java provides various built-in data structures to handle different types of data. Here’s a comprehensive overview of the most commonly used data structures in Java.
Data Structure | Description |
Array | It is a fixed-size data structure that can store multiple elements of the same data type. Allows random access to elements. |
ArrayList | Resizable array implementation of the List interface. Provides dynamic array capabilities. |
HashMap | Implementation of the Map interface. Stores key-value pairs and allows fast retrieval based on keys. |
TreeMap | Red-Black tree-based implementation of the Map interface. Maintains sorted order of keys. |
HashSet | Implementation of the Set interface. Stores unique elements and allows fast retrieval. |
TreeSet | NavigableSet implementation based on a TreeMap. Maintains elements in sorted order. |
PriorityQueue | Implementation of the Queue interface. Provides priority-based ordering of elements. |
Stack | Legacy class representing a last-in, first-out (LIFO) stack of objects. |
Queue | Interface representing a first-in, first-out (FIFO) queue. Implemented by classes like LinkedList and PriorityQueue. |
ArrayDeque | Resizable-array implementation of the Deque interface. |
Java operators are special symbols used to perform operations on variables and values. They are categorised based on the type of operation they perform. Here’s a comprehensive table of Java operators:
Operator Type | Operator | Description | Example |
Arithmetic Operators | + | Addition | a + b |
– | Subtraction | a – b | |
* | Multiplication | a * b | |
/ | Division | a / b | |
% | Modulus (remainder) | a % b | |
Unary Operators | + | Unary plus (promotes to int) | +a |
– | Unary minus (negates an expression) | -a | |
++ | Increment (increases value by 1) | a++ or ++a | |
— | Decrement (decreases value by 1) | a– or –a | |
! | Logical NOT | !a | |
Relational Operators | == | Equal to | a == b |
!= | Not equal to | a != b | |
> | Greater than | a > b | |
< | Less than | a < b | |
>= | Greater than or equal to | a >= b | |
<= | Less than or equal to | a <= b | |
Logical Operators | && | Logical AND | a && b |
|| | Logical OR | `a || b | |
Bitwise Operators | & | Bitwise AND | a & b |
| | Bitwise OR | a | b | |
^ | Bitwise XOR | a ^ b | |
~ | Bitwise complement | ~a | |
<< | Left shift | a << 2 | |
>> | Right shift | a >> 2 | |
>>> | Unsigned right shift | a >>> 2 | |
Assignment Operators | = | Assigns value | a = b |
+= | Addition assignment | a += b | |
-= | Subtraction assignment | a -= b | |
*= | Multiplication assignment | a *= b | |
/= | Division assignment | a /= b | |
%= | Modulus assignment | a %= b | |
&= | Bitwise AND assignment | a &= b | |
` | =` | Bitwise OR assignment | |
^= | Bitwise XOR assignment | a ^= b | |
<<= | Left shift assignment | a <<= 2 | |
>>= | Right shift assignment | a >>= 2 | |
>>>= | Unsigned right shift assignment | a >>>= 2 |
Java keywords are reserved words that have a specific meaning in the language. They cannot be used as identifiers (names for variables, methods, classes, etc.).
Keywords help define the structure and flow of a Java program. In the table below, we have covered some important keywords.
Keyword | Description |
abstract | Used to declare an abstract class that cannot be instantiated. |
boolean | Defines a variable for the values true and false only. |
break | Exits from the loop or switch statement. |
byte | Defines an 8-bit integer variable. |
case | Defines a branch in a switch statement. |
catch | Catches exceptions generated by try statements. |
char | Defines a character variable capable of holding any character. |
class | Declares a class. |
Java control statements manage the flow of execution in a program. They enable decision-making, looping, and branching, which are essential for creating dynamic and flexible code.
The if-else statement allows you to execute a block of code if a condition is true and another block of code if the condition is false.
In the below code, we have used the ‘number > 0’ condition with the ‘if’ statement.
Here, the condition is true. So, it will execute the code inside the ‘if’ block.
The switch statement allows you to choose one of many code blocks to be executed based
on the value of an expression.
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects. OOP is used by Java to provide a modular and manageable software structure.
In OOP, classes and objects are fundamental concepts. A class, for instance, serves as a blueprint for objects while also specifying their behaviour and properties. On the other hand, an object is an actual occurrence of a given class.
Below, we have defined the Animal class, which has a ‘name’ property to store the name of the animal and speak() method.
In the main() method, we have created an instance of the Animal() class and used it to set the value of the ‘name’ property and call the speak() method.
Here are the four pillars of OOP.
Encapsulation: EncapsulationPolymorphism: Polymorphism allows methods that do different functions depending on which object calls them. This adds flexibility to codes because polymorphism involves overriding and overloading of methods.
In Java, methods are an alternative to functions in other programming languages, which are used to perform a specific task. It allows you to write a reusable code.
There are two main types: normal (instance) methods and static methods.
Packages in Java are used to group related classes, interfaces, and sub-packages. They provide a modular structure to the code and help in avoiding name conflicts. Packages also make it easier to manage and organise large applications.
Here are some common Java Packages.
Package | Description |
java.lang | Contains fundamental classes like String, Math, System, and Object. |
java.util | Includes utility classes like ArrayList, HashMap, Date, and Collections. |
java.io | Provides classes for input and output through data streams and file systems. |
java.nio | Contains classes for non-blocking I/O operations. |
java.net | It provides classes for networking applications, including socket and URL. |
java.sql | Contains classes for accessing and processing data stored in a database. |
javax.swing | Includes classes for building graphical user interfaces (GUIs). |
java.awt | Contains classes for building graphical user interface components. |
java.text | Provides classes for text formatting and parsing. |
java.time | Contains classes for date and time API introduced in Java 8. |
The Java Collection Framework is a collection of classes and interfaces for storing and manipulating a group of data
as one object. It has different data structures such as lists, sets, and maps that help in dealing with data efficiently.
Interface | Description |
List | Ordered collection that allows duplicate elements. Implementations include ArrayList, LinkedList. |
Set | Collection that does not allow duplicate elements. Implementations include HashSet, TreeSet. |
Queue | Collection is used to hold multiple elements prior to processing. Implementations include LinkedList, PriorityQueue. |
Map | The object that maps keys to values, with no duplicate keys allowed. Implementations include HashMap, TreeMap. |
Deque | Double-ended queue that allows element insertion and removal at both ends. Implementations include ArrayDeque, LinkedList. |
Error handling in Java is crucial for building robust and error-resistant programs. It allows developers to manage runtime errors, ensuring the program can handle exceptions gracefully and continue execution or terminate smoothly.
In Java, multi-threading refers to the capability of running multiple threads at the same time. This is a powerful feature that can be used to perform several tasks simultaneously, thereby improving application performance.
Here are key points about multi-threading:
Java File Handling is an important part of Java programming, which enables the creation, reading, updating, and deletion of files on a computer. It helps in interacting with file systems and managing data storage efficiently.
Java regular expressions (regex) are a powerful tool for pattern matching and manipulating text. It is a sequence of characters used to search for similar patterns in the string.
Java networking allows creating and managing network connections that facilitate communication between computers over the network. It plays a crucial role in developing networking-based applications.
Java is a widely used programming language with many advantages and some disadvantages. Here’s a summary of its pros and cons in a single table:
Aspect | Pros | Cons |
Platform Independence | Java programs can run on any device with a Java Virtual Machine (JVM). |
Requires JVM, which may not be available in all environments. |
Performance | Generally performs well with good optimization. | Slower compared to languages like C or C++ due to JVM overhead. |
Memory Management | Automatic garbage collection prevents memory leaks. | Higher memory consumption compared to some lower-level languages. |
Multi-threading | Native support for multi-threading enables efficient concurrent processing. |
Managing multi-threading can be complex and error-prone. |
GUI Frameworks | Supports GUI development through Swing and JavaFX. | Java’s GUI frameworks are considered less modern compared to other technologies. |
Java is often compared to other programming languages. Here’s a comparison of Java with C, C++, and Python:
Feature | Java | C | C++ | Python |
Performance | Moderate | High | High | Low |
Memory Management | Automatic | Manual | Manual | Automatic |
Platform Independence | High | Low | Medium | High |
Syntax | Verbose | Low-level | Complex | Simple |
Learning Curve | Steep | Steep | Steep | Gentle |
Use Cases | Enterprise, Android | Systems, Embedded | System, Game | Web, Data Science |
Java is a versatile and powerful programming language widely used in various fields such as web dеvеlopmеnt, mobile applications, and еntеrрrisе solutions. Its object-oriented principles, platform indеpеndеncе, and an extensive standard library make it a top choice for developers. While Java has its challenges, such as verbosity and performance overhead, its advantages, robust community support, security features, and multi-threading capabilities outweigh its cons.
Learning Java can opеn numеrous opportunities in thе tеch industry, making it a valuable skill for both bеginnеrs and еxpеriеncеd programmers. Whether you’re building simple applications or complex systems, Java remains a reliable and efficient language.
The DevOps Playbook
Simplify deployment with Docker containers.
Streamline development with modern practices.
Enhance efficiency with automated workflows.
Popular
Data Science
Technology
Finance
Management
Future Tech
Accelerator Program in Business Analytics & Data Science
Integrated Program in Data Science, AI and ML
Certificate Program in Full Stack Development with Specialization for Web and Mobile
Certificate Program in DevOps and Cloud Engineering
Certificate Program in Application Development
Certificate Program in Cybersecurity Essentials & Risk Assessment
Integrated Program in Finance and Financial Technologies
Certificate Program in Financial Analysis, Valuation and Risk Management
© 2024 Hero Vired. All rights reserved