Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Introduction To Java Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

INTRODUCTION TO JAVA PROGRAMMING

Definition:

Java is a high-level, class-based, object-oriented programming language designed to have as few


implementation dependencies as possible. It allows developers to write code that can run on all
platforms that support Java without needing recompilation, making it a "write once, run anywhere"
(WORA) language.

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.

Features of Java Programming Language:

1. Object-Oriented: Everything in Java is considered an object, which models real-world entities.

2. Platform Independence: Through the Java Virtual Machine (JVM), Java programs can run on any
operating system without modification.

3. Multithreading: Java supports multithreaded programming, allowing developers to build


applications that can perform multiple tasks simultaneously.

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:

- Cross-Platform Capability: Java’s platform independence allows programs to run on different


hardware architectures and operating systems without modification.

- 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:

Java is used in various domains due to its flexibility and scalability:

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.

BASIC STRUCTURE OF A JAVA PROGRAM

Consider the following Sample Code:

// This is a simple Java program

public class HelloWorld {

public static void main(String[] args) {

// Print "Hello, World!" to the console

System.out.println("Hello, World!");

Breakdown of the Structure:

1. Comments:

- Example: // This is a simple Java program

- 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:

- Example: public class HelloWorld

- 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:

- Example: public static void main(String[] args)

- 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:

- Example: System.out.println("Hello, World!");

- 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.

Example with Command-Line Arguments:

Here's an extended version of the program that uses command-line arguments:

public class Greeting {

public static void main(String[] args) {

// Check if a name was provided as an argument

if (args.length > 0) {

System.out.println("Hello, " + args[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:

 Package Declaration (optional): Declares a package if the class belongs to one.


 Import Statements (optional): Import necessary classes from other packages.
 Class Declaration: Every program needs at least one class.
 Main Method: The entry point of the program where execution starts.
 Statements: The code that performs actions, such as printing or calculations.

This structure ensures that Java programs are well-organized and executable across different
platforms.

TOKENS IN JAVA PROGRAMMING

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.

Java's tokens can be categorized into several types:

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.

Rules for Identifiers in Java

Java has specific rules that govern how identifiers can be named:

a. Must begin with a letter, underscore (_), or dollar sign ($):

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:

- Valid: _age, $salary, name

- Invalid: 1name, 123abc

b. Subsequent characters can be letters, digits, underscores, or dollar signs:

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

- Invalid: my-var (hyphen is not allowed)

c. Identifiers are case-sensitive:

Java treats uppercase and lowercase letters as different, so age and Age are considered two distinct
identifiers.

Examples:

- Valid: MyClass, myclass (two different identifiers)

- Invalid: (Case-sensitivity is always valid but may cause confusion if not handled properly.)

d. Cannot be a reserved keyword:

Identifiers cannot use any of Javas reserved keywords, such as int, class, for, if, etc.

Examples:

- Invalid: class, if, for (these are reserved keywords)

- Valid: className, ifCondition, forLoop (modifying keywords to make them valid identifiers)

e. No limit on identifier length:

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

f. Cannot contain whitespace:

Identifiers cannot include spaces. If multiple words are needed in an identifier, programmers often
use camelCase or snake_case notation.

Examples:

- Valid: totalAmount, user_age

- Invalid: total amount (contains a space)

Examples:

i. Variable identifier example:

int totalMarks; // valid identifier

double _salary; // valid identifier starting with an underscore

ii. Class identifier example:

public class StudentDetails { // valid identifier

public class 123Class { // invalid, starts with a digit

Page 5 of 16
}

Best Practices for Identifiers

- 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:

- Integer literals: Whole numbers, e.g., 10, 200.

- Floating-point literals: Decimal values, e.g., 10.5, 3.14.

- Boolean literals: Represent truth values true and false.

- 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:

public class ArithmeticExample {


public static void main(String[] args) {
int a = 10, b = 5;
System.out.println("Addition: " + (a + b)); // 15

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:

public class RelationalExample {


public static void main(String[] args) {
int x = 10, y = 5;
System.out.println("x == y: " + (x == y)); // false
System.out.println("x != y: " + (x != y)); // true
System.out.println("x > y: " + (x > y)); // true
System.out.println("x < y: " + (x < y)); // false
}
}
c. Logical Operators
Logical operators are used to combine conditional expressions. They are mostly used with boolean
values.
| Operator | Description |
|----------|-------------------------|
| && | Logical AND (true if both conditions are true) |
| || | Logical OR (true if at least one condition is true) |
| ! | Logical NOT (negates the boolean value) |
Example:

public class LogicalExample {


public static void main(String[] args) {
boolean a = true, b = false;
System.out.println("a && b: " + (a && b)); // false
System.out.println("a || b: " + (a || b)); // true
System.out.println("!a: " + (!a)); // false
}
}
d. Bitwise Operators

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:

public class BitwiseExample {


public static void main(String[] args) {
int x = 5; // Binary: 0101
int y = 3; // Binary: 0011
System.out.println("x & y: " + (x & y)); // Binary AND (Result: 0001 => 1)
System.out.println("x | y: " + (x | y)); // Binary OR (Result: 0111 => 7)
System.out.println("x ^ y: " + (x ^ y)); // Binary XOR (Result: 0110 => 6)
System.out.println("~x: " + (~x)); // Binary NOT (Result: 1010 => -6)
}
}
e. Assignment Operators
Assignment operators are used to assign values to variables.
| Operator | Description |
|----------|-------------------|
| = | Simple assignment |
| += | Add and assign |
| -= | Subtract and assign |
| = | Multiply and assign |
| /= | Divide and assign |
| %= | Modulus and assign |
Example:

public class AssignmentExample {


public static void main(String[] args) {
int a = 10;
a += 5; // a = a + 5
System.out.println("a += 5: " + a); // 15
a = 2; // a = a 2
System.out.println("a = 2: " + a); // 30
}
}
f. Unary Operators
Unary operators are used with a single operand to perform various operations like
incrementing/decrementing a value, negating a value, or inverting a boolean value.
| Operator | Description |
|----------|---------------------------|

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).

- Parentheses (): Used in method declarations and function calls.

- Semicolon ;: Used to terminate statements.

- Comma ,: Used to separate variables or arguments in method calls.

Example:

public class Example {

public static void main(String[] args) {

int x = 10; // semicolon separates the statement

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.

- Multi-line comments: Enclosed between / and /.

Example:

// This is a single-line comment

This is a

multi-line comment

7. Punctuation (Delimiters)

Java uses punctuation marks or delimiters to define and separate code elements. These include:

- []: Used to declare arrays or access array elements.

- . (dot): Used to access members (methods or variables) of classes or objects.

- Example: System.out.println("Hello"); (accessing the println method of out object).

Java Input Using Scanner Variables

To input values in Java, we need to import the Scanner class.

The Scanner class in Java provides various functions to read different types of input. Here are some
common methods:

i. nextLine(): Reads a line of text.

ii. nextInt(): Reads an integer value.

iii. nextDouble(): Reads a double value.

iv. nextBoolean(): Reads a boolean value.

v. next(): Reads the next complete token.

vi. hasNext(): Checks if there is another token available.

vii. close(): Closes the scanner to free resources.

These methods facilitate flexible input handling in Java applications.

a. Importing Scanner: To use the `Scanner` class, you need to import it from the `java.util` package.

import java.util.Scanner;

b. Creating Scanner Object: Initialize a `Scanner` object to read input.

Scanner scanner = new Scanner(System.in);

Page 10 of 16
c. Reading Input Types:

- String: `String name = scanner.nextLine();`

- Integer: `int age = scanner.nextInt();`

- Double: `double salary = scanner.nextDouble();`

d. Closing Scanner: Always close the `Scanner` to free resources.

scanner.close();

Example Code

import java.util.Scanner;

public class InputExample {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");

String name = scanner.nextLine();

System.out.print("Enter your age: ");

int age = scanner.nextInt();

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

These operators perform basic mathematical operations.

- Addition (`+`): Adds two operands.

int a = 10, b = 5;

System.out.println("Addition: " + (a + b)); // 15

- Subtraction (`-`): Subtracts the second operand from the first.

System.out.println("Subtraction: " + (a - b)); // 5

- Multiplication (`*`): Multiplies two operands.

Page 11 of 16
System.out.println("Multiplication: " + (a * b)); // 50

- Division (`/`): Divides the first operand by the second.

System.out.println("Division: " + (a / b)); // 2

- Modulus (`%`): Returns the remainder of a division.

System.out.println("Modulus: " + (a % b)); // 0

b. Relational Operators

These operators are used to compare two values and return a boolean result.

- Equal to (`==`): Checks if two operands are equal.

System.out.println("Is a equal to b? " + (a == b)); // false

- Not equal to (`!=`): Checks if two operands are not equal.

System.out.println("Is a not equal to b? " + (a != b)); // true

- Greater than (`>`): Checks if the left operand is greater than the right.

System.out.println("Is a > b? " + (a > b)); // true

- Less than (`<`): Checks if the left operand is less than the right.

System.out.println("Is a < b? " + (a < b)); // false

- Greater than or equal to (`>=`): Checks if the left operand is greater than or equal to the right.

System.out.println("Is a >= b? " + (a >= b)); // true

- Less than or equal to (`<=`): Checks if the left operand is less than or equal to the right.

System.out.println("Is a <= b? " + (a <= b)); // false

c. Logical Operators

These operators are used to combine multiple boolean expressions.

- Logical AND (`&&`): Returns true if both operands are true.

boolean x = true, y = false;

System.out.println("x AND y: " + (x && y)); // false

- Logical OR (`||`): Returns true if at least one operand is true.

System.out.println("x OR y: " + (x || y)); // true

- Logical NOT (`!`): Reverses the logical state of its operand.

System.out.println("NOT x: " + (!x)); // false

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

System.out.println("Bitwise AND: " + (c & 3)); // 1 (0001 in binary)

- Bitwise OR (`|`): Compares each bit of two operands and returns 1 if at least one bit is 1.

System.out.println("Bitwise OR: " + (c | 3)); // 7 (0111 in binary)

- Bitwise XOR (`^`): Compares each bit of two operands and returns 1 if the bits are different.

System.out.println("Bitwise XOR: " + (c ^ 3)); // 6 (0110 in binary)

- Bitwise Complement (`~`): Inverts all bits of the operand.

System.out.println("Bitwise Complement: " + (~c)); // -6

- Left Shift (`<<`): Shifts bits to the left, filling with zeros.

System.out.println("Left Shift: " + (c << 1)); // 10 (1010 in binary)

- Right Shift (`>>`): Shifts bits to the right.

System.out.println("Right Shift: " + (c >> 1)); // 2 (0010 in binary)

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

System.out.println("Value of d: " + d); // 8

- 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

The ternary operator is a shorthand for the `if-else` statement.

- Syntax: `condition ? expression1 : expression2`

- Example:

```java

int max = (a > b) ? a : b;

Page 13 of 16
System.out.println("Max: " + max); // 10

Java Control Structures

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.

- If Statement: Executes a block of code if a specified condition is true.

int a = 10;

if (a > 5) {

System.out.println("a is greater than 5");

- If-Else Statement: Provides an alternative block of code if the condition is false.

if (a > 5) {

System.out.println("a is greater than 5");

} else {

System.out.println("a is 5 or less");

- Else-If Ladder: Tests multiple conditions.

if (a > 10) {

System.out.println("a is greater than 10");

} else if (a > 5) {

System.out.println("a is greater than 5 but less than or equal to 10");

} 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.

- For Loop: Repeats a block of code a fixed number of times.

for (int i = 0; i < 5; i++) {

System.out.println("Iteration: " + i);

- While Loop: Repeats a block of code while a condition is true.

int j = 0;

while (j < 5) {

System.out.println("Iteration: " + j);

j++;

- Do-While Loop: Similar to the while loop, but guarantees that the code block is executed at least
once.

int k = 0;

do {

System.out.println("Iteration: " + k);

k++;

} while (k < 5);

c. Branching Statements

Branching statements are used to change the flow of control within loops or switch statements.

- Break Statement: Exits the loop or switch statement immediately.

Page 15 of 16
for (int i = 0; i < 10; i++) {

if (i == 5) {

break; // exits the loop when i is 5

System.out.println("i: " + i);

- Continue Statement: Skips the current iteration and moves to the next iteration of the loop.

for (int i = 0; i < 10; i++) {

if (i % 2 == 0) {

continue; // skips even numbers

System.out.println("i: " + i);

- Return Statement: Exits from the current method and optionally returns a value.

public int sum(int x, int y) {

return x + y; // returns the sum of x and y

Page 16 of 16

You might also like