Java Basics

11
0

Introduction

Java is a high-level, class-based, object-oriented programming language. It follows the principle of “Write Once, Run Anywhere”, which means compiled Java programs can run on any platform that supports Java.

Some basic features of Java are:

  • Platform independence

  • Object-oriented programming

  • Simple and readable syntax

  • Automatic memory management

  • Built-in error handling

1. Sample Code

The following program prints Hello World:

public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
  • class Main defines a class named Main.

  • main() is the starting point of the program.

  • System.out.println() displays output on the screen.

The file should be saved as Main.java.

2. Comments

Comments are notes added to explain code. They are ignored by the compiler.

// This is a single-line comment
/*
This is a
multi-line comment
*/

3. Data Types

Data types specify the kind of value a variable can store. Java has eight primitive data types.

  • byte: Stores small integers from -128 to 127.

  • short: Stores integers larger than the range of byte.

  • int: Stores regular integer values and is the most commonly used integer type.

  • long: Stores very large integer values.

  • float: Stores decimal values with limited precision. Its value requires an f suffix.

  • double: Stores decimal values with greater precision.

  • char: Stores a single character.

  • boolean: Stores either true or false.

Example:

// Declare a byte variable to store small integer values
byte level = 10;
// Declare a short variable to store the year
short year = 2026;
// Declare an integer variable to store the marks
int marks = 85;
// Declare a long variable to store large integer values
long population = 8000000000L;
// Declare a float variable to store decimal values
float price = 10.5f;
// Declare a double variable to store decimal values with higher precision
double distance = 123.456;
// Declare a character variable to store a single character
char grade = 'A';
// Declare a boolean variable to store a true or false value
boolean passed = true;
Data Types

Data Types

4. Operators

Operators are used to perform calculations and comparisons.

Arithmetic Operators

  • + adds two values.

  • - subtracts one value from another.

  • * multiplies two values.

  • / divides one value by another.

  • % returns the remainder after division.

// Declare two integer variables
int a = 10;
int b = 3;
// Perform addition
System.out.println(a + b); // 13
// Perform subtraction
System.out.println(a - b); // 7
// Perform multiplication
System.out.println(a * b); // 30
// Perform integer division
System.out.println(a / b); // 3
// Find the remainder after division
System.out.println(a % b); // 1

Relational Operators

Relational operators compare two values and return either true or false.

  • == checks whether two values are equal.

  • != checks whether two values are different.

  • > checks whether the left value is greater.

  • < checks whether the left value is smaller.

  • >= checks whether the left value is greater than or equal to the right value.

  • <= checks whether the left value is smaller than or equal to the right value.

// Store the age in an integer variable
int age = 20;
// Check if age is equal to 20
System.out.println(age == 20); // true
// Check if age is greater than 18
System.out.println(age > 18); // true
// Check if age is less than 18
System.out.println(age < 18); // false

Logical Operators

Logical operators combine or modify boolean conditions.

  • && returns true when both conditions are true.

  • || returns true when at least one condition is true.

  • ! reverses the result of a condition.

// Store the person's age
int age = 20;
// Store whether the person has a driving license
boolean hasLicense = true;
// Check if the person is at least 18 years old and has a license
System.out.println(age >= 18 && hasLicense); // true
Operators

Operators

5. Input and Output

Java uses System.out.println() for output. The Scanner class can be used to read input.

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner sc = new Scanner(System.in);
// Read the user's age as an integer
int age = sc.nextInt();
// Read the user's name as a string
String name = sc.next();
// Display the name and age
System.out.println(name + " is " + age);
// Close the Scanner to release system resources
sc.close();
}
}

Scanner is easy to use and suitable for beginners. BufferedReader is usually faster but requires additional conversion when reading numbers.

8. Arrays

An array stores multiple values of the same type.

// Create an array to store scores
int[] scores = {90, 80, 70};
// Access and print the first element of the array
System.out.println(scores[0]); // 90
// Print the total number of elements in the array
System.out.println(scores.length); // 3
// Iterate through each score in the array
for (int score : scores) {
// Print the current score
System.out.println(score);
}

9. Strings

Strings are used to store text. A String is an object, not a primitive data type.

// Store a string in a variable
String text = "Hello";
// Find and print the length of the string
System.out.println(text.length()); // 5
// Access and print the character at index 1
System.out.println(text.charAt(1)); // e
// Extract and print characters from index 0 to 1
System.out.println(text.substring(0, 2)); // He
// Check if the string is equal to "Hello"
System.out.println(text.equals("Hello")); // true

Strings are immutable, which means their original value cannot be changed after creation.

Use equals() to compare the contents of two strings.

Java arrays and strings

Java arrays and strings

10. Conditional Statements

Conditional statements allow a program to make decisions.

If-Else

// Store the marks in an integer variable
int marks = 85;
// Check the marks and assign the appropriate grade
if (marks > 90) {
System.out.println("A");
} else if (marks > 80) {
System.out.println("B");
} else {
System.out.println("C");
}

The program checks each condition and runs the first block whose condition is true.

Switch

// Store the day number
int day = 2;
// Match the day number with the corresponding day
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid");
}

break stops the switch after a matching case. default runs when no case matches.

Conditional Statements

Conditional Statements

11. Loops

Loops repeat a block of code.

For Loop

// Loop from 0 to 4
for (int i = 0; i < 5; i++) {
// Print the current value of i
System.out.println(i);
}

A for loop is generally used when the number of repetitions is known.

While Loop

// Initialize the loop counter
int i = 0;
// Continue the loop while i is less than 5
while (i < 5) {
// Print the current value of i
System.out.println(i);
// Increment i to move to the next iteration
i++;
}

A while loop runs while its condition remains true.

Do-While Loop

// Initialize the loop counter
int i = 0;
// Execute the loop body at least once before checking the condition
do {
// Print the current value of i
System.out.println(i);
// Increment i to move to the next iteration
i++;
} while (i < 5); // Continue while i is less than 5
Loops

Loops

Summary

The basic concepts of Java include:

  • Classes and the main() method

  • Comments and data types

  • Operators and strings

  • Input and output

  • Arrays and conditional statements

  • Loops

CS Core

Read Similar Blogs

Comments0