0% found this document useful (0 votes)
40 views29 pages

Programming Practices Questions

This document contains summaries of 10 Java programs related to core Java concepts. The programs cover topics like installing the JDK, variable scope, classes, type casting, and exception handling. Each program includes an algorithm, code sample, and output to demonstrate the concept. The programs are part of a learning activity to help students understand and apply fundamental Java programming principles.

Uploaded by

Boby Rathour
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
40 views29 pages

Programming Practices Questions

This document contains summaries of 10 Java programs related to core Java concepts. The programs cover topics like installing the JDK, variable scope, classes, type casting, and exception handling. Each program includes an algorithm, code sample, and output to demonstrate the concept. The programs are part of a learning activity to help students understand and apply fundamental Java programming principles.

Uploaded by

Boby Rathour
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

1|Page

INDEX
S.No. Description Date Teacher’s Sign

1. Installation of J2SDK
Write a program to show
2.
Scope of Variables
Write a program to show
3. Concept of CLASS in JAVA
Write a program to show Type
4. Casting in JAVA
Write a program to show How
5. Exception Handling is in JAVA
Write a Program to show
6. Inheritance
Write a program to show
7. Polymorphism
Write a program to show
8. Access Specifiers (Public,
Private, Protected) in JAVA
Write a program to show use
9. and Advantages of
CONTRUCTOR
Write a program to show
10. Interfacing between two
classes
2|Page

Program – 1
Installation of J2SDK
Installing the JDK (Java Development Kit) is a crucial step for any Java
programmer. Following good programming practices ensures that the
installation process is smooth and aligns with industry standards. Here are
some programming practices to consider when installing the JDK:

1. Verify System Requirements: Before installing the JDK, make sure your
system meets the minimum requirements specified by the JDK provider. Check
the supported operating systems and hardware specifications.

2. Download from Official Source: Always download the JDK installer from
the official website of the JDK provider, such as Oracle or OpenJDK. Avoid
downloading from third-party sources to ensure authenticity and avoid
potential security risks.

3. Choose the Right Version: Select the appropriate JDK version based on
your project requirements and the features you need. In an academic setting,
you might be required to use a specific JDK version, but in a real-world
scenario, consider using the latest stable version for access to the latest features
and bug fixes.

4. Follow Installation Instructions: Carefully follow the installation


instructions provided by the JDK provider. Pay attention to any additional
settings or configurations required during the installation process.

5. Set Environment Variables: After the installation, set up the required


environment variables to point to the JDK installation directory. This ensures
that your system can locate the Java executable files (java and javac) when you
run Java programs.
3|Page

6. Update PATH Variable: Update the system's `PATH` variable to include the
JDK's `bin` directory. This allows you to run Java commands from any
directory without specifying the full path.

7. Test the Installation: After installation and setting up environment


variables, test the JDK installation by running `java -version` and `javac -
version` in the command prompt or terminal. Ensure that the correct version is
displayed, indicating a successful installation.

8. Keep JDK Updated: Regularly check for updates and security patches from
the JDK provider's website. Staying up-to-date with the latest JDK version
helps improve performance and ensures your code benefits from the latest
features and security fixes.

9. Document the Process: In an academic or professional setting, document


the installation steps and any configurations you made. This documentation can
be helpful when working on different systems or when sharing knowledge with
others.
4|Page

Program – 2
Write a program to show Scope of Variables
Description:
This Java program demonstrates the concept of variable scope in Java. It
declares a class-level variable (`classVar`) and a method-level variable
(`methodVar`). The program shows how these variables can be accessed within
different methods and how method-level variables are limited to their declaring
method.

Algorithm:
1. Declare a class `ScopeDemo`.
2. Declare a class-level variable `classVar` and set it to 10.
3. Define the `main` method:
a. Declare a method-level variable `methodVar` and set it to 20.
b. Print the values of `classVar` and `methodVar`.
c. Call the `accessLocalVariable` method.
4. Define the `accessLocalVariable` method:
a. Print the value of `classVar`.

Program: ScopeDemo.java

public class ScopeDemo {

static int classVar = 10;

public static void main(String[] args) {

int methodVar = 20;

System.out.println("Class-level variable (classVar): " + classVar);


5|Page

System.out.println("Method-level variable (methodVar): " + methodVar);

accessLocalVariable();

public static void accessLocalVariable() {

System.out.println("Accessing classVar in another method: " + classVar);

Output:
Class-level variable (classVar): 10
Method-level variable (methodVar): 20
Accessing classVar in another method: 10
6|Page

Program – 3
Write a program to show Concept of CLASS in JAVA
Description:
In Java, a class is a blueprint or a template that defines the structure and
behavior of objects. It encapsulates data (attributes) and methods (functions)
that operate on that data. Objects are instances of classes, and they allow us to
create multiple instances of the same type with their own unique data.

Algorithm:
1. Define a class named `Person`.
2. Declare private data members (attributes) such as `name`, `age`, and
`gender`.
3. Define a constructor to initialize the attributes when a `Person` object is
created.
4. Create getter and setter methods to access and modify the attributes of a
`Person`.
5. Define a method `displayInfo()` to display the information of a `Person`
object.

Program: Person.java

public class Person {

private String name;

private int age;

private char gender;

// Constructor to initialize the attributes

public Person(String name, int age, char gender) {


7|Page

this.name = name;

this.age = age;

this.gender = gender;

// Getter methods

public String getName() {

return name;

public int getAge() {

return age;

public char getGender() {

return gender;

// Setter methods

public void setName(String name) {

this.name = name;

public void setAge(int age) {

this.age = age;

public void setGender(char gender) {

this.gender = gender;
8|Page

// Method to display person's information

public void displayInfo() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

System.out.println("Gender: " + gender);

Program: Main.java

public class Main {

public static void main(String[] args) {

// Create a Person object and initialize its attributes

Person person1 = new Person("Alice", 30, 'F');

// Access and display the person's information using getter methods

System.out.println("Person 1 Info:");

System.out.println("Name: " + person1.getName());

System.out.println("Age: " + person1.getAge());

System.out.println("Gender: " + person1.getGender());

// Change person1's age using the setter method

person1.setAge(31);
9|Page

// Display updated information using the displayInfo() method

System.out.println("\nUpdated Person 1 Info:");

person1.displayInfo();

Output:
Person 1 Info:
Name: Alice
Age: 30
Gender: F

Updated Person 1 Info:


Name: Alice
Age: 31
Gender: F
10 | P a g e

Program – 4
Write a program to show Type Casting in JAVA
Description:
Type casting in Java allows you to convert a variable from one data type to
another. Sometimes, you may need to explicitly convert the variable to perform
certain operations or assignments where data types are not compatible.

Algorithm:
1. Declare two variables of different data types, e.g., `int` and `double`.
2. Perform an operation or assignment that requires type casting.
3. Explicitly cast one variable to the desired data type.
4. Print the results before and after type casting.

Program: TypeCastingDemo.java

public class TypeCastingDemo {

public static void main(String[] args) {

// Implicit type casting (Widening Conversion)

int intValue = 50;

double doubleValue = intValue; // int is implicitly cast to double

System.out.println("Implicit casting: int to double");

System.out.println("int value: " + intValue);

System.out.println("double value: " + doubleValue);

// Explicit type casting (Narrowing Conversion)

double doubleValue2 = 123.45;


11 | P a g e

int intValue2 = (int) doubleValue2; // double is explicitly cast to int

System.out.println("\nExplicit casting: double to int");

System.out.println("double value: " + doubleValue2);

System.out.println("int value: " + intValue2);

Output:
Implicit casting: int to double
int value: 50
double value: 50.0

Explicit casting: double to int


double value: 123.45
int value: 123

There are two types of type casting:


1. Implicit casting (Widening Conversion): It happens automatically when
converting a smaller data type to a larger data type, and there is no data loss
(e.g., converting `int` to `double`).
2. Explicit casting (Narrowing Conversion): It requires explicit declaration and
might result in data loss when converting a larger data type to a smaller data
type (e.g., converting `double` to `int`). When narrowing the data type, there is
a risk of losing precision or truncating the fractional part.
12 | P a g e

Program – 5
Write a program to show How Exception Handling is in JAVA
Description:
Exception handling in Java allows you to gracefully handle runtime errors or
exceptional situations that may occur during program execution. By using try-
catch blocks, you can identify and handle exceptions to prevent program
termination and provide meaningful error messages to the users.

Algorithm:
1. Define a Java program that includes a method that may potentially throw an
exception.
2. Use a try-catch block to handle the exception.
3. Within the try block, call the method that can throw an exception.
4. Catch the exception in the catch block and handle it appropriately.

Program: ExceptionHandlingDemo.java

import java.util.Scanner;

public class ExceptionHandlingDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

try {

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int result = divideByZero(number);

System.out.println("Result: " + result);


13 | P a g e

} catch (ArithmeticException ex) {

System.out.println("Exception caught: " + ex.getMessage());

} catch (Exception ex) {

System.out.println("Something went wrong: " + ex.getMessage());

} finally {

scanner.close();

System.out.println("Program completed.");

public static int divideByZero(int number) {

if (number == 0) {

throw new ArithmeticException("Cannot divide by zero.");

return 10 / number;

Output:
Enter a number: 0
Exception caught: Cannot divide by zero.
Program completed.
14 | P a g e

Program – 6
Write a Program to show Inheritance
Description:
Inheritance is an important concept in object-oriented programming (OOP). It
allows one class (subclass or derived class) to inherit the properties and
behaviors of another class (superclass or base class). This enables code reuse
and promotes a hierarchical relationship between classes.

Algorithm:
1. Define a superclass (base class) with common attributes and methods that
are to be inherited.
2. Define a subclass (derived class) that extends the superclass.
3. The subclass automatically inherits all the non-private attributes and
methods from the superclass.
4. Add additional attributes and methods specific to the subclass if needed.

Program: InheritanceDemo.java

// Superclass (Base class)

class Animal {

String species;

int age;

public Animal(String species, int age) {

this.species = species;

this.age = age;

}
15 | P a g e

public void makeSound() {

System.out.println("Animal makes a sound.");

public void displayInfo() {

System.out.println("Species: " + species);

System.out.println("Age: " + age);

// Subclass (Derived class)

class Dog extends Animal {

String breed;

public Dog(String species, int age, String breed) {

super(species, age); // Call the constructor of the superclass

this.breed = breed;

public void makeSound() {

System.out.println("Dog barks: Woof! Woof!");

public void displayInfo() {

super.displayInfo(); // Call the displayInfo() method of the superclass

System.out.println("Breed: " + breed);

}
16 | P a g e

public class InheritanceDemo {

public static void main(String[] args) {

// Create a Dog object and demonstrate inheritance

Dog dog1 = new Dog("Canine", 5, "Labrador");

dog1.displayInfo();

dog1.makeSound();

Output:
Species: Canine
Age: 5
Breed: Labrador
Dog barks: Woof! Woof!

Inheritance allows the `Dog` class to inherit the common attributes and
methods from the `Animal` class, while still having its unique characteristics.
This promotes code reuse and a hierarchical relationship between the classes.
17 | P a g e

Program – 7
Write a program to show Polymorphism
Description:
Polymorphism is another fundamental concept in object-oriented programming
(OOP). It allows a class to take multiple forms or have multiple behaviors. In
Java, polymorphism is achieved through method overriding and method
overloading.

Algorithm:
1. Define a superclass with a method that can be overridden in the subclass.
2. Define a subclass that extends the superclass and overrides the method with
a different implementation.
3. Use method overloading to create multiple methods with the same name but
different parameter lists.

Program: PolymorphismDemo.java

// Superclass

class Animal {

public void makeSound() {

System.out.println("Animal makes a sound.");

// Subclass

class Dog extends Animal {


18 | P a g e

@Override

public void makeSound() {

System.out.println("Dog barks: Woof! Woof!");

public void makeSound(int numTimes) {

for (int i = 0; i < numTimes; i++) {

System.out.print("Woof! ");

System.out.println();

// Another Subclass

class Cat extends Animal {

@Override

public void makeSound() {

System.out.println("Cat meows: Meow! Meow!");

public class PolymorphismDemo {

public static void main(String[] args) {


19 | P a g e

Animal animal1 = new Dog(); // Polymorphism - Dog is treated as an


Animal

Animal animal2 = new Cat(); // Polymorphism - Cat is treated as an Animal

animal1.makeSound(); // Calls Dog's makeSound() (runtime polymorphism)

animal2.makeSound(); // Calls Cat's makeSound() (runtime polymorphism)

Dog dog = new Dog();

dog.makeSound(); // Calls Dog's makeSound()

dog.makeSound(3); // Calls Dog's overloaded makeSound(int numTimes)

Output:
Dog barks: Woof! Woof!
Cat meows: Meow! Meow!
Dog barks: Woof! Woof!
Woof! Woof! Woof!

Additionally, we demonstrate method overloading in the `Dog` class by having


two `makeSound()` methods: one without parameters and one with an `int`
parameter. Method overloading is a form of compile-time polymorphism, as
the decision of which method to call is made at compile time based on the
method signature.
Polymorphism allows us to treat objects of subclasses as objects of the
superclass, enabling greater flexibility and code reusability.
20 | P a g e

Program – 8
Write a program to show Access Specifiers (Public, Private,
Protected) in JAVA
Description:
Access specifiers in Java define the visibility or accessibility of classes,
attributes, methods, and constructors within and outside the class. There are
four types of access specifiers: `public`, `private`, `protected`, and the default
(no specifier).

Algorithm:
1. Define a class with attributes and methods using different access specifiers.
2. Create an object of the class and demonstrate accessing the attributes and
methods from different contexts (inside the class, in the same package, and in a
different package).

Program: AccessSpecifierDemo.java

// Public class accessible from anywhere

public class AccessSpecifierDemo {

// Public attribute accessible from anywhere

public int publicVar = 10;

// Private attribute accessible only within this class

private int privateVar = 20;

// Protected attribute accessible within this class and its subclasses

protected int protectedVar = 30;

// Default (package-private) attribute accessible within the same package


21 | P a g e

int defaultVar = 40;

// Public method accessible from anywhere

public void publicMethod() {

System.out.println("Public method can be accessed from anywhere.");

// Private method accessible only within this class

private void privateMethod() {

System.out.println("Private method can be accessed only within this class.");

// Protected method accessible within this class and its subclasses

protected void protectedMethod() {

System.out.println("Protected method can be accessed within this class and


subclasses.");

// Default (package-private) method accessible within the same package

void defaultMethod() {

System.out.println("Default method can be accessed within the same


package.");

Program: Main.java
22 | P a g e

public class Main {

public static void main(String[] args) {

AccessSpecifierDemo demo = new AccessSpecifierDemo();

// Accessing public attribute and method from outside the class

System.out.println("Public attribute: " + demo.publicVar);

demo.publicMethod();

// Private attribute and method cannot be accessed from outside the class

// Uncommenting the lines below will cause a compilation error.

// System.out.println("Private attribute: " + demo.privateVar);

// demo.privateMethod();

// Protected attribute and method cannot be accessed from outside the


class

// Uncommenting the lines below will cause a compilation error.

// System.out.println("Protected attribute: " + demo.protectedVar);

// demo.protectedMethod();

// Default attribute and method can be accessed from the same package

System.out.println("Default attribute: " + demo.defaultVar);

demo.defaultMethod();

}
23 | P a g e

Output:
Public attribute: 10
Public method can be accessed from anywhere.
Default attribute: 40
Default method can be accessed within the same package.
24 | P a g e

Program – 9
Write a program to show use and Advantages of CONTRUCTOR
Description:
In Java, a constructor is a special method used to initialize objects of a class.
Constructors have the same name as the class and are called automatically
when an object is created using the `new` keyword. They are useful for setting
initial values, allocating resources, and performing necessary tasks when an
object is created.

Advantages of Constructors:
1. Object Initialization: Constructors ensure that objects are properly
initialized with the required initial values when they are created.
2. Automatic Invocation: Constructors are automatically called when an
object is created, so you don't need to manually initialize the object after its
creation.
3. Overloading: You can have multiple constructors with different parameter
lists (constructor overloading), allowing you to create objects with different
initializations.
4. Memory Allocation: Constructors can be used to allocate resources or
perform memory-related tasks when an object is created.
5. Encapsulation: Constructors help encapsulate the object creation process
within the class, ensuring that the object is always in a valid state.

Algorithm:
1. Create a class with a constructor to demonstrate its usage and advantages.
2. Define attributes that represent the object's state.
3. Implement a constructor to initialize the attributes.
4. Create objects using the constructor and observe the initialization process.
25 | P a g e

Program: ConstructorDemo.java

public class ConstructorDemo {

private String name;

private int age;

// Constructor with parameters

public ConstructorDemo(String name, int age) {

this.name = name;

this.age = age;

System.out.println("Object created with constructor: " + this.name + ", " +


this.age + " years old");

// Constructor with default values

public ConstructorDemo() {

this.name = "Unknown";

this.age = 0;

System.out.println("Default object created: " + this.name + ", " + this.age +


" years old");

public void displayInfo() {


26 | P a g e

System.out.println("Name: " + name);

System.out.println("Age: " + age);

public static void main(String[] args) {

ConstructorDemo person1 = new ConstructorDemo("Alice", 30);

ConstructorDemo person2 = new ConstructorDemo();

person1.displayInfo();

person2.displayInfo();

Output:
Object created with constructor: Alice, 30 years old
Default object created: Unknown, 0 years old
Name: Alice
Age: 30
Name: Unknown
Age: 0
27 | P a g e

Program – 10
Write a program to show Interfacing between two classes
Description:
In Java, interfaces allow two or more classes to interact with each other without
sharing a common parent class. An interface defines a contract, specifying a set
of abstract methods that classes implementing the interface must provide
concrete implementations for. This concept is known as "interfacing" between
classes.

Algorithm:
1. Create an interface with abstract method signatures.
2. Implement the interface in one or more classes.
3. Provide concrete implementations for the interface methods in each
implementing class.
4. Use the interface to interact between objects of different classes.

Program:

// Step 1: Create an interface

interface Shape {

double getArea(); // Abstract method to calculate the area

// Step 2: Implement the interface in a class

class Circle implements Shape {

private double radius;

public Circle(double radius) {


28 | P a g e

this.radius = radius;

@Override

public double getArea() {

return Math.PI * radius * radius;

// Step 2: Implement the interface in another class

class Rectangle implements Shape {

private double length;

private double width;

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

@Override

public double getArea() {

return length * width;

}
29 | P a g e

// Step 4: Use the interface to interact between objects of different classes

public class InterfacingDemo {

public static void main(String[] args) {

Circle circle = new Circle(5.0);

Rectangle rectangle = new Rectangle(4.0, 6.0);

printArea(circle);

printArea(rectangle);

// A method that accepts any object of the Shape interface

public static void printArea(Shape shape) {

System.out.println("Area: " + shape.getArea());

Output:
Area: 78.53981633974483
Area: 24.0

In the `InterfacingDemo` class, we demonstrate interfacing between the


`Circle` and `Rectangle` classes by passing objects of these classes to the
`printArea()` method, which accepts any object of the `Shape` interface. This
illustrates how interfaces facilitate interaction between objects of different
classes that implement the same interface.

You might also like