Introduction to Java Programming
Java is one of the most popular and widely used programming languages in the world. It is an object-oriented programming language used to build desktop and mobile applications, web applications, games, embedded systems, and more. Java code can run on any device that has a Java Virtual Machine (JVM) installed, including Windows, macOS, Linux, and mobile platforms. This allows Java applications and code written once to run anywhere without recompilation. Some key things to know about Java:
Object-oriented – Java is an object-oriented programming language. It allows code organization and reuse through classes, interfaces, inheritance, and polymorphism.
Platform independent – As mentioned above, Java code can run on any device that supports Java without needing to be recompiled. This helps ensure Java code will run on different platforms.
Secure and robust – Features like garbage collection, bytecode verification, and sandboxing help make Java very secure and robust. Java code cannot directly access memory locations or device hardware for security reasons.
Widely used – Java is one of the most popular programming languages and is used across the web, desktop, mobile apps, games, etc. Its wide use and large community make Java a stable and supported option.
Large standard library – The Java class library provides a huge amount of pre-written code for common tasks like networking, file I/O, XML handling, collections, etc. This speeds up development significantly.
Extensive tools and IDE support – Java has many powerful integrated development environments (IDEs) that simplify development like Eclipse, NetBeans, and IntelliJ IDEA. Also, tools like Maven and Gradle aid in build automation.
Java is an excellent option for any programming task due to its platform independence, security, large library and community, and IDE/tool support. Let’s now look at how to write some basic Java code and programs.
Hello World Program
The simplest and most common first program written in any programming language is the “Hello World” program. Here is how you can write this basic program in Java:
Create a Java file named HelloWorld.java
Add the following code:
java
Copy
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello World!”);
}
}
Save the file
Compile the code using javac HelloWorld.java
Run the program using java HelloWorld
This will print “Hello World!” to the console. Let’s break down what this code is doing:
The public class declares a named public class called HelloWorld
The main() method is the entry point for all Java programs
It is static so it can be called without creating an object of the class
It takes an array of strings as arguments which can be command line arguments
The System.out.println() prints the string to the standard output stream
This is the simplest Java program possible to print output. You can modify it to print your name, greeting message etc.
Basic Java Concepts
Now let’s look at some key Java programming concepts that are important to understand:
Classes – Classes are blueprints that define the properties and behaviors of user-defined objects in Java using fields and methods. They act as templates to create objects.
Objects – Objects are instances of classes that are allocated memory at runtime. They have state and behavior defined by class fields and methods respectively.
Fields (Variables) – Fields are variables declared within a class that store state specific to each object. They can be instance or static variables.
Methods – Methods are functions that define behavior and are defined within classes using access modifiers, return type, name and parameters.
Access Modifiers – Modifiers like public, private, protected control access/visibility of classes, fields and methods.
Data Types – Basic types like int, double, boolean and reference types like String, arrays, classes etc.
Constructors – Special methods that create and initialize an object of a class. Constructor name matches class name.
Inheritance – Deriving a child class from a parent class to inherit its members using extends keyword.
Polymorphism – Ability of an object to take on multiple forms. Achieved by method overriding and overloaded methods.
Abstraction – Hiding implementation details and exposing only necessary/relevant details through interfaces and abstract classes.
Encapsulation – Bundling code and data together into a single unit like a class and controlling access to members.
Packages – Namespaces that organize related classes and interfaces. Helps avoid naming collisions.
Interfaces – Blueprints of a class that can have only abstract methods, static/constant fields. Multiple interfaces implemented via implements.
These are some of the fundamental concepts needed to understand and write Java programs. Let’s now look at an example Java program that uses some of these concepts.
Basic Class Example
Here is a basic Java program with a Student class that demonstrates some key concepts:
java
Copy
public class Student {
//Fields (variables)
private int rollNo;
private String name;
//Constructor
public Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
//Method
public void displayStudentDetails() {
System.out.println(“Roll No: ” + rollNo);
System.out.println(“Name: ” + name);
}
public static void main(String[] args) {
//Create object
Student student1 = new Student(101, “John”);
//Invoke method
student1.displayStudentDetails();
}
}
This program demonstrates:
Defining a class with fields
Declaring constructor to initialize fields
Defining a non-static method that accesses fields
Creating an object invoking method from main
To summarize:
Classes organize code into reusable blueprints
Objects are class instances allocated memory at runtime
Fields store state specific to each object
Constructors initialize objects
Methods define behavior
This covers a basic overview of writing Java code and programming concepts. Let’s now look at some common Java programs.
Common Java Programs
Here are some example programs that demonstrate common uses of Java:
Calculator Program
Performs basic arithmetic operations like addition, subtraction etc using methods
Takes user input, performs calculation and displays output
Array Program
Demonstrates arrays to store multiple values of same type
Can sort, search, insert, delete array elements
String Programs
Perform operations on String like concat, compare, substring etc
Useful for text processing
Date and Time Program
Uses Date and Calendar class to work with dates and times
Handle date/time calculations, formatting and parsing
File Handling Program
Read/write files using File, FileReader, FileWriter classes
Useful for logging, configuration, saving data
Database Connectivity Program
Connect to databases like MySQL using JDBC
PerformCRUDoperations to demonstrate data access
Multi-Threading Program
Create and manage multiple threads
Demonstrate benefits of concurrency over single threaded programs
Networking Program
Create simple client-server programs
Handle sockets, URLs, networking tasks
Games using Swing Library
Create simple games like TicTacToe
Demonstrate GUI programming using Swing components
These are some of the common tasks Java is well-suited for. Let’s now discuss a database connectivity program in more detail.
Java Database Connectivity (JDBC) Program
One common task is connecting Java applications to relational databases to access and manipulate persistent data. Java Database Connectivity (JDBC) is the API that facilitates communication between Java and databases like MySQL, Oracle, Microsoft SQL Server etc.
Here is an example program to demonstrate basic database operations from Java:
Import Java classes –
java
Copy
import java.sql.*;
Define main method and establish connection:
java
Copy
public static void main(String[] args) {
// Database URL, credentials
String url = “jdbc:mysql://localhost:3306/dbname”;
String username = “root”;
String password = “password”;
try {
Connection con = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
//exception handling
}
}
Define queries and execute statements:
java
Copy
//Insert
String sql = “INSERT INTO table VALUES (?, ?)”;
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, “John”);
pstmt.setInt(2, 25);
pstmt.executeUpdate();
//Select
String sql = “SELECT * FROM table”;
ResultSet rs = stmt.executeQuery(sql);
Handle result set and close resources
Handle any exceptions
This demonstrates how to connect to a database, execute queries and retrieve results using JDBC in Java. More complex CRUD operations can also be performed like update, delete, stored procedures, transactions etc.
JDBC provides a standard interface to connect Java programs to various databases
