Introduction to Java Programming
1.0 Introduction
Java is a high-level, class-based, object-oriented programming language
designed to have as few implementation dependencies as possible. It is widely
used for developing robust, scalable, and secure applications for various
platforms.
1.1 Objectives
By the end of this section, you should be able to:
Understand the basic features and characteristics of Java.
Learn the tools required to set up and run Java applications.
Comprehend Java's architecture and security features.
Work with variables, literals, operators, and data types in Java.
1.2 Java Programming Language
Java is a platform-independent programming language that runs on the
principle of "Write Once, Run Anywhere" (WORA). This means that Java
programs can run on any device that has the Java Virtual Machine (JVM).
1.3 Characteristics of Java Programming Language
1. Platform-Independent: Java code is compiled into bytecode, which can
run on any platform using the JVM.
2. Object-Oriented: Java uses objects and classes as its core components.
3. Simple and Easy to Learn: Its syntax is derived from C and C++,
making it easier for those familiar with those languages.
4. Secure: Java provides robust security features like bytecode verification
and runtime security checks.
5. Multithreaded: Supports concurrent execution of multiple threads.
6. Robust: Java provides strong memory management and exception
handling.
7. Portable: Java programs can be executed across various systems
without requiring recompilation.
8. Dynamic: Java supports dynamic linking and loading of classes during
runtime.
1.4 History of Java
Java was developed by James Gosling and his team at Sun Microsystems in
1995. Initially called "Oak," it was later renamed Java, inspired by the coffee
consumed by its creators. The language was designed to enable interactive
television, but it became popular for internet applications due to its portability.
Key milestones in Java's evolution:
1995: Java 1.0 was released.
2004: Java 5 introduced features like generics and annotations.
2014: Java 8 introduced lambda expressions and the Stream API.
2021: Java 17 became the latest Long-Term Support (LTS) release.
1.5 Tools Required to Run Java Applications
JDK (Java Development Kit): Includes the tools needed to develop and
run Java applications.
JRE (Java Runtime Environment): Provides the runtime environment
for executing Java programs.
JVM (Java Virtual Machine): Converts Java bytecode into machine
code.
1.6 Java Environment Setup
To set up Java:
1. Download and install the latest version of the JDK from the Oracle
website.
2. Set the JAVA_HOME environment variable to the JDK installation path.
3. Update the system's PATH variable to include the bin directory of the JDK.
4. Test the setup by running java -version and javac -version in the terminal.
1.7 Most Used Java Editors
IntelliJ IDEA: Popular for its advanced features and user-friendly
interface.
Eclipse: Free, open-source IDE widely used for Java development.
NetBeans: Another free IDE that supports multiple languages.
Visual Studio Code: Lightweight editor with Java extensions.
BlueJ: Simple IDE for beginners.
1.8 Java Architecture
Java follows a three-layer architecture:
1. Java Code: Written by the developer.
2. Bytecode: Generated after compiling the Java code.
3. JVM: Executes the bytecode.
The Java architecture ensures portability and security through its modular
design and the use of the JVM.
1.9 Java Architectural Security
Java provides the following security features:
Bytecode Verification: Ensures that the code adheres to Java's
specifications.
Class Loader: Separates the namespaces of different classes to prevent
malicious code execution.
Security Manager: Restricts operations that a Java application can
perform.
Sandboxing: Runs untrusted code in a restricted environment.
1.10 Declaration of Variables and Literals
Variables are named memory locations used to store data, while literals are
fixed values assigned to variables.
1.11 Data Types
Java data types are categorized into two types:
1. Primitive Data Types
These are the basic data types built into the Java language. Java has 8 primitive
data types:
Explanation of Java Data Types
In Java, data types specify the size and type of data that variables can store.
Data types are divided into primitive and non-primitive categories. Below is
a detailed explanation of each primitive data type, their characteristics, size,
and examples.
1. byte
Description:
Stores integer values in a small range.
Useful for saving memory, especially in large arrays where memory
usage is critical.
Size: 1 byte (8 bits).
Range: -128 to 127.
Example:
byte age = 25;
byte smallNumber = -100;
2. short
Description:
Stores integer values, similar to byte, but allows a slightly larger
range.
Also useful for saving memory in arrays.
Size: 2 bytes (16 bits).
Range: -32,768 to 32,767.
Example:
short temperature = 30000;
short lowNumber = -25000;
3. int
Description:
The most commonly used integer data type for storing whole
numbers.
Used when the range of byte and short is insufficient.
Size: 4 bytes (32 bits).
Range: -2³¹ to 2³¹-1 (-2,147,483,648 to 2,147,483,647).
Example:
int salary = 50000;
int largeNumber = -1000000;
4. long
Description:
Used for storing very large integer values beyond the range of int.
Requires an L suffix for literals to indicate it's a long value.
Size: 8 bytes (64 bits).
Range: -2⁶³ to 2⁶³-1 (-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807).
Example:
long distance = 15000000000L;
long bigNumber = -9000000000000000L;
5. float
Description:
Used for storing decimal (floating-point) numbers with single
precision (less precision than double).
Requires an F suffix for literals to indicate it's a float value.
Size: 4 bytes (32 bits).
Range: Approximately ±3.40282347E+38 (7 decimal places).
Example:
float price = 19.99F;
float smallDecimal = -0.0001F;
6. double
Description:
The default data type for storing decimal numbers.
Provides higher precision than float (double precision).
Size: 8 bytes (64 bits).
Range: Approximately ±1.79769313486231570E+308 (15 decimal
places).
Example:
double pi = 3.141592653589793;
double largeDecimal = -1.234567890123456;
7. char
Description:
Stores a single character or Unicode value.
Can store any character from the Unicode set, including letters,
digits, or special symbols.
Size: 2 bytes (16 bits).
Range: 0 to 65,535 (unsigned Unicode values).
Example:
char grade = 'A';
char symbol = '@';
char digit = '1';
8. boolean
Description:
Used for storing logical values: true or false.
Commonly used in decision-making and control flow (like if
conditions).
Size: 1 bit (theoretically, but JVM stores it as a byte for alignment).
Example:
boolean isPassed = true;
boolean isActive = false;
Summary Table
Data Example
Description Size Range
Type Values
1
byte Stores small integers. -128 to 127 25, -100
byte
2
short Stores larger integers. -32,768 to 32,767 30000, -25000
bytes
4 50000, -
int Default integer type. -2³¹ to 2³¹-1
bytes 1000000
Stores very large 8 15000000000
long -2⁶³ to 2⁶³-1
integers. bytes L
Data Example
Description Size Range
Type Values
Stores decimals (less 4 19.99F, -
float ±3.40282347E+38
precision). bytes 0.0001F
8 ±1.7976931348623157 3.14159, -
double Default for decimals.
bytes 0E+308 1.23456
Stores a single 2 0 to 65,535 (Unicode
char 'A', '@', '1'
character. bytes values)
boolea
Stores true/false. 1 bit true, false true, false
n
2. Non-Primitive (Reference) Data Types
These are more complex data types created by the programmer or provided by
Java, used to store objects and more complex structures.
Examples:
1. Strings: A sequence of characters, defined as String.
Example:
String name = "John";
2. Arrays: A collection of elements of the same type.
Example:
int[] numbers = {1, 2, 3, 4, 5};
3. Classes: User-defined types that group fields and methods.
4. Interfaces: Defines methods that a class must implement.
5. Collections: Includes dynamic data structures like ArrayList, HashMap,
etc.
1.12 Defining Variables and Literals
To define a variable:
int number = 10; // "number" is the variable, and "10" is the literal.
Literals represent fixed values in Java, such as:
Integer Literals: 10, 0b1010 (binary), 012 (octal), 0xA (hexadecimal).
Floating-Point Literals: 3.14, 1.0e4.
Character Literals: 'A', '\n'.
String Literals: "Hello".
Boolean Literals: true, false.
1.13 Variable Naming Convention
1. Variable names should be meaningful and descriptive.
2. They must begin with a letter, a dollar sign ($), or an underscore (_).
3. Avoid using reserved keywords.
4. Use camelCase for naming.
1.14 Variable Declaration and Assignment
Declaration: int x;
Assignment: x = 5;
Combined: int x = 5;
1.15 Literals in Java
Literals represent fixed values in Java, such as:
Integer Literals: 10, 0b1010 (binary), 012 (octal), 0xA (hexadecimal).
Floating-Point Literals: 3.14, 1.0e4.
Character Literals: 'A', '\n'.
String Literals: "Hello".
Boolean Literals: true, false.
1.16 Assignment Operator
The assignment operator (=) assigns a value to a variable:
int a = 10;
1.17 Arithmetic Operators
Java provides the following arithmetic operators:
Addition: +
Subtraction: -
Multiplication: *
Division: /
Modulus: %
Example:
int sum = 10 + 5; // sum is 15
1.18 Practice Questions
1. Write a Java program to print "Hello, World!".
2. Declare and initialize variables of different data types.
3. Write a program to calculate the sum, difference, product, and quotient of
two numbers.
4. Create a program to demonstrate type casting and type conversion.
1.19 Summary
In this section, we covered the basics of Java, including its history, setup,
architecture, and foundational concepts like variables, data types, and
operators. We also explored how to work with Java tools and editors.
1.20 Class Work
1. Write a program to swap two numbers using a temporary variable.
2. Write a program to calculate the area of a circle using the formula Area =
pi * r^2.
3. Create a Java program that prints the Fibonacci series up to 10 terms.
4. Write a program to check whether a number is even or odd.
Answers to questions.
1. Print "Hello, World!"
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
2. Declare and initialize variables of different data types
public class VariableTypes {
public static void main(String[] args) {
int age = 25;
double height = 5.9;
char grade = 'A';
boolean isPassed = true;
String name = "John";
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Grade: " + grade);
System.out.println("Passed: " + isPassed);
System.out.println("Name: " + name);
}
}
3. Arithmetic Operations
public class ArithmeticOperations {
public static void main(String[]args) {
int num1 = 15;
int num2 = 5;
int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
double quotient = (double) num1 / num2;
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
}
}
4. Type Casting and Type Conversion
public class TypeCasting {
public static void main(String[] args) {
// Implicit type conversion (widening)
int num = 10;
double doubleNum = num;
System.out.println("Implicit Conversion (int to double): " + doubleNum);
// Explicit type casting (narrowing)
double pi = 3.14159;
int roundedPi = (int) pi;
System.out.println("Explicit Conversion (double to int): " + roundedPi);
}
}
5. Swap Two Numbers
public class SwapNumbers {
public static void main(String[] args) {
int a = 5, b = 10;
System.out.println("Before Swap: a = " + a + ", b = " + b);
int temp = a;
a = b;
b = temp;
System.out.println("After Swap: a = " + a + ", b = " + b);
}
}
6. Calculate Area of a Circle
public class CircleArea {
public static void main(String[] args) {
double radius = 7.0; // Hardcoded radius
double area = Math.PI * Math.pow(radius, 2);
System.out.println("Area of the circle: " + area);
}
}
7. Fibonacci Series
public class FibonacciSeries {
public static void main(String[] args) {
int n = 10, firstTerm = 0, secondTerm = 1;
System.out.println("Fibonacci Series up to " + n + " terms:");
for (int i = 1; i <= n; i++) {
System.out.print(firstTerm + " ");
// Calculate the next term
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
8. Check Whether a Number is Even or Odd
public class EvenOddCheck {
public static void main(String[] args) {
int number = 8; // Hardcoded number
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
}
}