CSE2005 - Java Coding Practice with Solutions
1. Class with Constructor and Method
class Student {
String name;
int regNo, marks;
Student(String name, int regNo, int marks) {
[Link] = name;
[Link] = regNo;
[Link] = marks;
}
void displayDetails() {
[Link](name + " " + regNo + " " + marks);
}
}
2. Use of 'this' Keyword
class Demo {
int x;
Demo(int x) {
this.x = x;
}
}
3. Static Variable Demo
class Count {
static int counter = 0;
Count() { counter++; }
static void showCount() {
[Link]("Count: " + counter);
}
}
4. Inheritance Example
class Employee {
void show() { [Link]("Employee"); }
}
class Manager extends Employee {
void display() {
[Link]();
[Link]("Manager");
}
}
5. Method Overriding
CSE2005 - Java Coding Practice with Solutions
class Shape {
void area() { [Link]("Area"); }
}
class Circle extends Shape {
void area() { [Link]("Circle Area"); }
}
6. Abstract Class
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
void makeSound() { [Link]("Bark"); }
}
7. Final Keyword
final class A {}
class B { final void display() { [Link]("Hello"); } }
8. Object Class Methods
class Person {
String name;
public String toString() { return name; }
public boolean equals(Object o) { return [Link](((Person)o).name); }
}
9. Interface Example
interface Flyable { void fly(); }
class Bird implements Flyable {
public void fly() { [Link]("Bird flies"); }
}
10. Extend Interface
interface A { void show(); }
interface B extends A { void display(); }
class C implements B {
public void show() {}
public void display() {}
}
11. Multiple Catch Blocks
CSE2005 - Java Coding Practice with Solutions
try {
int a = 5/0;
} catch (ArithmeticException e) {
[Link]("Arithmetic Error");
} catch (Exception e) {
[Link]("General Error");
}
12. User Defined Exception
class InvalidAgeException extends Exception {}
void check(int age) throws InvalidAgeException {
if (age < 18) throw new InvalidAgeException();
}
13. Finally Block
try {
int a = 5/0;
} catch (Exception e) {
[Link]("Exception");
} finally {
[Link]("Always executed");
}
14. ArrayList Example
ArrayList<String> list = new ArrayList<>();
[Link]("John"); [Link]("Amy");
[Link](list);
for(String s : list) [Link](s);
15. HashMap with Iterator
HashMap<Integer, String> map = new HashMap<>();
[Link](1, "John");
for([Link]<Integer,String> e : [Link]())
[Link]([Link]() + " " + [Link]());
16. Generic Class
class Box<T> {
T value;
Box(T value) { [Link] = value; }
void display() { [Link](value); }
}
CSE2005 - Java Coding Practice with Solutions
17. Generic Method
public <T extends Comparable<T>> T max(T a, T b, T c) {
T max = a;
if([Link](max) > 0) max = b;
if([Link](max) > 0) max = c;
return max;
}
18. Thread using Runnable
class MyThread implements Runnable {
public void run() {
for(int i=1;i<=5;i++) [Link](i);
}
}
19. Synchronization Example
synchronized void printTable(int n) {
for(int i=1;i<=5;i++) [Link](n*i);
}
20. Thread Priority
Thread t1 = new Thread(); [Link](Thread.MAX_PRIORITY);
[Link]();