Java Programming Concepts - Step-by-Step Code with Output
1. Class in Java
Code:
class Person {
String name;
int age;
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Person p = new Person();
p.name = "Kishan";
p.age = 21;
p.displayInfo();
}
}
Output:
Name: Kishan, Age: 21
2. Typecasting
Code:
public class TypeCastingExample {
public static void main(String[] args) {
int i = 100;
long l = i;
float f = l;
System.out.println("int->long->float: " + f);
double d = 123.456;
int x = (int) d;
System.out.println("double->int: " + x);
}
}
Output:
int->long->float: 100.0
double->int: 123
3. Inheritance
Code:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
public static void main(String[] args) {
Java Programming Concepts - Step-by-Step Code with Output
Dog d = new Dog();
d.sound();
d.bark();
}
}
Output:
Animal makes sound
Dog barks
4. Exception Handling
Code:
public class ExceptionExample {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block always runs");
}
}
}
Output:
Error: / by zero
Finally block always runs
5. Polymorphism
Code:
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape {
void draw() {
System.out.println("Drawing a rectangle");
}
public static void main(String[] args) {
Shape s1 = new Circle();
Shape s2 = new Rectangle();
s1.draw();
s2.draw();
}
}
Output:
Java Programming Concepts - Step-by-Step Code with Output
Drawing a circle
Drawing a rectangle