Basics of Java Programming
Introduction
Java is a versatile and widely-used programming language known for its platform independence, object-
oriented features, and robust performance. It is designed for building secure and portable applications.
Key Features
1. Object-Oriented: Supports encapsulation, inheritance, and polymorphism.
2. Platform Independent: "Write Once, Run Anywhere" using the Java Virtual Machine (JVM).
3. Robust and Secure: Built-in exception handling and security features.
4. High Performance: Just-In-Time (JIT) compiler enhances execution speed.
Java Program Structure
Basic Structure
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
Components
1. Class Declaration: public class Main defines the class.
2. Main Method: Entry point of the program.
3. Statements: Instructions executed by the program.
Variables and Data Types
Variables
● Declaration: dataType variableName;
● Initialization: variableName = value;
Data Types
1. Primitive: int, char, float, double, boolean, etc.
2. Non-Primitive: Arrays, Strings, Classes, etc.
Example
int age = 25;
float height = 5.9f;
char grade = 'A';
boolean isPassed = true;
Control Structures
Conditional Statements
● if-else
if (age > 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
● switch
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
default:
System.out.println("Try harder");
Loops
● for
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
● while
while (isPassed) {
System.out.println("Passed");
isPassed = false;
Object-Oriented Programming (OOP)
Key Concepts
1. Encapsulation: Grouping related variables and methods into a class.
2. Inheritance: Deriving new classes from existing ones.
3. Polymorphism: Using a single interface to represent different types.
4. Abstraction: Hiding implementation details from the user.
Example
class Animal {
void sound() {
System.out.println("Animal makes a sound");
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
Common Java Libraries
1. java.util: Collections, Date, Random, etc.
2. java.io: Input and output operations.
3. java.net: Networking utilities.
Practice Problems
1. Write a program to check if a number is even or odd.
2. Create a class Car with attributes brand and speed, and a method to display them.
3. Write a program that uses a loop to print the first 10 Fibonacci numbers.
Summary
Java's combination of simplicity, object-orientation, and extensive library support makes it an essential
language for modern development. Understanding its basic structure, control flow, and OOP principles is
crucial for creating effective applications.