0% found this document useful (0 votes)
19 views8 pages

Java Programming Concepts and Examples

The document contains multiple Java programming assignments demonstrating various concepts such as class and object implementation, data types, variables, looping and conditional statements, user-defined methods, and array usage. Each section includes a program example along with its output, showcasing practical applications of Java programming. The assignments cover creating classes, using static and instance variables, performing arithmetic operations, and handling arrays.

Uploaded by

anshpatel1093
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views8 pages

Java Programming Concepts and Examples

The document contains multiple Java programming assignments demonstrating various concepts such as class and object implementation, data types, variables, looping and conditional statements, user-defined methods, and array usage. Each section includes a program example along with its output, showcasing practical applications of Java programming. The assignments cover creating classes, using static and instance variables, performing arithmetic operations, and handling arrays.

Uploaded by

anshpatel1093
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Practical Assignment-2

1. Write a JAVA program to Implement of class and object.


Program:

class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
[Link]=101;
[Link]="Sonoo";
[Link]=102;
[Link]="Amit";
//Printing data
[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);
}
}
Output:

101 Sonoo

102 Amit
2. Write a JAVA program to Implement of data types, variables, local
variables, and static variables.
Program:

public class VariablesDemo {

// Static variable
static int staticVariable = 50;

// Instance variable
int instanceVariable;

// Constructor to initialize the instance variable


public VariablesDemo(int instanceVariable) {
[Link] = instanceVariable;
}

// Method to demonstrate local variables


public void demonstrateLocalVariable() {
// Local variable
int localVariable = 10;
[Link]("Local Variable: " + localVariable);
}

// Method to display instance and static variables


public void displayVariables() {
[Link]("Instance Variable: " + instanceVariable);
[Link]("Static Variable: " + staticVariable);
}

// Main method
public static void main(String[] args) {
// Creating an object of VariablesDemo
VariablesDemo demo1 = new VariablesDemo(20);
VariablesDemo demo2 = new VariablesDemo(30);

// Displaying variables for demo1


[Link]();

// Displaying variables for demo2


[Link]();

// Demonstrating local variable


[Link]();

// Modifying static variable


[Link] = 100;
// Displaying variables again to see the effect of static variable modification
[Link]();
[Link]();
}
}
Output:

Instance Variable: 20
Static Variable: 50
Instance Variable: 30
Static Variable: 50
Local Variable: 10
Instance Variable: 20
Static Variable: 100
Instance Variable: 30
Static Variable: 100
3. Write a JAVA program using Looping statements, conditional
statements.

Program:

import [Link];

public class NumberOperations {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Take input from the user


[Link]("Enter a positive integer: ");
int number = [Link]();

// Check if the number is even or odd using if-else


if (number % 2 == 0) {
[Link](number + " is even.");
} else {
[Link](number + " is odd.");
}

// Print the multiplication table using a for loop


[Link]("Multiplication table of " + number + ":");
for (int i = 1; i <= 10; i++) {
[Link](number + " x " + i + " = " + (number * i));
}

// Find and print the factorial using a while loop


int factorial = 1;
int tempNumber = number;
while (tempNumber > 0) {
factorial *= tempNumber;
tempNumber--;
}
[Link]("Factorial of " + number + " is " + factorial);

// Print a message based on the value of the number using switch


switch (number) {
case 1:
[Link]("You entered one.");
break;
case 2:
[Link]("You entered two.");
break;
case 3:
[Link]("You entered three.");
break;
default:
[Link]("You entered a number greater than three.");
break;
}

// Close the scanner


[Link]();
}
}
Output:
Enter a positive integer: 5
5 is odd.
Multiplication table of 5:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Factorial of 5 is 120
You entered a number greater than three.
4. Write a JAVA program to Implement user-defined methods, instance
method, static method.
Program:

public class MathOperations {

// Instance method to add two numbers


public int add(int a, int b) {
return a + b;
}

// Static method to multiply two numbers


public static int multiply(int a, int b) {
return a * b;
}

// User-defined method to demonstrate instance and static methods


public void demonstrateMethods() {
int num1 = 5;
int num2 = 3;

// Calling the instance method


int sum = add(num1, num2);
[Link]("Sum (using instance method): " + sum);

// Calling the static method


int product = multiply(num1, num2);
[Link]("Product (using static method): " + product);
}

// Main method
public static void main(String[] args) {
// Create an object of MathOperations
MathOperations mathOps = new MathOperations();

// Call the user-defined method to demonstrate instance and static methods


[Link]();
}
}

Output:
Sum (using instance method): 8
Product (using static method): 15
5. Write a JAVA program to Implement single dimensional array,
multidimensional array.
Program:

public class ArraysDemo {

public static void main(String[] args) {


// Single-dimensional array
int[] singleDimArray = {1, 2, 3, 4, 5};

// Print elements of single-dimensional array


[Link]("Single-dimensional array elements:");
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + singleDimArray[i]);
}

// Multi-dimensional array (2D array)


int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Print elements of multi-dimensional array


[Link]("\nMulti-dimensional array elements:");
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < multiDimArray[i].length; j++) {
[Link]("Element at [" + i + "][" + j + "]: " + multiDimArray[i][j]);
}
}

}
}
Output:

Single-dimensional array elements:


Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5

Multi-dimensional array elements:


Element at [0][0]: 1
Element at [0][1]: 2
Element at [0][2]: 3
Element at [1][0]: 4
Element at [1][1]: 5
Element at [1][2]: 6
Element at [2][0]: 7
Element at [2][1]: 8
Element at [2][2]: 9

Common questions

Powered by AI

The Java program utilizes a combination of control flow statements such as if-else, for, while, and switch to handle different scenarios. Initially, it uses if-else to determine if a number is even or odd based on the modulus operation (number % 2). The for loop is employed to print the multiplication table from 1 to 10. A while loop calculates the factorial by decrementing the value of tempNumber. Finally, the switch statement checks the number and prints corresponding messages for specific cases like 1, 2, and 3, defaulting to a message for numbers greater than three .

Arrays in Java provide a structure to store multiple elements of the same type, allowing indexed access to each element for efficient iteration and manipulation. A single-dimensional array, demonstrated by 'int[] singleDimArray = {1, 2, 3, 4, 5}', stores elements in a linear form, each accessed via an index [0 to array.length-1]. Multi-dimensional arrays allow storage in tabular form. 'int[][] multiDimArray = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }' showcases a two-dimensional array where elements are accessed using two indices, representing rows and columns. Such structures are essential for operations requiring data representation beyond linear structure, like matrices .

The program uses a while loop to calculate the factorial by initializing a 'factorial' variable to 1 and multiplying it successively with decrements of 'tempNumber', which starts as the input number. This iterative approach is beneficial because it iteratively multiplies numbers from the input down to 1, effectively computing the factorial in a clear manner that mirrors the mathematical definition. The advantage lies in simplicity and direct translation from algorithm to code, though it could be optimized for large numbers or replaced by a recursive approach for potential clarity improvements .

Methods in Java are essential in demonstrating object-oriented principles such as encapsulation, abstraction, and polymorphism. In the MathOperations class, the instance method 'add' (encapsulation) hides the implementation details of addition, offering a simple interface to perform arithmetic operations. The static method 'multiply' demonstrates abstraction by providing the functionality without needing an object. By separating logic into methods, even static and instance methods can be used polymorphically in larger interfaces, though not shown here explicitly, illustrating Java's support for polymorphic behavior through method overriding and interface implementation .

User-defined methods allow for modularity and code reuse in Java programs. In the provided MathOperations class, the instance method 'add' is designed to add two integers and a static method 'multiply' multiplies two integers. These clear, specific tasks encapsulate logic, helping segregate functionality into manageable chunks. By calling demonstrateMethods, the program illustrates how both instance and static methods are invoked and how encapsulation improves readability. Use of such methods aids maintainability by allowing isolated updates to logic without affecting the overall program .

The program exemplifies encapsulation by defining class fields (id, name) and methods within the Student class that manage its state, with main methods accessing these via object references. Encapsulation ensures internal states of objects are protected from unintended interference. Object instantiation is shown through 'new' keyword use, creating distinct Student objects with unique states. These concepts underpin Java's object-oriented paradigm, where encapsulation ensures a clear separation of concerns and object instantiation facilitates modular program design, promoting reusability and clearer code organization .

The program captures user input through a Scanner instance, expecting integer input. It checks if the input number is even or odd, and executes subsequent operations. However, the program lacks input validation, which is critical to handle non-integer inputs or invalid data gracefully. To improve, the program could include try-catch blocks to catch InputMismatchException for non-integer values and loop back to prompt user input again, ensuring input is valid before proceeding with operations, thus enhancing robustness against incorrect input types .

Local variables in Java are declared within a method and can be used only within the scope of that method. They are instantiated upon method entry and destroyed upon exit. In the VariablesDemo class, the demonstrateLocalVariable method defines a local variable 'localVariable' assigned a value of 10. This variable is used solely within this method, showcasing that it exists only during the execution of demonstrateLocalVariable. By being local, the variable's memory usage is limited to the method's duration, which optimizes resource management .

The Java program demonstrates the use of various looping constructs including for and while loops. The for loop prints the multiplication table by iterating from 1 to 10, highlighting the loop's aptitude for tasks with a known iteration count. The while loop calculates the factorial of a number using a condition that depends on another variable instead of a fixed range, which shows its flexibility for unknown iteration lengths. Looping constructs like these reduce code redundancy, improve readability and maintain control over iteration, leading to efficient execution of repetitive tasks .

Instance variables in Java are specific to each object instance of a class, meaning that each object maintains its separate copy. In the provided example, the class VariablesDemo has an instance variable 'instanceVariable', which is initialized through the constructor and holds different values (20 and 30) for demo1 and demo2 objects, respectively. Static variables, on the other hand, belong to the class as a whole and are shared across all instances of the class. The 'staticVariable' is a static variable, initially set to 50, and when modified to 100, it reflects this change across all instances as shown in the output when both demo1 and demo2 report the static variable value as 100 after the modification .

You might also like