Basic JAVA tutorial with code examples

 Certainly! Below is a comprehensive tutorial on Java, covering key concepts, examples, and code snippets to help you understand Java programming in detail. I will break this tutorial into several sections, starting from the basics and moving into more advanced topics.


1. Introduction to Java

Java is a high-level, object-oriented programming language designed for portability, performance, and security. It was created by James Gosling and Mike Sheridan at Sun Microsystems in 1995.

Key Features:

  • Object-Oriented: Everything in Java is an object.
  • Platform Independent: Write once, run anywhere (thanks to the Java Virtual Machine, JVM).
  • Simple and Robust: Java is designed to be easy to learn and provides automatic memory management (garbage collection).
  • Secure: Java is designed with security in mind, especially for online applications.

2. Setting Up the Java Environment

To get started with Java, you need to install the following:

  1. JDK (Java Development Kit): Contains tools necessary to write Java programs.
  2. IDE (Integrated Development Environment): Examples include Eclipse, IntelliJ IDEA, and NetBeans.

You can download the JDK from the official Oracle website: JDK Downloads.


3. Java Basic Syntax and Structure

3.1 Hello World Program

The simplest Java program is the "Hello World" program. Here is how it looks:

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }

Explanation:

  • public class HelloWorld: Defines a class named HelloWorld.
  • public static void main(String[] args): The main method, where the program starts execution.
  • System.out.println(): A method that prints output to the console.

3.2 Data Types

Java has a rich set of data types, both primitive and reference types.

Primitive Data Types:

  • int: Integer numbers
  • float: Floating-point numbers
  • double: Double precision floating-point numbers
  • char: Single character
  • boolean: True or false values

Example:

int x = 10; double y = 5.5; char letter = 'A'; boolean isJavaFun = true;

Reference Data Types:

  • String: A sequence of characters.
  • Arrays, Classes, Interfaces, etc.

Example:

String name = "Java";

4. Variables and Operators

4.1 Variables

In Java, a variable is a container for storing data values. It must be declared with a type before use.

Example:


int age = 25; // Declaring and initializing an integer variable String name = "John"; // Declaring and initializing a string variable

4.2 Operators

Java supports a variety of operators like arithmetic, relational, logical, etc.

  • Arithmetic Operators: +, -, *, /, %
  • Relational Operators: ==, !=, <, >, <=, >=
  • Logical Operators: &&, ||, !
  • Assignment Operator: =

Example:

int a = 5; int b = 2; int sum = a + b; // Arithmetic operator boolean isEqual = (a == b); // Relational operator boolean result = (a > b && b > 0); // Logical operator

5. Control Flow Statements

5.1 Conditional Statements

Java uses if, else if, and else for conditional execution.

Example:

int age = 20; if (age < 18) { System.out.println("You are a minor."); } else { System.out.println("You are an adult."); }

5.2 Switch-Case

The switch statement evaluates an expression and executes the corresponding case block.

Example:

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

Java supports several types of loops: for, while, and do-while.

For Loop Example:

for (int i = 1; i <= 5; i++) { System.out.println(i); }

While Loop Example:


int i = 1; while (i <= 5) { System.out.println(i); i++; }

Do-While Loop Example:

int i = 1; do { System.out.println(i); i++; } while (i <= 5);

6. Functions (Methods)

A method in Java is a block of code that performs a specific task. It is defined within a class and can be called to execute the task.

6.1 Method Definition

public class Calculator { public static int add(int a, int b) { return a + b; } public static void main(String[] args) { int result = add(5, 3); // Calling the add method System.out.println("Result: " + result); } }

Explanation:

  • public static int add(int a, int b): A method that takes two integers and returns their sum.
  • main: The entry point of the program.

6.2 Method Overloading

Java allows methods with the same name but different parameters.

class Display { public void show(int num) { System.out.println("Integer: " + num); } public void show(String str) { System.out.println("String: " + str); } public static void main(String[] args) { Display display = new Display(); display.show(10); // Calls show(int) display.show("Hello"); // Calls show(String) } }

7. Object-Oriented Programming (OOP) Concepts

7.1 Classes and Objects

Java is object-oriented, meaning it revolves around classes and objects. A class is a blueprint, and an object is an instance of that class.

class Car { String model; int year; public void displayInfo() { System.out.println("Model: " + model + ", Year: " + year); } } public class Main { public static void main(String[] args) { Car car = new Car(); // Creating an object car.model = "Toyota"; car.year = 2020; car.displayInfo(); // Calling a method of the object } }

7.2 Inheritance

Inheritance allows one class to inherit properties and behaviors from another class.

class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.sound(); // Calls Dog's overridden method } }

7.3 Polymorphism

Polymorphism allows methods to have the same name but behave differently based on the object type.

class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { Animal myDog = new Dog(); // Animal reference but Dog object Animal myCat = new Cat(); // Animal reference but Cat object myDog.sound(); // Calls Dog's sound myCat.sound(); // Calls Cat's sound } }

8. Exception Handling

In Java, exceptions are used to handle errors or other exceptional conditions.

8.1 Try-Catch Block

public class Main { public static void main(String[] args) { try { int result = 10 / 0; // This will throw an exception } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } } }

8.2 Throw and Throws

You can use throw to throw an exception manually and throws to declare exceptions in a method.

class CustomException extends Exception { public CustomException(String message) { super(message); } } public class Main { public static void checkAge(int age) throws CustomException { if (age < 18) { throw new CustomException("Age must be 18 or older"); } } public static void main(String[] args) { try { checkAge(16); } catch (CustomException e) { System.out.println("Caught exception: " + e.getMessage()); } } }

9. Java Collections

The Java Collections Framework provides classes and interfaces for working with data groups, such as ArrayList, HashSet, HashMap, etc.

9.1 ArrayList

import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); for (String fruit : list) { System.out.println(fruit); } } }

9.2 HashMap

import java.util.HashMap; public class Main { public static void main(String[] args) { HashMap<String, String> map = new HashMap<>(); map.put("1", "Apple"); map.put("2", "Banana"); map.put("3", "Orange"); System.out.println("Fruit with key 2: " + map.get("2")); } }

10. Conclusion

Java is a powerful and versatile language with vast capabilities, from basic syntax to advanced concepts such as object-oriented programming, exception handling, and collections. This tutorial has covered key areas, but Java is a deep language with endless possibilities.

Feel free to experiment with these examples and continue learning by exploring more advanced topics such as threads, file I/O, GUI programming, and networking. Happy coding!

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

oAuth in angular