TSP III Programs
TSP III Programs
PROGRAM:
public class JavaTokensExample { // 'public' and 'class' are keywords; '{}' are separators
// Main method - starting point of the program
public static void main(String[] args) { // 'public', 'static', 'void' are keywords; '()' are
separators
// Declaring and initializing variables with different data types
int number = 10; // 'int' is a keyword and 'number' is an identifier
double price = 99.99; // 'double' is a keyword and 'price' is an identifier
char grade = 'A'; // 'char' is a keyword and 'grade' is an identifier
boolean isJavaFun = true; // 'boolean' is a keyword and 'isJavaFun' is an identifier
String message = "Hello, Java!"; // 'String' is a reference data type and 'message' is an
identifier
// Using separators
System.out.println("The number is: " + number); // '.' is a separator
System.out.println("The price is: $" + price); // '.' is a separator
System.out.println("Grade: " + grade); // '.' is a separator
System.out.println("Is Java fun? " + isJavaFun); // '.' is a separator
System.out.println("Message: " + message); // '.' is a separator
// A for loop demonstrating the use of separators, identifiers, and keywords
for (int i = 0; i < 5; i++) { // 'for' is a keyword, 'i' is an identifier, and ';', '{}' are
separators
System.out.println("Loop iteration: " + i);
}
// Using a conditional statement
if (number > 5) { // 'if' is a keyword, and '{}' are separators
System.out.println("The number is greater than 5.");
} else { // 'else' is a keyword
System.out.println("The number is 5 or less.");
}
// Return statement - 'return' is a keyword, used to end the main method
return; // Optional as 'void' indicates no return value is needed
}
}
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
The number is: 10
The price is: $99.99
Grade: A
Is Java fun? true
Message: Hello, Java!
Loop iteration: 0
Loop iteration: 1
Loop iteration: 2
Loop iteration: 3
Loop iteration: 4
The number is greater than 5.
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
// Java program to demonstrate Scoping and Parameter Passing
public class ScopingAndParameterPassing {
// Global variable (class-level scope)
static int globalVar = 50;
public static void main(String[] args) {
// Local variable (local scope)
int localVar = 10;
System.out.println("Before modifying, localVar: " + localVar);
// Demonstrating scoping
modifyLocalVariable(localVar);
System.out.println("After modifying, localVar: " + localVar); // Unchanged due to local
scope
System.out.println("Before modifying, globalVar: " + globalVar);
modifyGlobalVariable();
System.out.println("After modifying, globalVar: " + globalVar); // Changed due to
global scope
// Demonstrating parameter passing
int primitiveValue = 5;
System.out.println("Before modifying, primitiveValue: " + primitiveValue);
modifyPrimitive(primitiveValue);
System.out.println("After modifying, primitiveValue: " + primitiveValue); // Unchanged
(pass-by-value)
MyObject obj = new MyObject();
System.out.println("Before modifying, obj.value: " + obj.value);
modifyObject(obj);
System.out.println("After modifying, obj.value: " + obj.value); // Changed (pass-by-
reference)
}
// Method to demonstrate local scope
public static void modifyLocalVariable(int localVar) {
localVar = 20; // Changes only within the scope of this method
System.out.println("Inside modifyLocalVariable, localVar: " + localVar);
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
}
// Method to demonstrate global scope
public static void modifyGlobalVariable() {
globalVar = 100; // Modifies the global variable
}
// Method to demonstrate pass-by-value
public static void modifyPrimitive(int value) {
value = 10; // Changes only the local copy
System.out.println("Inside modifyPrimitive, value: " + value);
}
// Method to demonstrate pass-by-reference
public static void modifyObject(MyObject obj) {
obj.value = 20; // Modifies the original object's property
}
}
// Helper class to demonstrate pass-by-reference
class MyObject {
int value = 10;
}
OUTPUT:
Before modifying, localVar: 10
Inside modifyLocalVariable, localVar: 20
After modifying, localVar: 10
Before modifying, globalVar: 50
After modifying, globalVar: 100
Before modifying, primitiveValue: 5
Inside modifyPrimitive, value: 10
After modifying, primitiveValue: 5
Before modifying, obj.value: 10
After modifying, obj.value: 20
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
import java.util.Scanner;
public class FlowControlExample {
public static void main(String[] args) {
// Initialize Scanner for user input
Scanner sc = new Scanner(System.in);
// Part 1: Using if-else to check if the number is even or odd
System.out.print("Enter a number to check if it is even or odd: ");
int num = sc.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
// Part 2: Using switch-case to print day of the week
System.out.print("\nEnter a number (1-7) to get the corresponding day of the week: ");
int day = sc.nextInt();
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid input! Please enter a number between 1 and 7.");
}
// Part 3: Using for loop to print numbers from 1 to 5
System.out.println("\nNumbers from 1 to 5 using a for loop:");
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// Part 4: Using while loop to print numbers from 6 to 10
System.out.println("\nNumbers from 6 to 10 using a while loop:");
int i = 6;
while (i <= 10) {
System.out.println(i);
i++;
}
// Close the scanner to prevent resource leak
sc.close();
}
}
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
Enter a number to check if it is even or odd: 7
7 is odd.
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
public class ArraysAndVarArgs {
// Method to calculate the sum of elements in an array
public static int sumArray(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}
// Method to calculate the sum of any number of integers using var-args
public static int sumVarArgs(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
public static void main(String[] args) {
// Part 1: Working with Arrays
int[] numbersArray = {10, 20, 30, 40, 50}; // Array initialization
System.out.println("Array: ");
for (int num : numbersArray) {
System.out.print(num + " ");
}
System.out.println();
// Calculate sum using the array method
int arraySum = sumArray(numbersArray);
System.out.println("Sum of array elements: " + arraySum);
// Part 2: Working with Var-args
System.out.println("\nUsing Var-args method:");
// Pass multiple integers as var-args
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
Array:
10 20 30 40 50
Sum of array elements: 150
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
public class OperatorsPrecedenceAssociativity {
public static void main(String[] args) {
// Arithmetic Operators
int a = 10, b = 5, c = 2;
System.out.println("Arithmetic Operators:");
System.out.println("a + b * c = " + (a + b * c)); // Multiplication (*) has higher
precedence than addition (+)
System.out.println("(a + b) * c = " + ((a + b) * c)); // Parentheses override precedence
System.out.println("a / b + c = " + (a / b + c)); // Division (/) before Addition (+)
// Relational Operators
System.out.println("Relational Operators:");
System.out.println("a > b && b > c: " + (a > b && b > c)); // Logical AND (&&) has
lower precedence than Relational (>)
System.out.println("a < b || b > c: " + (a < b || b > c)); // Logical OR (||) lower than
Relational (>)
// Bitwise Operators
System.out.println("Bitwise Operators:");
System.out.println("a & b = " + (a & b)); // Bitwise AND (&) has lower precedence than
arithmetic operators
System.out.println("a | b = " + (a | b)); // Bitwise OR (|)
// Assignment Operators
System.out.println("Assignment Operators:");
int x = 5;
x += 10; // Equivalent to x = x + 10
System.out.println("x += 10: " + x);
x *= 2; // Equivalent to x = x * 2
System.out.println("x *= 2: " + x);
// Associativity Example
System.out.println("Associativity Example:");
System.out.println("a - b - c = " + (a - b - c)); // Left to Right associativity in subtraction
System.out.println("a / b * c = " + (a / b * c)); // Left to Right associativity in division &
multiplication
// Unary Operators
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
System.out.println("Unary Operators:");
int y = 10;
System.out.println("y = " + y);
System.out.println("++y = " + (++y)); // Pre-increment
System.out.println("y++ = " + (y++)); // Post-increment
System.out.println("Final y = " + y);
}
}
OUTPUT:
Arithmetic Operators:
a + b * c = 20
(a + b) * c = 30
a/b+c=4
Relational Operators:
a > b && b > c: true
a < b || b > c: true
Bitwise Operators:
a&b=0
a | b = 15
Assignment Operators:
x += 10: 15
x *= 2: 30
Associativity Example:
a-b-c=3
a/b*c=4
Unary Operators:
y = 10
++y = 11
y++ = 11
Final y = 12
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
public class TypeConversionExample {
public static void main(String[] args) {
// Widening Conversion (Implicit Conversion)
int intValue = 100;
double doubleValue = intValue; // int to double (widening)
System.out.println("Widening Conversion:");
System.out.println("Integer Value: " + intValue);
System.out.println("Converted to Double: " + doubleValue);
// Narrowing Conversion (Explicit Conversion)
double largeDoubleValue = 99.99;
int narrowedIntValue = (int) largeDoubleValue; // double to int (narrowing)
System.out.println("\nNarrowing Conversion:");
System.out.println("Double Value: " + largeDoubleValue);
System.out.println("Converted to Integer (truncated): " + narrowedIntValue);
// Widening Conversion Example with char to int
char charValue = 'A'; // ASCII value of 'A' is 65
int charToInt = charValue; // widening
System.out.println("\nWidening Conversion (char to int):");
System.out.println("Character Value: " + charValue);
System.out.println("Converted to Integer (ASCII value): " + charToInt);
// Narrowing Conversion Example with int to byte
int largeIntValue = 130;
byte narrowedByteValue = (byte) largeIntValue; // narrowing
System.out.println("\nNarrowing Conversion (int to byte):");
System.out.println("Integer Value: " + largeIntValue);
System.out.println("Converted to Byte (may cause data loss): " + narrowedByteValue);
}
}
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
Widening Conversion:
Integer Value: 100
Converted to Double: 100.0
Narrowing Conversion:
Double Value: 99.99
Converted to Integer (truncated): 99
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
// Public class accessible from anywhere
public class AccessModifiersExample {
public static void main(String[] args) {
// Creating an object of DemoClass
DemoClass obj = new DemoClass();
// Accessing public variable and method
System.out.println("Public Variable: " + obj.publicVar);
obj.publicMethod();
// Accessing protected variable and method
System.out.println("Protected Variable: " + obj.protectedVar);
obj.protectedMethod();
// Accessing default (package-private) variable and method
System.out.println("Default Variable: " + obj.defaultVar);
obj.defaultMethod();
// Private members cannot be accessed outside the class
// Uncommenting the below lines will cause compilation errors
// System.out.println(obj.privateVar);
// obj.privateMethod();
}
}
// Class with different access modifiers
class DemoClass {
// Public variable and method (Accessible everywhere)
public int publicVar = 10;
public void publicMethod() {
System.out.println("Public Method Called");
}
// Protected variable and method (Accessible within the same package and subclasses)
protected int protectedVar = 20;
protected void protectedMethod() {
System.out.println("Protected Method Called");
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
}
// Default (Package-private) variable and method (Accessible within the same package)
int defaultVar = 30;
void defaultMethod() {
System.out.println("Default Method Called");
}
// Private variable and method (Accessible only within the same class)
private int privateVar = 40;
private void privateMethod() {
System.out.println("Private Method Called");
}
}
OUTPUT:
Public Variable: 10
Public Method Called
Protected Variable: 20
Protected Method Called
Default Variable: 30
Default Method Called
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
// Final class (cannot be extended)
final class FinalClass {
// Static variable (belongs to the class, not instance-specific)
static int staticVar = 100;
// Final variable (cannot be modified after initialization)
final int finalVar;
// Constructor initializing final variable
FinalClass(int value) {
this.finalVar = value;
}
// Static method (can be called without an instance)
static void displayStatic() {
System.out.println("Static method called. Static Variable: " + staticVar);
}
// Final method (cannot be overridden)
final void displayFinal() {
System.out.println("Final method called. Final Variable: " + finalVar);
}
}
// Abstract class (cannot be instantiated)
abstract class AbstractClass {
// Abstract method (must be implemented by subclasses)
abstract void abstractMethod();
// Synchronized method (thread-safe execution)
synchronized void synchronizedMethod() {
System.out.println("Synchronized method execution.");
}
}
// Concrete class extending abstract class
class ConcreteClass extends AbstractClass {
// Implementing abstract method
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
void abstractMethod() {
System.out.println("Abstract method implemented.");
}
}
public class NonAccessModifiersExample {
public static void main(String[] args) {
// Working with final class and its members
FinalClass obj1 = new FinalClass(200);
obj1.displayFinal();
FinalClass.displayStatic();
// Working with abstract class and its implementation
ConcreteClass obj2 = new ConcreteClass();
obj2.abstractMethod();
obj2.synchronizedMethod();
}
}
OUTPUT:
Final method called. Final Variable: 200
Static method called. Static Variable: 100
Abstract method implemented.
Synchronized method execution.
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
mypackage/Utility.java
package mypackage; // Package declaration
public class Utility {
// Static method to find the square of a number
public static int square(int num) {
return num * num;
}
}
StaticImportDemo.java
// Importing specific static methods from Math class
import static java.lang.Math.*;
import mypackage.Utility; // Importing custom package class
public class StaticImportDemo {
public static void main(String[] args) {
// Using static imports for Math methods
double result1 = sqrt(25); // No need to use Math.sqrt()
double result2 = pow(2, 3); // No need to use Math.pow()
double result3 = abs(-10.5); // No need to use Math.abs()
// Using custom package method
int squareValue = Utility.square(6); // Calling static method from custom package
// Printing results
System.out.println("Square root of 25: " + result1);
System.out.println("2 raised to power 3: " + result2);
System.out.println("Absolute value of -10.5: " + result3);
System.out.println("Square of 6 using Utility class: " + squareValue);
}
}
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
Square root of 25: 5.0
2 raised to power 3: 8.0
Absolute value of -10.5: 10.5
Square of 6 using Utility class: 36
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
// Defining a class named Person
class Person {
// Attributes (instance variables)
String name;
int age;
// Constructor to initialize attributes
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display person details
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
// Main class
public class CreatingClassesAndInstances {
public static void main(String[] args) {
// Creating instances of the Person class
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);
// Displaying details of each person
System.out.println("Person 1 Details:");
person1.displayInfo();
System.out.println("\nPerson 2 Details:");
person2.displayInfo();
}
}
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
Person 1 Details:
Name: Alice
Age: 25
Person 2 Details:
Name: Bob
Age: 30
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
Sum of integers: 15
Sum of doubles: 16.0
Factorial of 5: 120
Drawing a Circle
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
// Parent Class
class Animal {
String name;
// Method in the parent class
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
// Child Class
class Dog extends Animal {
// Method specific to the child class
public void bark() {
System.out.println(name + " is barking.");
}
}
// Main Class to demonstrate inheritance
public class InheritanceExample {
public static void main(String[] args) {
// Create an object of the child class
Dog dog = new Dog();
// Accessing properties and methods of the parent class
dog.name = "Buddy";
dog.eat(); // From Animal class
dog.sleep(); // From Animal class
// Accessing method of the child class
dog.bark(); // From Dog class
}
}
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
Buddy is eating.
Buddy is sleeping.
Buddy is barking.
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
// Base Class (Parent Class)
class Animal {
// Method to be overridden
public void sound() {
System.out.println("An animal makes a sound.");
}
}
// Derived Class 1 (Child Class)
class Dog extends Animal {
// Overriding the method from the parent class
@Override
public void sound() {
System.out.println("The dog says: Woof Woof!");
}
}
// Derived Class 2 (Child Class)
class Cat extends Animal {
// Overriding the method from the parent class
@Override
public void sound() {
System.out.println("The cat says: Meow!");
}
}
// Class demonstrating Method Overloading
class Calculator {
// Overloaded method 1
public int add(int a, int b) {
return a + b;
}
// Overloaded method 2
public double add(double a, double b) {
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
return a + b;
}
// Overloaded method 3
public int add(int a, int b, int c) {
return a + b + c;
}
}
// Main Class
public class PolymorphismExample {
public static void main(String[] args) {
// Demonstrating Method Overriding (Run-Time Polymorphism)
Animal myAnimal; // Reference of parent class
// Dog object
myAnimal = new Dog();
myAnimal.sound(); // Calls overridden method in Dog class
// Cat object
myAnimal = new Cat();
myAnimal.sound(); // Calls overridden method in Cat class
// Demonstrating Method Overloading (Compile-Time Polymorphism)
Calculator calc = new Calculator();
System.out.println("Addition of two integers: " + calc.add(10, 20));
System.out.println("Addition of two doubles: " + calc.add(5.5, 7.3));
System.out.println("Addition of three integers: " + calc.add(1, 2, 3));
}
}
OUTPUT:
The dog says: Woof Woof!
The cat says: Meow!
Addition of two integers: 30
Addition of two doubles: 12.8
Addition of three integers: 6
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
class Student {
String name;
int age;
// 1. Default Constructor
public Student() {
this.name = "Unknown";
this.age = 0;
System.out.println("Default Constructor called!");
}
// 2. Parameterized Constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Parameterized Constructor called!");
}
// 3. Copy Constructor
public Student(Student other) {
this.name = other.name;
this.age = other.age;
System.out.println("Copy Constructor called!");
}
// Display method to show student details
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class ConstructorDemo {
public static void main(String[] args) {
// Using Default Constructor
Student student1 = new Student();
student1.display();
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
Default Constructor called!
Name: Unknown, Age: 0
Parameterized Constructor called!
Name: Alice, Age: 20
Copy Constructor called!
Name: Alice, Age: 20
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
class Student {
// Static data member: shared among all objects
static int studentCount = 0;
// Non-static data members
String name;
int rollNo;
// Constructor
public Student(String name, int rollNo) {
this.name = name;
this.rollNo = rollNo;
studentCount++; // Increment static variable
System.out.println("Student Created: " + name + ", Roll No: " + rollNo);
}
// Static method to display the total number of students
public static void displayTotalStudents() {
System.out.println("Total Students: " + studentCount);
}
// Non-static method to display student details
public void displayDetails() {
System.out.println("Name: " + name + ", Roll No: " + rollNo);
}
}
public class StaticExample {
public static void main(String[] args) {
// Call static method before any objects are created
Student.displayTotalStudents(); // Output: Total Students: 0
// Create objects of Student class
Student s1 = new Student("Alice", 101);
Student s2 = new Student("Bob", 102);
Student s3 = new Student("Charlie", 103);
// Call static method after creating objects
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
Total Students: 0
Student Created: Alice, Roll No: 101
Student Created: Bob, Roll No: 102
Student Created: Charlie, Roll No: 103
Total Students: 3
Name: Alice, Roll No: 101
Name: Bob, Roll No: 102
Name: Charlie, Roll No: 103
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
// Custom Exception Class
class InvalidAgeException extends Exception {
// Constructor to accept a custom message
public InvalidAgeException(String message) {
super(message);
}
}
public class UserDefinedExceptionDemo {
// Method to validate age
public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above to proceed.");
} else {
System.out.println("Age is valid. You are eligible!");
}
}
public static void main(String[] args) {
try {
System.out.println("Checking Age for: 15");
validateAge(15); // Will throw the custom exception
System.out.println("Checking Age for: 21");
validateAge(21); // Will not throw exception
} catch (InvalidAgeException e) {
// Handle the custom exception
System.out.println("Exception Caught: " + e.getMessage());
} finally {
System.out.println("Age validation process completed.");
}
}
}
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
OUTPUT:
Checking Age for: 15
Exception Caught: Age must be 18 or above to proceed.
Age validation process completed.
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
PROGRAM:
String threadName;
PriorityThread(String name) {
this.threadName = name;
try {
} catch (InterruptedException e) {
System.out.println(e.getMessage());
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
highPriorityThread.setPriority(Thread.MAX_PRIORITY); // Priority 10
mediumPriorityThread.setPriority(Thread.NORM_PRIORITY); // Priority 5
lowPriorityThread.setPriority(Thread.MIN_PRIORITY); // Priority 1
highPriorityThread.start();
mediumPriorityThread.start();
lowPriorityThread.start();
try {
highPriorityThread.join();
mediumPriorityThread.join();
lowPriorityThread.join();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
OUTPUT:
211423243XXX XXX
23ES1411 TECHNICAL SKILL PRACTICES III
211423243XXX XXX