Example:
int age; // Declaring an integer variable named 'age'
double salary; // Declaring a double variable named 'salary'
String name; // Declaring a String variable named 'name'
Example:
int age = 30; // Initializing the 'age' variable with the value 30
double salary = 50000.50; // Initializing the 'salary' variable with the value 50000.50
String name = "John"; // Initializing the 'name' variable with the value "John"
Example:
public class VariablesExample {
public static void main(String[] args) {
int age = 30; // declaring and initializing an integer variable 'age'
double salary = 50000.50; // declaring and initializing a double variable 'salary'
String name = "John"; // declaring and initializing a String variable 'name'
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: $" + salary);
}
}
Output:
Name: John
Age: 30
Salary: $50000.5
Example:
public void exampleMethod() {
int localVar = 10; // localVar is a local variable
// localVar can only be used within this method
System.out.println(localVar);
}
Example:
public class MyClass {
int instanceVar; // instanceVar is an instance variable
// instanceVar can be accessed by any method in MyClass
}
Example:
public class MyClass {
static int classVar; // classVar is a class variable
// classVar can be accessed using MyClass.classVar
}
public class DataTypesExample {
public static void main(String[] args) {
// Primitive data types
byte myByte = 127;
short myShort = 32000;
int myInt = 2147483647;
long myLong = 9223372036854775807L; // Note the 'L' suffix for long literals
float myFloat = 3.14f; // Note the 'f' suffix for float literals
double myDouble = 2.71828;
char myChar = 'A';
boolean myBoolean = true;
// Output
System.out.println("Primitive Data Types:");
System.out.println("byte: " + myByte);
System.out.println("short: " + myShort);
System.out.println("int: " + myInt);
System.out.println("long: " + myLong);
System.out.println("float: " + myFloat);
System.out.println("double: " + myDouble);
System.out.println("char: " + myChar);
System.out.println("boolean: " + myBoolean);
}
}
Output:
Primitive Data Types:
byte: 127
short: 32000
int: 2147483647
long: 9223372036854775807
float: 3.14
double: 2.71828
char: A
boolean: true
Objects of Classes: In Java, objects are instances of classes. Classes define the structure and behavior of objects.
Arrays: Arrays are collections of elements of the same type. They can hold primitive data types or objects.
public class DataTypesExample {
public static void main(String[] args) {
// Reference data types
String myString = "Hello, Java!";
int[] myArray = {1, 2, 3, 4, 5}; // Array of integers
// Output
System.out.println("nReference Data Types:");
System.out.println("String: " + myString);
System.out.print("Array: [");
for (int i = 0; i < myArray.length; i++) {
System.out.print(myArray[i]);
if (i < myArray.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
Output:
Reference Data Types:
String: Hello, Java!
Array: [1, 2, 3, 4, 5]
public class ConstantsExample {
// Constant using the 'final' keyword
public static final int MAX_VALUE = 100;
public static final double PI = 3.14159;
public static final String APPLICATION_NAME = "MyApp";
}
public class Main {
public static void main(String[] args) {
System.out.println("Max value: " + ConstantsExample.MAX_VALUE);
System.out.println("PI: " + ConstantsExample.PI);
System.out.println("Application Name: " + ConstantsExample.APPLICATION_NAME);
}
}
Constants are an essential part of Java programming, providing a way to define and use fixed values throughout your codebase.
public interface MathConstants {
double PI = 3.14159;
double E = 2.71828;
}
public class Main {
public static void main(String[] args) {
System.out.println("PI: " + MathConstants.PI);
System.out.println("E: " + MathConstants.E);
}
}
public class ArithmeticOperatorsExample {
public static void main(String[] args) {
int a = 10;
int b = 5;
// Addition
int sum = a + b;
System.out.println("Sum: " + sum);
// Subtraction
int difference = a - b;
System.out.println("Difference: " + difference);
// Multiplication
int product = a * b;
System.out.println("Product: " + product);
// Division
int quotient = a / b;
System.out.println("Quotient: " + quotient);
// Modulus
int remainder = a % b;
System.out.println("Remainder: " + remainder);
// Increment
a++;
System.out.println("Incremented a: " + a);
// Decrement
b--;
System.out.println("Decremented b: " + b);
}
}
public class RelationalOperatorsExample {
public static void main(String[] args) {
int x = 5;
int y = 10;
// Equal to
System.out.println("Is x equal to y? " + (x == y));
// Not equal to
System.out.println("Is x not equal to y? " + (x != y));
// Greater than
System.out.println("Is x greater than y? " + (x > y));
// Less than
System.out.println("Is x less than y? " + (x < y));
// Greater than or equal to
System.out.println("Is x greater than or equal to y? " + (x >= y));
// Less than or equal to
System.out.println("Is x less than or equal to y? " + (x <= y));
}
}
public class LogicalOperatorsExample {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
// Logical AND
System.out.println("a AND b: " + (a && b));
// Logical OR
System.out.println("a OR b: " + (a || b));
// Logical NOT
System.out.println("NOT a: " + (!a));
}
}
public class AssignmentOperatorsExample {
public static void main(String[] args) {
int x = 10;
// Assignment
int y = x;
System.out.println("y: " + y);
// Compound Assignment
x += 5;
System.out.println("x after compound assignment: " + x);
}
}
public class BitwiseOperatorsExample {
public static void main(String[] args) {
int a = 5; // 101 in binary
int b = 3; // 011 in binary
// Bitwise AND
int bitwiseAnd = a & b; // Result: 001 (1 in decimal)
System.out.println("Bitwise AND: " + bitwiseAnd);
// Bitwise OR
int bitwiseOr = a | b; // Result: 111 (7 in decimal)
System.out.println("Bitwise OR: " + bitwiseOr);
// Bitwise XOR
int bitwiseXor = a ^ b; // Result: 110 (6 in decimal)
System.out.println("Bitwise XOR: " + bitwiseXor);
// Bitwise Complement
int bitwiseComplement = ~a; // Result: 11111111111111111111111111111010 (-6 in decimal)
System.out.println("Bitwise Complement of a: " + bitwiseComplement);
// Left Shift
int leftShift = a << 1; // Result: 1010 (10 in decimal)
System.out.println("Left Shift of a: " + leftShift);
// Right Shift
int rightShift = a >> 1; // Result: 10 (2 in decimal)
System.out.println("Right Shift of a: " + rightShift);
}
}
public class ConditionalOperatorExample {
public static void main(String[] args) {
int x = 5;
int y = 10;
// Conditional Operator (Ternary Operator)
int max = (x > y) ? x : y;
System.out.println("Max value: " + max);
}
}
public class IfElseExample {
public static void main(String[] args) {
int number = 10;
// If-else statement
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
}
}
public class NestedIfElseExample {
public static void main(String[] args) {
int age = 20;
boolean isCitizen = true;
// Nested if-else statement
if (age >= 18) {
if (isCitizen) {
System.out.println("You are eligible to vote");
} else {
System.out.println("You are not a citizen");
}
} else {
System.out.println("You are not eligible to vote");
}
}
}
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
String dayName;
// Switch statement
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Unknown";
}
System.out.println("Day: " + dayName);
}
}
public class ForLoopExample {
public static void main(String[] args) {
// For loop to print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
// While loop to print numbers from 1 to 5
while (i <= 5) {
System.out.println(i);
i++;
}
}
}
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;
// Do-while loop to print numbers from 1 to 5
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
public class Car {
// Attributes
String make;
String model;
int year;
// Methods
public void start() {
System.out.println("Car started");
}
public void stop() {
System.out.println("Car stopped");
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of the Car class
Car myCar = new Car();
myCar.make = "Toyota";
myCar.model = "Corolla";
myCar.year = 2020;
// Calling methods on the object
myCar.start();
myCar.stop();
}
}
// Superclass
public class Vehicle {
String make;
String model;
public void drive() {
System.out.println("Vehicle is driving");
}
}
// Subclass
public class Car extends Vehicle {
int year;
public void start() {
System.out.println("Car started");
}
public void stop() {
System.out.println("Car stopped");
}
}
// Superclass
public class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
// Subclasses
public class Dog extends Animal {
public void makeSound() {
System.out.println("Bark");
}
}
// Subclasses
public class Cat extends Animal {
public void makeSound() {
System.out.println("Meow");
}
}
public class Employee {
private String name;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
// Abstract class
abstract class Shape {
// Abstract method (no body)
public abstract double area();
// Concrete method
public void display() {
System.out.println("This is a shape.");
}
}
// Concrete subclass
class Rectangle extends Shape {
private double length;
private double width;
// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Implementation of abstract method
public double area() {
return length * width;
}
}
// Usage
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 3);
System.out.println("Area of rectangle: " + rectangle.area());
rectangle.display();
}
}
// Interface
interface Shape {
// Abstract method
double area();
// Static method
static void display() {
System.out.println("This is a shape.");
}
}
// Concrete class implementing the interface
class Rectangle implements Shape {
private double length;
private double width;
// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Implementation of abstract method
public double area() {
return length * width;
}
}
// Usage
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 3);
System.out.println("Area of rectangle: " + rectangle.area());
Shape.display();
}
}
try {
// Code that may throw an exception
int result = 10 / 0;
// This will throw an ArithmeticException
} catch (ArithmeticException e) {
// Handle the exception
System.out.println("An arithmetic exception occurred: " + e.getMessage());
}
try {
// Code that may throw an exception
int[] arr = new int[5];
System.out.println(arr[10]);
// This will throw an ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
// Handle arithmetic exception
} catch (ArrayIndexOutOfBoundsException e) {
// Handle array index out of bounds exception
} catch (Exception e) {
// Handle other types of exceptions
}
try {
// Code that may throw an exception
} catch (Exception e) {
// Handle the exception
} finally {
// Code that always executes, regardless of whether an exception occurs or not
}
public void withdraw(double amount) throws InsufficientFundsException {
if (balance < amount) {
throw new InsufficientFundsException("Insufficient funds in the account");
}
// Withdraw the amount
}
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
List
List
Set
Set
Set
Map
Map
Map
try (FileInputStream fis = new FileInputStream("input.txt");
BufferedInputStream bis = new BufferedInputStream(fis)) {
int data; while ((data = bis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
try (FileOutputStream fos = new FileOutputStream("output.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
String message = "Hello, world!";
byte[] bytes = message.getBytes();
bos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
try (InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr)) {
System.out.println("Enter text:");
String input = br.readLine();
System.out.println("You entered: " + input);
} catch (IOException e) {
e.printStackTrace();
}
try (OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter bw = new BufferedWriter(osw)) {
bw.write("Hello, world!");
bw.newLine(); // Write a new line
bw.flush(); // Flush the buffer
} catch (IOException e) {
e.printStackTrace();
}