javadocuments
javadocuments
Introduction to Java
2. Features of Java
java
Copy code
a. byte
java
Copy code
b. short
java
Copy code
c. int
java
Copy code
}
d. long
java
Copy code
e. float
java
Copy code
f. double
java
Copy code
g. char
Stores a single character.
java
Copy code
h. boolean
java
Copy code
a. String
java
Copy code
}
b. Array
java
Copy code
c. Class
java
Copy code
class Student {
String name;
int age;
void display() {
student.name = "John";
student.age = 20;
student.display();
}
d.interface
interface Animal {
System.out.println("Dog barks");
dog.sound();
dog.eat();
}
5.OPERATORS
1. Arithmetic Operators
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 10 / 2 5
% Modulus (Remainder) 10 % 3 1
Example:
java
Copy code
int a = 10, b = 3;
== Equal to 5 == 5 true
Example:
java
Copy code
3. Logical Operators
|| Logical OR ` Logical OR
Example:
java
Copy code
4. Assignment Operators
Example:
java
Copy code
int a = 10;
a += 5;
a -= 3;
System.out.println("a after a -= 3: " + a);
5. Bitwise Operators
` ` Bitwise OR `5
~ Bitwise Complement ~5 -6
Example:
java
Copy code
int x = 5, y = 3;
6. Unary Operators
Work with a single operand.
+ Unary plus +x x
- Unary minus -x -x
7. Ternary Operator
Syntax:
java
Copy code
Example:
java
Copy code
6.CONDITIONAL STATEMENTS
1. if Statement
java
Copy code
if (condition) {
Example:
java
Copy code
if (number > 5) {
2. if-else Statement
Executes one block of code if the condition is true and another block if it is false.
Syntax:
java
Copy code
if (condition) {
} else {
Example:
java
Copy code
int number = 4;
if (number % 2 == 0) {
} else {
3. if-else-if Ladder
Syntax:
java
Copy code
if (condition1) {
} else if (condition2) {
} else {
Example:
java
Copy code
System.out.println("Grade: A");
System.out.println("Grade: B");
} else {
System.out.println("Grade: F");
4. switch Statement
Tests a variable against multiple values and executes a block of code that matches the value.
Syntax:
java
Copy code
switch (expression) {
case value1:
break;
case value2:
break;
// more cases...
default:
Example:
java
Copy code
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
5. Nested if Statements
Syntax:
java
Copy code
if (condition1) {
if (condition2) {
Example:
java
Copy code
if (hasLicense) {
} else {
} else {
7.LOOP STATEMENTS
1. for Loop
Syntax:
java
Copy code
// Code to be executed
Example:
java
Copy code
2. while Loop
The while loop repeats a block of code as long as a specified condition is true.
Syntax:
java
Copy code
while (condition) {
// Code to be executed
Example:
java
Copy code
int i = 1;
while (i <= 5) {
i++;
}
3. do-while Loop
The do-while loop executes the code block once, then checks the condition, and repeats if true.
Syntax:
java
Copy code
do {
// Code to be executed
} while (condition);
Example:
java
Copy code
int i = 1;
do {
i++;
java
Copy code
if (i == 3) {
The continue statement skips the current iteration and jumps to the next one.
java
Copy code
int i = 0;
while (i < 5) {
i++;
if (i == 3) {
A switch statement can be used inside loops to control the flow based on a variable's value.
java
Copy code
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
break;
java
Copy code
if (i % 2 == 0) {
if (i > 7) {
}
System.out.println("Odd number: " + i);
Summary
switch: Provides a structured way to handle multiple cases, often within loops.
8.Methods in Java
Methods in Java are blocks of code designed to perform a specific task. They help make code
modular, reusable, and easy to maintain.
Syntax:
java
Copy code
returnType methodName(parameters) {
Example:
java
Copy code
2. Method Parameters
Java always uses pass-by-value, meaning a copy of the variable is passed to the method. Any changes
made inside the method do not affect the original value.
Example:
java
Copy code
int x = 20;
obj.changeValue(x);
Objects are passed by reference. Changes made to the object inside the method affect the original
object.
Example:
java
Copy code
class Box {
int length = 5;
obj.modify(box);
Methods can return values. The return type specifies the data type of the value returned by the
method.
Example:
java
Copy code
4. Method Overloading
Method overloading allows multiple methods with the same name but different parameter lists.
Example:
java
Copy code
// Overloaded methods
return a + b;
return a + b;
5.Recursion in Java
Recursion is a technique in which a method calls itself to solve smaller instances of a problem. Every
recursive method must have a base case, which stops the recursion when a condition is met, and a
recursive step, which reduces the problem size.
java
Copy code
returnType methodName(parameters) {
1. Factorial Calculation
Example:
java
Copy code
if (n == 1) { // Base case
return 1;
}
}
9.Strings in Java
The String class in Java represents a sequence of characters and is widely used for handling text.
Strings in Java are immutable, meaning once a string object is created, its value cannot be changed.
The String class is part of the java.lang package and provides various methods to manipulate strings.
java
Copy code
System.out.println(str.length()); // Output: 5
java
Copy code
System.out.println(str.charAt(1)); // Output: e
3. substring(int start): Returns a new string starting from the specified index to the end of the
string.
java
Copy code
4. substring(int start, int end): Returns a new string from the start index to end - 1 index.
java
Copy code
java
Copy code
java
Copy code
java
Copy code
java
Copy code
String Concatenation
java
Copy code
java
Copy code
sb.append("Hello");
sb.append(" ");
sb.append("World");
StringBuilder is more efficient than using the + operator because it does not create a new string
object each time a new string is added.
String Comparison
java
Copy code
2. == (Reference comparison): Compares the references of the two strings (not the content).
java
Copy code
o Returns a negative integer if the first string is lexicographically less than the second.
o Returns a positive integer if the first string is lexicographically greater than the
second.
java
Copy code
In Java, strings are immutable. Once a string object is created, its value cannot be changed.
When you modify a string, a new string object is created. For example:
java
Copy code
If you perform multiple modifications to a string, it creates a new object each time, which
can be inefficient for large strings or in loops. This is one reason why using StringBuilder or
StringBuffer is preferred for such cases.
An exception is an event that disrupts the normal flow of the program. It can occur due to errors like
dividing by zero, accessing an invalid array index, or other unforeseen circumstances during the
execution of the program. Java provides a robust mechanism to handle these exceptions so that the
program can continue executing even after an error occurs.
NullPointerException: Occurs when an object reference is null, but methods or fields are
accessed.
1. try Block: Contains the code that may throw an exception. It is followed by one or more
catch blocks or a finally block.
java
Copy code
try {
2. catch Block: Catches exceptions thrown by the try block and handles them.
java
Copy code
catch (ArithmeticException e) {
3. finally Block: This block is always executed after the try-catch block, regardless of whether an
exception occurred or not. It is typically used to close resources like file streams or database
connections.
java
Copy code
finally {
java
Copy code
try {
} catch (ExceptionType e) {
Example:
java
Copy code
try {
} catch (ArrayIndexOutOfBoundsException e) {
The finally block is always executed after the try-catch blocks, even if no exception occurs or if an
exception is caught. It is generally used for cleaning up resources (e.g., closing files or releasing
database connections).
Example:
java
Copy code
try {
int result = 10 / 2;
} catch (ArithmeticException e) {
} finally {
Output:
sql
Copy code
Result: 5
Types of Exceptions
1. Checked Exceptions:
o These exceptions are checked at compile-time. The program will not compile unless
these exceptions are either caught using a try-catch block or declared to be thrown.
o These exceptions must be handled or declared in the method signature using the
throws keyword.
Example:
java
Copy code
try {
} catch (IOException e) {
o These exceptions are not checked at compile-time. These are usually caused by
programming bugs and do not need to be explicitly handled or declared.
o Examples: NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException.
Example:
java
Copy code
try {
} catch (ArithmeticException e) {
Throwing Exceptions
You can throw exceptions manually using the throw keyword. This is often used to enforce certain
conditions or validate input.
Syntax:
java
Copy code
Example:
java
Copy code
System.out.println("Age is valid");
throw Keyword
The throw keyword is used to explicitly throw an exception in your program. It can throw both
checked and unchecked exceptions.
Example:
java
Copy code
try {
} catch (Exception e) {
The throws keyword is used in a method signature to declare that a method may throw one or more
exceptions. This is typically used with checked exceptions, indicating that the calling method should
handle or declare the exception.
Syntax:
java
Copy code
Example:
java
Copy code
fr.read();
In this case, the readFile() method declares that it might throw an IOException, and it must be either
caught or declared by the caller.
Creating Custom Exceptions
You can create your own exception classes by extending the Exception class for checked exceptions
or RuntimeException for unchecked exceptions.
Example:
java
Copy code
super(message);
try {
} catch (CustomException e) {
Output:
vbnet
Copy code
To read user input from the console, Java provides various classes, with the most commonly used
being the Scanner class. This class can read input from various sources such as the keyboard
(System.in).
The Scanner class in java.util is used to capture user input. Below is an example demonstrating how
to use Scanner to read different types of input.
java
Copy code
import java.util.Scanner;
System.out.println("Hello, " + name + ". You are " + age + " years old.");
scanner.close();
Outputting Data
In Java, you can output data to the console using the System.out object, which provides methods
such as print() and println().
Example:
java
Copy code
System.out.print("World!"); // No newline
Output:
vbnet
Copy code
java
Copy code
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
try {
// Create FileReader object to read a file
String line;
System.out.println(line);
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
2. BufferedWriter: Writes text to a file efficiently by buffering the data before writing it.
java
Copy code
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
1. Reading Input:
o Use Scanner class to read data from the user (e.g., nextLine(), nextInt(),
nextDouble()).
2. Outputting Data:
3. File Reading:
4. File Writing:
o Use FileWriter and BufferedWriter to write data to a file.