Certainly! Java is a widely-used, object-oriented programming language known for its portability, performance, and extensive libraries. Here’s a rundown of some of the fundamental concepts and features of Java with code examples:
Concept:
Java programs are written in classes and methods. The main method (public static void main(String[] args)
) is the entry point for any Java application.
Code Example:
java// Basic Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld
defines a class namedHelloWorld
.public static void main(String[] args)
is the main method where execution begins.System.out.println("Hello, World!");
prints the text to the console.
2. Variables and Data Types
Concept: Java is a statically typed language, meaning you must declare the type of variables explicitly.
Code Example:
java// Variables and Data Types
public class DataTypes {
public static void main(String[] args) {
int age = 30; // Integer
double salary = 75000.50; // Floating-point number
char grade = 'A'; // Character
boolean isEmployed = true; // Boolean
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
System.out.println("Employed: " + isEmployed);
}
}
Explanation:
int
,double
,char
, andboolean
are different data types in Java.- Variables are declared with a type and initialized with a value.
3. Control Flow
Concept:
Java uses control flow statements like if
, else
, for
, while
, and do-while
to control the execution of code based on conditions or loops.
Code Example:
java// Control Flow
public class ControlFlow {
public static void main(String[] args) {
int temperature = 28;
if (temperature > 30) {
System.out.println("It's a hot day.");
} else if (temperature > 20) {
System.out.println("It's a pleasant day.");
} else {
System.out.println("It's a cold day.");
}
// For Loop
for (int i = 0; i < 5; i++) {
System.out.println("Index: " + i);
}
// While Loop
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
}
}
Explanation:
if-else
constructs allow decision-making based on conditions.for
andwhile
loops are used for iteration.
4. Functions (Methods)
Concept: Methods in Java are used to perform tasks. They can take parameters and return values.
Code Example:
java// Methods
public class MethodsExample {
public static void main(String[] args) {
int sum = add(5, 3);
System.out.println("Sum: " + sum);
greet("Alice");
}
// Method to add two numbers
public static int add(int a, int b) {
return a + b;
}
// Method to greet a person
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}
Explanation:
add
method takes two integers and returns their sum.greet
method prints a greeting message.
5. Classes and Objects
Concept: Java is an object-oriented language. Classes are blueprints for creating objects.
Code Example:
java// Classes and Objects
public class Person {
// Attributes
String name;
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method
public void introduce() {
System.out.println("My name is " + name + " and I am " + age + " years old.");
}
public static void main(String[] args) {
// Creating an object
Person person1 = new Person("John", 25);
person1.introduce();
}
}
Explanation:
Person
class has attributesname
andage
, a constructor to initialize them, and a methodintroduce
to print details.- An object of
Person
is created and used to call theintroduce
method.
6. Inheritance
Concept: Inheritance allows one class (subclass) to inherit fields and methods from another class (superclass).
Code Example:
java// Inheritance
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Method from Animal class
myDog.bark(); // Method from Dog class
}
}
Explanation:
Dog
class extendsAnimal
, inheriting itseat
method and adding its ownbark
method.- The
myDog
object demonstrates both inherited and own methods.
7. Exception Handling
Concept:
Exception handling in Java helps manage errors gracefully using try
, catch
, and finally
.
Code Example:
java// Exception Handling
public class ExceptionHandling {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero.");
} finally {
System.out.println("This block always executes.");
}
}
}
Explanation:
try
block contains code that may throw an exception.catch
block handles specific exceptions.finally
block executes regardless of whether an exception was thrown or not.
8. File Handling
Concept:
Java provides classes for reading from and writing to files using the java.io
package.
Code Example:
javaimport java.io.*;
public class FileHandling {
public static void main(String[] args) {
// Writing to a file
try (FileWriter writer = new FileWriter("example.txt")) {
writer.write("Hello, file!");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
}
// Reading from a file
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line = reader.readLine();
System.out.println("File content: " + line);
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
}
}
}
Explanation:
FileWriter
is used to write data to a file.BufferedReader
andFileReader
are used to read data from a file.- The
try-with-resources
statement ensures proper closing of file resources.
0 Comments