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.
Why Should You Learn 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:
Versatility: Java is used in web development, mobile apps, and enterprise software.
Popularity: Many top companies are using it hence, demand for experts too increases, thus creating more employment chances.
Community Support: A large number of developers ensures constant availability of resources & help when needed by programmers worldwide.
Platform Independence: Runs on any device with JVM (Java Virtual Machine).
Security: Specially designed security features make it suitable even for sensitive applications where other languages may fail.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
History of Java
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.
Components of Java
Java consists of several tools that work together to enable it to function as a powerful and versatile programming language. The key ones include:
Java Development Kit (JDK): This is a kit of tools that facilitates the writing and compiling of programs in Java. It contains the compiler- javac, the interpreter/loader(Java), an archiver(jar), a documentation generator(Javadoc), and other tools associated with developing Java programs.
Java Runtime Environment (JRE): It’s a part of JDK but can be downloaded alone, too. It contains libraries for running Java applications, among many others, like JVM(Java Virtual Machine).
Java Virtual Machine (JVM): It is a core component of the entire Java system. It performs the execution of compiled code known as bytecode. The JVM achieves platform independence by enabling bytecode to run on any device with JVM installed.
Java Compiler (javac): A javac converts the source code into bytecode that can later be executed by JVM. A compiler only checks if a program follows rules set by language.
How to Install Java?
You can follow the below steps to install Java on your local machine.
Find the latest version of the JDK that fits your operating system and download it.
Install JDK:
Run the downloaded installer.
Follow the on-screen instructions to complete the installation.
Set Environment Variables (Windows):
Search for Environment Variables and open it.
Next, you need to add a new system variable, ‘JAVA_HOME’, having Path as a value to your JDK installation.
Edit the Path variable and add %JAVA_HOME%bin.
Verify Installation:
Open Command Prompt or Terminal.
Type java -version and javac -version to check the installation.
How Does Java Work?
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.
Writing Your First Java 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.
Code
public class test {
public static void main(String[] args) {
System.out.println("Hello World Java");
}
}
Run 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
Output
"Hello World Java"
Java Comments
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:
Single-line comments: You can use the ‘//’ operator to add single-line comments in the Java code.
Multi-line comments: You can use the ‘/* … */’ operator to add comments in multiple lines. Here, ‘/*’ represents the start of the comment, and ‘*/’ represents the end of the comment.
Let’s understand the comments using the example below.
Code
public class test {
//Single-line comment
public static void main(String[] args) {
/* This is a first line of comment.
This is a second line of comment.
*/
System.out.println("Hello World Java");
}
}
Output
"Hello World Java"
Java Features
Easy Syntax: Its syntax is simple, meaning that even someone who knows C++ can learn it faster.
Platform Independent: It does not depend on any particular computer platform; instead, all computers running Java have a specific kind of software loaded onto them called JVM (Java Virtual Machine).
Multi-threaded: Java allows several threads to run concurrently, therefore supporting multi-threading.
Distributed: Java has networking facilities, hence making distributed application creation easy.
Garbage Collection: Unexpected memory leakages are prevented by an automatic memory management system through garbage collection.
Advanced Security: It also contains advanced security features like secure communication, cryptography, and others, which make Java applications safe.
Applications of Java
Java is utilised in various applications as it can be used in various fields. Here are some key areas where Java is commonly applied:
Web Applications: Server-side application development happens extensively using Java. Dynamic web pages and strong web applications are created through technologies like Spring and JSP.
Mobile Applications: Most Android apps are programmed using Java language.
Enterprise Applications: Large-scale, secure, and scalable enterprise applications use Java EE (Enterprise Edition). These components include Servlets, Enterprise JavaBeans (EJB), and JMS (Java Message Service).
Desktop GUI Applications:
Libraries such as Swing and JavaFX facilitate the creation of highly advanced graphical user interfaces for desktop-based apps using Java.
Games: Game developers use Java to build both 2D and 3D games. The lightweight Java game library (LWJGL) as well as the Java 2D API, support game development through third-party libraries, among others.
Big Data Technologies: Several big data tools like Apache Hadoop or Apache Spark rely on Java as their base platform due to its scalability coupled with robustness when dealing with huge datasets.
Testing Tools: Automated testing frameworks like Selenium or JUnit have been built in Java to create testing tools.
Input/Output in Java
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:
Import the java.util.Scanner class to use it.
Next, To read input, create an instance of the Scanner class.
Read various data types using the Scanner methods like nextLine(), nextInt(), nextDouble(), etc.
To print output to the console, you use the System.out object and its methods. The most common methods are print and println.
Example
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Take name input from user
System.out.print("Enter your name: ");
String name = scanner.nextLine();
// Print the name
System.out.println("Name: " + name);
scanner.close();
}
}
Output
It prints the input you provided in the console.
Java Variables
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.
Code
In the code below, we have declared the ‘num’ variable of integer data type and stored value ‘10’.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
int num = 10; // Declaring a variable
System.out.println(num); // Printing a number
}
}
Output
10
Java Data Types
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.
Primitive Data Types
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 in Java
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 (Widening)
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 (Narrowing)
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
Example
public class test {
public static void main(String[] args) {
double doubleNum = 100.04;
int num = (int) doubleNum; // Explicit casting from double to int
System.out.println("Double value: " + doubleNum);
System.out.println("Integer value: " + num);
}
}
Output
Double value: 100.04
Integer value: 100
Arrays in Java
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.
int[] arrayname;
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.
public class test {
public static void main(String[] args) {
int[] numbers = {10, 2, 33, 4, 56};
System.out.println("First element: " + numbers[0]); // Outputs 10
System.out.println("Second element: " + numbers[1]); // Outputs 2
}
}
Strings in Java
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:
Using the string literal: You can use the double quotes to declare the string.
String greeting = "Hello, World!";
Using the String() Constructor: You can also use the String() constructor to create an instance of the String class.
String greeting = new String("Hello, World!");
Data Structures in Java
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.
Built-in Data Structures
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
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
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
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.
if-else Statement
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.
Example
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.
public class test {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is not positive.");
}
}
}
Output
The number is positive.
switch Statement
The switch statement allows you to choose one of many code blocks to be executed based
on the value of an expression.
Syntax
switch (expression) {
case value1:
// Write a code to execute if the expression equals value1
break;
case value2:
break;
// additional cases
default:
}
Looping Statements
for Loop: The for loop is used
to iterate a block of code a specified number of times.
for (initialization; condition; update) {
// code to be executed
}
while Loop: It executes a block
of code as long as a specified condition is true.
while (condition) {
// code to be executed
}
do-while Loop: The do-while loop
is similar to the while loop, but it executes the block of code at least once before checking the
condition.
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.
Classes and Objects
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.
Example
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.
public class Main {
public static void main(String[] args) {
Animal dog = new Animal(); // Create an object of Animal class
dog.name = "Jim"; // Set property
dog.speak(); // Call method
}
}
class Animal {
String name; // Property
void speak() { // Method
System.out.println("The animal speaks.");
}
}
Output
The animal speaks.
Here are the four pillars of OOP.
Encapsulation: Encapsulation
limits direct access to an object’s data by allowing it only to be accessed through well-defined methods.
This improves its security as well as the integrity of data. Inheritance: Inheritance is where a new class can acquire properties or methods from otherexisting ones.It encourages code reusability and establishes a hierarchy among classes.
Polymorphism: 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.
Abstraction: Abstraction is the approach of hiding implementation details and revealing only those characteristics of an object, which are significant to the user. The complex systems are simplified, and classes are modelled that form the basis of any problem domain.
Methods in Java
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.
Normal Method: It is also known
as instance methods, which are associated with an instance of a class. They can access instance variables
and methods.
class Example {
void instanceMethod() {
// Method code
}
}
Static Method: Static methods belong to the class itself and can be called without creating an instance. They can only directly access static variables and methods.
class Example {
static void staticMethod() {
// Method code
}
}
Java Packages
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.
Java Collection Framework
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.
Key Components of the Collection Framework
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
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.
Key Components of Error Handling
Try Block: It encloses code that might throw an exception. If an exception occurs, the flow of control is transferred to the catch block.
Catch Block: It catches and handles the exception thrown by the try block. You can also define multiple catch blocks to handle different types of exceptions.
Finally Block: It always executes after the try and catch blocks. It is used for cleanup activities like closing resources, regardless of whether an exception was
thrown or not.
Example
public class test {
public static void main(String[] args) {
try {
// Code with error
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
// Handle the exception
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
// Cleanup code
System.out.println("Finally block executed.");
}
}
}
Output
Cannot divide by zero: / by zero
Finally block executed.
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:
Thread: It is the smallest unit of a process that can be scheduled for execution.
Main Thread: The first thread created by JVM (Java Virtual Machine) when it starts executing the program’s main method.
Concurrency: It is a way of performing several tasks at once by running multiple threads in parallel.
Java File Handling
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.
What you can do with Java File Handling
Create Files: You can use Java to create new files in the file system.
Read Files: In Java, there are methods to read content from files such as text or binary files.
Write Files: You can write data into files, even appending data into existing ones.
Delete Files: You can erase any file from file systems using Java code if you have permission.
File Information: Various information about a file like its size, permissions, and last modified date, may be obtained through the use of this method call.
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.
Regex Usage
Pattern Matching: Identify and extract particular patterns from strings like email addresses, phone numbers, or dates.
Validation: Validate input strings against certain formats, such as passwords and usernames.
Search and Replace: This is useful in text processing and formatting through finding and replacing parts of string based on
patterns.
String Splitting: This helps in data parsing by splitting strings into arrays using regex patterns.
Complex Searches: You can perform advanced searches with quantifiers, groups, and character classes, among other things, within Java regex constructs that are more complex than the Perl version.
Java Networking
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.
Uses of Java Networking
Socket Programming: Use a socket to establish communication between two machines to exchange data over TCP/IP
Client-Server Applications: Build client-server applications where the server handles several clients at once.
URL Handling: URL access, web content download, and interaction with web services are some examples of what URL handling involves.
Multithreaded Servers: These servers employ multithreading to simultaneously deal with multiple client connections
Protocol Implementation: Designing application-specific custom protocols for network implementation purposes are other use cases of the Java Networking technology.
Pros & Cons of Java
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.
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 vs Other Programming Languages
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
Conclusion
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.
FAQs
What is Java in 50 words?
Java is a popular, platform-independent, object-oriented programming language used for building a wide range of applications. It's known for its simplicity, robustnеss, and portability.
How to start a Java program for bеginnеrs?
Bеginnеrs can start by installing JDK, sеtting up an IDE like Eclipse, and writing simple programs to understand basic concepts.
Is Java еasy or Python?
Python is generally easier to learn due to its simple syntax, but Java is powerful and widely used in enterprise environments.
Whеrе is Java mostly used?
Java is mostly used in web development, mobile applications (Android), еntеrprisе softwarе and largе scalе systеms.
What are the 4 pillars of Java?
The four pillars of Java are Encapsulation, Inhеritancе, Polymorphism, and Abstraction.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.