Introduction to Java
Java is a high-level, object-oriented, platform-independent programming language. It was developed by James Gosling at Sun Microsystems and officially released in 1995. Java is designed to be write once, run anywhere (WORA) — which means code written in Java can run on any platform that supports Java without modification.
Key Features of Java
- Object-Oriented
- Platform Independent (via JVM)
- Secure and Robust
- Multithreaded
- High Performance (via JIT compiler)
- Rich Standard Library
Setting Up Java Environment
Install Java
- Download and install the JDK (Java Development Kit) from the Oracle website.
- Set the JAVA_HOME environment variable.
- Install an IDE like Eclipse, IntelliJ IDEA, or use VS Code.
To begin developing Java applications, you first need to set up your Java environment. Start by downloading and installing the Java Development Kit (JDK) from the official Oracle website. After installation, it's important to set the JAVA_HOME environment variable, which allows other applications and tools to locate your Java installation. Finally, choose and install a suitable Integrated Development Environment (IDE) like Eclipse, IntelliJ IDEA, or Visual Studio Code to write, compile, and run your Java code efficiently.
Your First Java Program
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, world!");
}
}
Explanation:
- public class HelloWorld: Declares a class.
- public static void main: Main method is the entry point.
- System.out.println: Prints text to the console.
This simple Java program prints "Hello, world!" to the console. The line public class HelloWorld defines a class named HelloWorld. Inside it, the public static void main(String[] args) method serves as the entry point of the program—it's where execution starts. The statement System.out.println("Hello, world!") outputs the text to the console. Every Java application must have a main method to run, and using System.out.println is a common way to display output.
Java Variables and Data Types
Declaration
int age = 25;
double pi = 3.14;
char grade = 'A';
String name = "Waleed";
boolean isJavaFun = true;
Primitive Data Types
- int, byte, short, long - Integers
- float, double - Floating-point numbers
- char - Single character
- boolean - true/false
In Java, variables are used to store data values, and each variable has a specific data type that defines the kind of data it can hold. For example, int age = 25; declares an integer variable named age, and double pi = 3.14; stores a decimal value. Java supports various primitive data types: integers (int, byte, short, long), floating-point numbers (float, double), characters (char), and boolean values (true or false). Additionally, non-primitive types like String are used for more complex data such as text.
Operators in Java
- Arithmetic: +, -, *, /, %
- Relational: ==, !=, >, <, >=, <=
- Logical: &&, ||, !
- Assignment: =, +=, -=, *=, /=
- Unary: ++, --
Example:
int a = 10, b = 5;
System.out.println(a + b); // 15
Operators in Java are special symbols used to perform operations on variables and values. Arithmetic operators like +, -, *, /, and % are used for basic mathematical calculations. Relational operators such as ==, !=, >, <, >=, and <= compare values and return a boolean result. Logical operators like &&, ||, and ! are used to combine or invert boolean expressions. Assignment operators (e.g., =, +=) assign values to variables, while unary operators like ++ and -- increment or decrement a value. In the example, a + b evaluates to 15 and is printed to the console.
Conditional Statements
If Statement
int score = 70;
if (score >= 50)
{
System.out.println("Passed");
}
Conditional statements in Java allow you to make decisions in your code based on certain conditions. The if statement checks whether a condition is true, and if it is, the block of code inside it executes. In the example, the program checks if the score is greater than or equal to 50. Since the condition is true, it prints "Passed" to the console. If the condition were false, the code inside the if block would be skipped.
If-else Statement
int score = 70;
if (score >= 50)
{
System.out.println("Passed");
} else
{
System.out.println("Failed");
}
The if-else statement in Java is used to execute one block of code if a condition is true, and another block if the condition is false. In the given example, the program checks whether score is greater than or equal to 50. If the condition is true, it prints "Passed"; otherwise, it prints "Failed". This structure ensures that exactly one of the two outcomes is executed based on the condition.
If-else if Statement
public class GradeChecker
{
public static void main(String[] args)
{
int marks = 75;
if (marks >= 90)
{
System.out.println("Grade: A");
} else if (marks >= 80)
{
System.out.println("Grade: B");
} else if (marks >= 70)
{
System.out.println("Grade: C");
} else
{
System.out.println("Grade: F");
}
}
}
The if-else if statement in Java is used when you need to test multiple conditions. Each if or else if condition is checked in order, and the first one that evaluates to true will execute its corresponding block of code. In this example, the program checks the value of marks and assigns a grade based on the range it falls into. Since marks is 75, the condition marks >= 70 is true, so it prints "Grade: C". If none of the conditions are met, the else block executes, printing "Grade: F".
Switch Statement
int day = 3;
switch (day)
{
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Other day");
}
The switch statement in Java is used to execute one block of code out of many based on the value of a variable. It is an alternative to using multiple if-else statements when checking a single variable against different values. In this example, the value of day is 3. The switch checks each case to find a match. Since there is no case 3, it falls through to the default case and prints "Other day". Each case typically ends with a break statement to prevent fall-through.
Loops in Java
For Loop
for (int i = 0; i < 5; i++)
{
System.out.println(i);
}
The for loop in Java is used to execute a block of code a specific number of times. It consists of three parts: initialization, condition, and increment/decrement. In the example, int i = 0 initializes the loop variable, i < 5 is the condition that keeps the loop running, and i++ increases the value of i by 1 after each iteration. The loop runs five times and prints the numbers 0 to 4 to the console.
While Loop
int i = 0;
while (i < 5)
{
System.out.println(i);
i++;
}
The while loop in Java repeatedly executes a block of code as long as the given condition is true. In this example, the loop starts with i = 0 and continues to run while i < 5. Inside the loop, the current value of i is printed, and then i is incremented by 1. The loop stops once i reaches 5, so the numbers 0 through 4 are printed to the console.
Do-While Loop
int i = 0;
do
{
System.out.println(i);
i++;
} while (i < 5);
The do-while loop in Java is similar to the while loop, but it guarantees that the loop body will execute at least once, even if the condition is false. In this example, the loop starts with i = 0, prints the value of i, and then increments it. After each iteration, it checks whether i < 5. Since the condition is true initially, the loop continues until i reaches 5, printing the numbers 0 to 4 to the console.
Functions (Methods)
public static int add(int a, int b)
{
return a + b;
}
Usage:
int result = add(5, 3);
System.out.println(result); // 8
In Java, functions (commonly called methods) are blocks of code designed to perform specific tasks and can be reused throughout a program. The example defines a static method named add that takes two integer parameters, a and b, and returns their sum. The return statement sends the result back to the caller. In the usage example, add(5, 3) returns 8, which is stored in the variable result and then printed to the console.
Object-Oriented Programming (OOP)
Class and Object
class Car
{
String color = "Red";
}
public class Main
{
public static void main(String[] args)
{
Car myCar = new Car();
System.out.println(myCar.color);
}
}
In Java, Object-Oriented Programming (OOP) is based on the concept of classes and objects. A class is a blueprint for creating objects, which are instances of that class. In the example, the Car class has a property color with the value "Red". In the Main class, an object myCar is created from the Car class using the new keyword. The program then accesses the color property of myCar and prints "Red" to the console.
Inheritance
class Animal
{
void sound()
{
System.out.println("Animal sound");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Bark");
}
}
Inheritance is a key feature of Object-Oriented Programming in Java that allows one class to inherit properties and methods from another class. In this example, the Dog class extends the Animal class, meaning it inherits the sound() method from Animal. Additionally, the Dog class defines its own method, bark(). This enables code reuse and establishes a relationship between the parent (Animal) and child (Dog) classes, allowing Dog to access both inherited and its own methods.
Polymorphism
class Animal
{
void sound()
{
System.out.println("Generic sound");
}
}
class Cat extends Animal
{
void sound()
{
System.out.println("Meow");
}
}
Polymorphism in Java allows methods to have different behaviors based on the object that is calling them. It enables a single method name to act differently for different classes. In the example, both Animal and Cat have a sound() method. However, when the method is called on an object of type Cat, it overrides the sound() method of the Animal class and prints "Meow" instead of "Generic sound". This is an example of **method overriding**, a key form of polymorphism.
Abstraction
abstract class Animal
{
abstract void sound();
}
class Cow extends Animal
{
void sound()
{
System.out.println("Moo");
}
}
Abstraction in Java is the concept of hiding complex implementation details and showing only the essential features of an object. This is typically achieved using abstract classes and methods. In the example, Animal is an abstract class that contains an abstract method sound(), which has no body. The Cow class extends Animal and provides a concrete implementation of the sound() method by printing "Moo". This allows developers to define a general structure in the abstract class and enforce implementation in its subclasses.
Encapsulation
class Person
{
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
Encapsulation is the practice of wrapping data (variables) and methods that operate on the data into a single unit, typically a class, and restricting direct access to some of the object's components. In Java, this is done using the private access modifier along with public getter and setter methods. In the example, the name variable is declared private, so it cannot be accessed directly from outside the Person class. Instead, the setName() and getName() methods are used to modify and access the value of name, ensuring controlled and secure access to the data.
Arrays in Java
int[] numbers = {1, 2, 3, 4};
System.out.println(numbers[0]); // 1
Multidimensional Array:
int[][] matrix = {
{1, 2},
{3, 4}
};
Arrays in Java are used to store multiple values of the same data type in a single variable. In the example, int[] numbers = {1, 2, 3, 4}; creates a one-dimensional array containing four integers. The value at a specific index can be accessed using square brackets, with indexing starting from 0—so numbers[0] returns 1. Java also supports multidimensional arrays like int[][] matrix, which is essentially an array of arrays. In the given example, matrix represents a 2x2 grid containing values arranged in rows and columns.
Strings in Java
String s = "Java";
System.out.println(s.length()); // 4
System.out.println(s.toUpperCase()); // JAVA
In Java, strings are objects that represent sequences of characters. They are widely used for storing and manipulating text. In the example, String s = "Java"; creates a string object with the value "Java". The method s.length() returns the number of characters in the string, which is 4. The method s.toUpperCase() converts all characters in the string to uppercase, resulting in "JAVA". Java provides many built-in methods for working with strings, making them powerful and flexible to use.
Exception Handling
try
{
int x = 10 / 0;
} catch (ArithmeticException e)
{
System.out.println("Cannot divide by zero!");
} finally
{
System.out.println("Always runs");
}
Exception handling in Java is used to manage runtime errors gracefully without crashing the program. The try block contains code that might throw an exception. If an exception occurs, control is transferred to the corresponding catch block. In this example, dividing 10 by 0 causes an ArithmeticException, which is caught and handled by printing a message. The finally block contains code that always runs, regardless of whether an exception occurred or not, making it useful for cleanup operations like closing files or releasing resources.
File Handling
import java.io.File;
public class Main
{
public static void main(String[] args)
{
File file = new File("myfile.txt");
if (file.exists())
{
System.out.println("File found");
}
}
}
File handling in Java allows you to create, read, update, and delete files using classes from the java.io package. In this example, a File object is created to represent a file named myfile.txt. The method file.exists() checks whether the file actually exists in the specified location. If it does, the program prints "File found" to the console. This is a basic way to interact with the file system, and Java provides many additional methods for working with file content and properties.
Java Collections Framework
- List: ArrayList, LinkedList
- Set: HashSet, TreeSet
- Map: HashMap, TreeMap
Example:
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
The Java Collections Framework provides a set of classes and interfaces for storing and manipulating groups of data efficiently. It includes core interfaces like List, Set, and Map. Lists such as ArrayList and LinkedList allow ordered collections with duplicate elements. Sets like HashSet and TreeSet store unique elements. Maps such as HashMap and TreeMap store key-value pairs. In the example, an ArrayList of strings is created and populated with the values "Java" and "Python" using the add() method.
Multithreading
class MyThread extends Thread
{
public void run()
{
System.out.println("Running thread");
}
}
Multithreading in Java allows multiple threads to run concurrently, making programs more efficient and responsive, especially for tasks like parallel processing or background operations. To create a thread, you can extend the Thread class and override its run() method, which contains the code to be executed in the new thread. In the example, MyThread is a custom thread class, and when its run() method is called (typically via start()), it prints "Running thread" to the console.
Java Input/Output (I/O)
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String name = sc.nextLine();
Java provides various classes for handling input and output (I/O), and one of the most commonly used for console input is the Scanner class from the java.util package. In the example, a Scanner object named sc is created to read input from the user. The System.out.print() statement displays a prompt, and sc.nextLine() reads a full line of text entered by the user, which is then stored in the name variable. This approach is useful for interactive console-based programs.
Access Modifiers
- public: accessible everywhere
- private: accessible only within the class
- protected: accessible within package and subclasses
- default (no keyword): within the same package
Access modifiers in Java define the visibility and accessibility of classes, methods, and variables. The public modifier allows access from any other class, making the member universally available. private restricts access to within the same class only, promoting encapsulation. protected allows access within the same package and also by subclasses in other packages. When no modifier is specified (default access), the member is accessible only within classes in the same package. Proper use of access modifiers helps in designing secure and modular code.
Packages and Import
package mypackage;
public class MyClass
{
public void display()
{
System.out.println("Hello Package");
}
}
Packages in Java are used to group related classes and interfaces together, helping to organize code and avoid name conflicts. The package keyword is used to declare the package at the top of the Java file. In the example, the class MyClass belongs to the package mypackage. To use this class in another file, you would use the import statement followed by the fully qualified name (e.g., import mypackage.MyClass;). Packages improve code maintainability and structure, especially in large projects.
Java API and Libraries
- java.lang - Core classes
- java.util - Collections and utilities
- java.io - Input/Output
- java.net - Networking
- java.sql - Database access
The Java API (Application Programming Interface) is a vast library of prewritten classes and interfaces that provide essential functionality for Java programs. It is organized into packages, each serving a specific purpose. The java.lang package includes core classes like String and Math and is imported by default. java.util offers utility classes such as collections and date/time handling. java.io supports file and data input/output, while java.net is used for network operations. java.sql provides classes for interacting with databases. These libraries help developers build robust applications efficiently.
Java GUI with Swing (Basic)
import javax.swing.*;
public class GUI
{
public static void main(String[] args)
{
JFrame frame = new JFrame("My Window");
JButton btn = new JButton("Click");
frame.add(btn);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
Swing is a part of Java’s standard library used for building graphical user interfaces (GUIs). It provides a set of lightweight components such as windows, buttons, text fields, and more. In this example, a JFrame is created to represent a window titled "My Window". A JButton labeled "Click" is added to the frame. The setSize() method sets the dimensions of the window, and setVisible(true) makes it appear on the screen. This simple program demonstrates the basic structure of a Swing-based GUI application.
Java Interview Questions (Basic)
- What is JVM, JRE, and JDK?
- What are access modifiers?
- What is a constructor?
- What is method overloading and overriding?
- Difference between == and .equals()?
Click here for online JAVA Code reader.
Click here to download VS CODE.
Click to go back Home.