0% found this document useful (0 votes)
8 views3 pages

Java Programming Practical Examples

Uploaded by

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

Java Programming Practical Examples

Uploaded by

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

Java practical answers

1.
public class SumOfNumbers4
{
public static void main(String args[])
{
int x = [Link](args[0]); //first arguments
int y = [Link](args[1]); //second arguments
int sum = x + y;
[Link]("The sum of x and y is: " +sum);
}
}

2.

class FactorialExample{
public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
[Link]("Factorial of "+number+" is: "+fact);
}
}
OUTPUT

Factorial of 5 is: 120

3.

To convert a decimal to binary number

public class Cnvrt {


public static void main(String[] args) {
int dec = 23;
int b1 = 0;
int rem;
int rev = 1;
while (dec > 0) {
rem = dec % 2;
// storing remainder
dec = dec / 2;
// dividing the given decimal value
b1 = b1 + rem * rev;
// reversing the remainders and storing it
rev = rev * 10;
}
[Link]("Binary value of given decimal number: " + b1);
}
}

OUTPUT –

Binary value of given decimal number is 10111.

4.

Write a program that show working of different functions of String and StringBufferclasss like
setCharAt(, setLength(), append(), insert(), concat()and equals().

public class StringProgram {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("SIDDHARTH");

StringBuilder stbr = new StringBuilder("RAHUL IS A GOOD BOY");

[Link]("Original String : " + stbr);

[Link](0, 'S'); // change the char

[Link]("After using setCharAt(0,'S') : " + stbr);

[Link](true); // ret

[Link]("After using append() " + stbr);

[Link]("Original length : " + [Link]() + " string :" + sb);

[Link](5);

[Link]("After using setLength(5) length : " + [Link]() + " string :" + sb);

[Link](3, 'R');
[Link]("After using insert(3,'R') " + sb);

String str1 = "AMAN", test = "AMAN";

String str2 = " KUMAR";

[Link]([Link](test)); // returns true

[Link]([Link](str2)); // returns false

[Link]([Link](str2));

OUTPUT _
Original String : RAHUL IS A GOOD BOY

After using setCharAt(0,'S') : SAHUL IS A GOOD BOY

After using append() SAHUL IS A GOOD BOYtrue

Original length : 9 string :SIDDHARTH

After using setLength(5) length : 5 string :SIDDH

After using insert(3,'R') SIDRDH

true

false

AMAN KUMAR

Common questions

Powered by AI

The equals() method checks for value equality between String objects, thus confirming if the contents of two strings are identical. In the provided example, 'AMAN'.equals('AMAN') returns true, while comparing against ' KUMAR' returns false. This method is crucial for ensuring logical comparisons rather than comparing references, which impacts decision-making processes in applications—such as validating user input or executing conditional logic based on string content—ensuring robust string management within Java applications .

The FactorialExample class computes the factorial by initializing a variable 'fact' to 1 and iteratively multiplying it by each integer up to the specified number, which is 5 in this case. The loop runs from 1 to the number, cumulatively multiplying and storing the result in 'fact'. The final value after the loop represents the factorial, which is printed as 120 for the number 5. This approach effectively uses a simple iteration to calculate the product of all positive integers up to the specified number, demonstrating basic iteration and multiplication .

The numeric conversions in classes like Cnvrt focus on algorithmic transformations using arithmetic operations, resulting in new numeric representations without intermediate objects. These operations are computationally efficient as they do not involve object creation or manipulation of immutable types. In contrast, string manipulations in StringBuffer or StringBuilder manage textual data using mutable objects, allowing direct modification of content. This mutability is key to avoiding inefficiencies related to constant reallocation and copying inherent in typical String operations. By leveraging mutable objects, string manipulations achieve efficient updates and flexibility, as opposed to numeric manipulations which focus on computational efficiency through iterative algorithms .

The SumOfNumbers4 class takes two command-line arguments, converts them from strings to integers using Integer.parseInt(args[]), and calculates their sum by adding these integers together. It then prints the result with System.out.println. This approach is useful in scenarios where dynamic user input is required for arithmetic calculations, such as in command-line calculators or automated scripts where inputs are supplied during execution .

In the StringProgram class, the append() function adds content to the end of a StringBuilder object, changing 'SAHUL IS A GOOD BOY' to 'SAHUL IS A GOOD BOYtrue'. This method modifies the existing object, avoiding the need to create a new string, thus enhancing performance by reducing memory and processing overhead associated with string concatenation. The in-place modification principle of append() is critical to optimized string operations, particularly in situations with frequent updates to string content .

The Cnvrt class converts a decimal number to binary by repeatedly dividing the number by 2 and storing the remainder. It starts with the decimal number 23 and continuously updates the number by division, retrieving remainders using modulo operation ('%'). These remainders (1 or 0) represent the binary digits, which are then accumulated into a result variable 'b1' using multiplication by powers of 10 to maintain positional values. This repeated division forms the basis of binary conversion, where 10111 is ultimately produced as the binary equivalent .

StringBuffer is synchronized, making it thread-safe for use in multi-threaded environments, albeit with added overhead due to synchronization. In contrast, StringBuilder does not implement synchronization, leading to better performance in single-threaded applications where thread safety isn't a concern. When used in single-threaded contexts, StringBuilder provides faster execution and less overhead, making it preferable for high-performance scenarios that involve extensive string manipulation, as implied by the Java classes provided .

In the StringProgram class, StringBuffer and StringBuilder enhance string manipulation by providing methods like setCharAt, append, setLength, and insert. These methods allow in-place modifications of mutable strings without creating new objects, improving performance. StringBuffer is synchronized and thread-safe, while StringBuilder is not, making the latter faster for single-threaded environments. Their use in this program demonstrates efficient manipulation of strings compared to immutable String objects, reducing overhead in scenarios involving repetitive modifications, such as dynamic rendering of UI components .

The setLength() method of StringBuffer truncates the buffer to a specified length, effectively reducing the amount of character data it holds, as shown by shortening 'SIDDHARTH' to 'SIDDH'. This is useful for efficiently managing memory when only a portion of the buffer is needed. The setCharAt() method changes a character at a specific index, modifying 'RAHUL IS A GOOD BOY' to 'SAHUL IS A GOOD BOY', demonstrating inline modification capability without creating new strings. This ability to mutate strings while conserving resources makes StringBuffer indispensable in performance-critical applications .

setLength() in StringBuffer sets the buffer size, either truncating or padding with null characters. It's crucial for managing buffer size constraints and controlling memory usage. The insert() method adds specified data at a given position within the buffer, allowing for modification without creating new objects. In the provided example, setLength() reduced 'SIDDHARTH' to 'SIDDH', while insert() added a character 'R' within the string, showing its utility in managing dynamic text data efficiently and flexibly, reflecting in customizing outputs with minimal overhead .

You might also like