Introduction To Java Programming
Introduction To Java Programming
Introduction To Java Programming
Definition:
Origin:
Java was developed by James Gosling and his team at Sun Microsystems in the early 1990s, with its
first release in 1995. Initially, it was conceived as part of the "Green Project," aimed at developing
software for digital devices like set-top boxes. Over time, Java evolved into a general-purpose
programming language. In 2010, Sun Microsystems was acquired by Oracle Corporation, which now
maintains and supports Java.
2. Platform Independence: Through the Java Virtual Machine (JVM), Java programs can run on any
operating system without modification.
4. Automatic Memory Management: Java uses garbage collection to automatically manage memory,
which simplifies programming and reduces memory leaks.
5. Robust and Secure: Java emphasizes early error checking, runtime checking, and has built-in
security features that make it reliable for developing applications across different environments.
Benefits:
- Wide Community Support: Java has a large and active community that contributes libraries,
frameworks, and tools, which enhances development productivity.
- Scalability: Java is suitable for small applications and large-scale systems alike, making it a versatile
choice for various project sizes.
- Rich API: Java provides a vast array of standard libraries (APIs) for different tasks like networking,
data structures, and graphical interfaces, which reduces the need for third-party tools.
- Security Features: Java has built-in security features such as bytecode verification, cryptography,
and access control, making it suitable for applications requiring robust security.
Application Areas:
1. Web Development: Java-based frameworks like Spring and Hibernate are widely used in server-
side applications.
Page 1 of 16
2. Mobile Applications: Java is the foundation for Android app development, the world’s most
popular mobile OS.
3. Enterprise Solutions: Java is heavily used in large enterprise systems for backend services and
middleware.
4. Embedded Systems: Java is deployed in smart cards, sensors, and other IoT devices.
5. Big Data: Java plays a crucial role in the big data ecosystem through tools like Hadoop.
6. Cloud Computing: Java is integral to cloud-based applications and services due to its scalability.
System.out.println("Hello, World!");
1. Comments:
- Comments are used to explain code and are ignored by the compiler. Single-line comments start
with //, while multi-line comments are enclosed between / and /. They are useful for making the
code more understandable to humans.
2. Class Declaration:
- Every Java program must have at least one class. The class name must match the file name (in this
case, HelloWorld.java). The class keyword is followed by the class name, which is capitalized by
convention.
- The public keyword makes the class accessible to other classes, and this is important for the entry
point of the program.
3. Main Method:
- The main method is the entry point of every Java application. When the program starts, this
method is executed. Here’s a breakdown of the keywords:
- public: This means the method can be accessed from outside the class.
Page 2 of 16
- sta
tic: This means the method belongs to the class itself, not an instance of the class.
- void: This means the method does not return any value.
- main: This is the method name, and it must be spelled exactly as shown because it’s predefined
in Java.
- String[] args: This is an array of String objects, which can store command-line arguments when
the program is executed.
4. Statements:
- This line is an example of a statement in Java. The System.out.println() method prints a message
to the console. Every statement in Java must end with a semicolon (;).
- System.out refers to the standard output stream, and println is a method that prints the message
to the console followed by a new line.
Key Points:
- Braces {}: Curly braces define the start and end of code blocks. In this case, the body of the class
and the method is enclosed within braces.
- Indentation: Proper indentation is not required by the Java compiler but is highly recommended
for code readability.
if (args.length > 0) {
} else {
System.out.println("Hello, World!");
In this example:
- The program checks if any command-line arguments were passed (i.e., if the length of args is
greater than 0). If a name is provided as an argument (e.g., java Greeting John), it prints a
personalized greeting like "Hello, John!".
Page 3 of 16
Summary of Structure:
This structure ensures that Java programs are well-organized and executable across different
platforms.
In Java programming, tokens are the smallest elements or building blocks of a program that the Java
compiler interprets. These tokens represent the basic units of code.
1. Keywords
These are predefined, reserved words in Java that have a specific meaning and purpose. Keywords
cannot be used as identifiers (names for variables, classes, methods, etc.). Examples of Java
keywords include:
abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double,
else, enum, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface,
long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch,
synchronized, this, throw, throws, transient, try, void, volatile
2. Identifiers
In Java, identifiers are names given to various elements in a program, such as variables, methods,
classes, objects, and functions. These names are used to uniquely identify elements within a program
and allow the programmer to reference them throughout the code. Identifiers are critical for writing
understandable and maintainable code.
Java has specific rules that govern how identifiers can be named:
The first character of an identifier must be a letter (A-Z or a-z), an underscore (_), or a dollar sign
($). It cannot start with a digit.
Examples:
After the first character, the identifier can include any combination of letters, digits, underscores, or
dollar signs.
Examples:
Page 4 of 16
- Valid: myVar123, total_amount, $value99
Java treats uppercase and lowercase letters as different, so age and Age are considered two distinct
identifiers.
Examples:
- Invalid: (Case-sensitivity is always valid but may cause confusion if not handled properly.)
Identifiers cannot use any of Javas reserved keywords, such as int, class, for, if, etc.
Examples:
- Valid: className, ifCondition, forLoop (modifying keywords to make them valid identifiers)
Java does not impose a specific limit on the length of identifiers, but it’s recommended to keep
them reasonably short and meaningful for better readability.
Examples:
- Valid: thisIsAVeryLongVariableNameThatIsStillAllowed
Identifiers cannot include spaces. If multiple words are needed in an identifier, programmers often
use camelCase or snake_case notation.
Examples:
Examples:
Page 5 of 16
}
- Use meaningful names that reflect the purpose of the variable or function. For example,
customerName is better than x.
- Follow naming conventions: variables and methods typically start with a lowercase letter (e.g.,
calculateTotal), while class names start with an uppercase letter (e.g., Employee).
3. Literals
Literals represent fixed values directly used in the program. Java supports several types of literals:
- Character literals: Single characters enclosed in single quotes, e.g., 'A', '1'.
- String literals: Sequences of characters enclosed in double quotes, e.g., "Hello, World!".
4. Operators
In Java, operators are special symbols or keywords used to perform operations on variables and
values. Operators can be classified into several categories based on their functionality:
Arithmetic Operators
Relational (Comparison) Operators
Logical Operators
Bitwise Operators
Assignment Operators
Unary Operators
Ternary (Conditional) Operator
Below is a detailed explanation of each type of operator, along with simple Java programs to
demonstrate their usage.
a. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such as addition,
subtraction, multiplication, and division.
| Operator | Description |
|----------|------------------|
| + | Addition |
| - | Subtraction |
| | Multiplication |
| / | Division |
| % | Modulus (remainder) |
Example:
Page 6 of 16
System.out.println("Subtraction: " + (a - b)); // 5
System.out.println("Multiplication: " + (a b)); // 50
System.out.println("Division: " + (a / b)); // 2
System.out.println("Modulus: " + (a % b)); // 0
}
}
b. Relational (Comparison) Operators
Relational operators are used to compare two values or expressions. They return a boolean result
(true or false).
| Operator | Description |
|----------|------------------------------|
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
Example:
Page 7 of 16
Bitwise operators perform bit-level operations on data. They work on binary representations of
numbers.
| Operator | Description |
|----------|-------------------------|
| & | Bitwise AND |
| | | Bitwise OR |
| ^ | Bitwise XOR (Exclusive OR) |
| ~ | Bitwise NOT |
| << | Left shift |
| >> | Right shift |
Example:
Page 8 of 16
| + | Unary plus (usually redundant) |
| - | Unary minus (negates a value) |
| ++ | Increment (adds 1 to a value) |
| -- | Decrement (subtracts 1 from a value) |
| ! | Logical NOT (inverts a boolean value) |
Example:
public class UnaryExample {
public static void main(String[] args) {
int a = 10;
System.out.println("a: " + a); // 10
System.out.println("++a: " + (++a)); // 11 (Pre-increment)
System.out.println("a--: " + (a--)); // 11 (Post-decrement)
System.out.println("New a: " + a); // 10
}
}
g. Ternary Operator
The ternary operator (also called conditional operator) is a shorthand for an if-else statement. It
takes three operands.
| Operator | Description |
|----------|-----------------------------------|
| ?: | Conditional (ternary) operator |
Example:
public class TernaryExample {
public static void main(String[] args) {
int a = 10, b = 20;
int max = (a > b) ? a : b; // If a > b, assign a to max, otherwise assign b
System.out.println("Maximum: " + max); // 20
}
}
5. Separators
Separators are symbols that help define the structure of a program. Common separators include:
- Braces {}: Used to define code blocks (e.g., class or method definitions).
Example:
Page 9 of 16
6. Comments
Although not part of the executable code, comments are tokens used to document the code. They
are ignored by the compiler and come in two forms:
- Single-line comments: Start with // and continue to the end of the line.
Example:
This is a
multi-line comment
7. Punctuation (Delimiters)
Java uses punctuation marks or delimiters to define and separate code elements. These include:
The Scanner class in Java provides various functions to read different types of input. Here are some
common methods:
a. Importing Scanner: To use the `Scanner` class, you need to import it from the `java.util` package.
import java.util.Scanner;
Page 10 of 16
c. Reading Input Types:
scanner.close();
Example Code
import java.util.Scanner;
System.out.println("Hello, " + name + ". You are " + age + " years old.");
scanner.close();
Java Operators
Java operators are symbols used to perform operations on variables and values. Here’s a detailed
overview of the different categories of operators in Java, including descriptions and examples.
a. Arithmetic Operators
int a = 10, b = 5;
Page 11 of 16
System.out.println("Multiplication: " + (a * b)); // 50
b. Relational Operators
These operators are used to compare two values and return a boolean result.
- Greater than (`>`): Checks if the left operand is greater than the right.
- Less than (`<`): Checks if the left operand is less than the right.
- Greater than or equal to (`>=`): Checks if the left operand is greater than or equal to the right.
- Less than or equal to (`<=`): Checks if the left operand is less than or equal to the right.
c. Logical Operators
d. Bitwise Operators
These operators perform operations on bits and are used for bit-level manipulation.
- Bitwise AND (`&`): Compares each bit of two operands and returns 1 if both bits are 1.
Page 12 of 16
int c = 5; // 0101 in binary
- Bitwise OR (`|`): Compares each bit of two operands and returns 1 if at least one bit is 1.
- Bitwise XOR (`^`): Compares each bit of two operands and returns 1 if the bits are different.
- Left Shift (`<<`): Shifts bits to the left, filling with zeros.
e. Assignment Operators
These operators assign values to variables and can also combine arithmetic operations.
- Simple Assignment (`=`): Assigns the right-hand operand to the left-hand operand.
int d = 5;
- Add and Assign (`+=`): Adds the right operand to the left operand and assigns the result.
d += 3; // Equivalent to d = d + 3
- Subtract and Assign (`-=`): Subtracts the right operand from the left operand and assigns the result.
d -= 2; // Equivalent to d = d - 2
- Multiply and Assign (`*=`): Multiplies the left operand by the right operand and assigns the result.
d *= 2; // Equivalent to d = d * 2
- Divide and Assign (`/=`): Divides the left operand by the right operand and assigns the result.
d /= 2; // Equivalent to d = d / 2
f. Ternary Operator
- Example:
```java
Page 13 of 16
System.out.println("Max: " + max); // 10
Control structures in Java determine the flow of control in a program. They can be categorized into
three main types: conditional statements, looping statements, and branching statements.
a. Conditional Statements
These statements allow the program to execute different blocks of code based on certain conditions.
int a = 10;
if (a > 5) {
if (a > 5) {
} else {
System.out.println("a is 5 or less");
if (a > 10) {
} else if (a > 5) {
} else {
System.out.println("a is 5 or less");
- Switch Statement: Allows a variable to be tested for equality against a list of values (cases).
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
Page 14 of 16
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
b. Looping Statements
Looping statements are used to execute a block of code repeatedly based on a condition.
int j = 0;
while (j < 5) {
j++;
- Do-While Loop: Similar to the while loop, but guarantees that the code block is executed at least
once.
int k = 0;
do {
k++;
c. Branching Statements
Branching statements are used to change the flow of control within loops or switch statements.
Page 15 of 16
for (int i = 0; i < 10; i++) {
if (i == 5) {
- Continue Statement: Skips the current iteration and moves to the next iteration of the loop.
if (i % 2 == 0) {
- Return Statement: Exits from the current method and optionally returns a value.
Page 16 of 16