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

Java Programming Practical Exercises

The document contains a series of practical Java programming exercises, including printing squares of numbers using loops, calculating the area of a circle, creating a student class, sorting an array of strings, searching in an array, handling exceptions in division, and demonstrating string class methods. Each practical includes sample code and outputs. The exercises are designed for students at GTB Public School as part of their IT practical file.
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)
11 views8 pages

Java Programming Practical Exercises

The document contains a series of practical Java programming exercises, including printing squares of numbers using loops, calculating the area of a circle, creating a student class, sorting an array of strings, searching in an array, handling exceptions in division, and demonstrating string class methods. Each practical includes sample code and outputs. The exercises are designed for students at GTB Public School as part of their IT practical file.
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 23: Write a JAVA program that print the squares of numbers from 1 to 5 using while

loop.

Code: public class Square {


public static void main(String[] args) {
int num =1;
while(num<=5){
[Link]("Square of "+num);
[Link](" = " + num*num);
++num;
}
}
}

GTB PUBLIC SCHOOL – XII IT PRACTICAL FILE Page 11


Practical 24: Write a JAVA program that print the squares of numbers from 1 to 5 using do-while
loop.

Code: public class SquareUsingDoWhile {


public static void main(String[] args) {
int num =1;
do{
[Link]("Square of "+num);
[Link](" = " + num*num);
++num;
}
while(num<=5);
}
}

GTB PUBLIC SCHOOL – XII IT PRACTICAL FILE Page 12


Practical 25: Write a JAVA method that return the area of a circle.

Code:
import [Link];
public class CalculateArea
{
static double areaOfCircle(){
Scanner sc = new Scanner([Link]);
[Link](" Enter the radius of a circle :");
double radius = [Link]();
double area = [Link]*radius*radius;
return area;
}
public static void main(String[] args)
{
[Link](" Area of circle = "+areaOfCircle()+" sq. m ");
}
}

GTB PUBLIC SCHOOL – XII IT PRACTICAL FILE Page 13


Practical 26: Write a JAVA program to create class student.

Code:
class student_class {
String name;
int rollNo;
void showInfo(){
[Link]("Name: " +name);
[Link]("Roll No: " +rollNo);
}
}
public class Project1 {
public static void main(String[] args)
{
student_class s1= new student_class();
[Link]=" RITA ";
[Link]=30;
[Link]();
}
}

GTB PUBLIC SCHOOL – XII IT PRACTICAL FILE Page 14


Practical 27: Write a program to sort an array of string in alphabetical order.

Code:
import [Link];
public class SortArray
{
public static void main(String[] args) {
String[] alphabets = {"India", "Russia", "Bhutan", "China", "Nepal"};
[Link]("Array Before Sorting :");
for (int i = 0; i< [Link];i++)
{
[Link](alphabets[i]);
}

[Link](alphabets);
[Link]("Array After Sorting :");
for (String alphabet : alphabets)
{
[Link](alphabet);
}
}
}

GTB PUBLIC SCHOOL – XII IT PRACTICAL FILE Page 15


Practical 28: Write a JAVA program to show the array search program and its output.

Code:
import [Link];
import [Link];
public class SearchProgram
{
public static void main(String[] args)
{
double[] score = {67,90,45,23,87,78,83};
// Sorting the array first before using binarySearch
[Link](score);
Scanner Sc = new Scanner([Link]);
[Link](" Enter any number to search : ");
int key = [Link]();
int index = [Link](score, key);
if (index >= 0)
{
[Link](" Element found at position : " +(index+1));
}
else {
[Link]("Element not found ");
}
}
}

GTB PUBLIC SCHOOL – XII IT PRACTICAL FILE Page 16


Practical 29: Write a program that has a method Divide() which takes two numbers as
parameters, divide them and returns the quotient using exception handling.

Code:
public class DivisionExample {
public static void divide(int a, int b ) {
try {
int result =a/b;
[Link](" Result : "+result);
}
catch(ArithmeticException e){
[Link](" Denominator cannot be zero ");
}
finally {
[Link]("Program has completed the try-catch block.");
}
}
public static void main(String[] args) {
divide(10,0);
divide(10,2);
}
}

GTB PUBLIC SCHOOL – XII IT PRACTICAL FILE Page 17


Practical 30: Write a JAVA program for string class method.

Code:
public class StringClass{
public static void main(String[] args) {
String myString = " Hello world ";
[Link]("Given String: " +myString);
[Link]("Length: " +[Link]());
[Link]("char at position 7: "+[Link] (7));
[Link]("indexOf o: "+[Link]("o"));
[Link]("concat 'Today': "+ [Link](" Today"));
[Link]("contains 'Hell': " +[Link](" Hell"));
[Link]("endsWith'old': "+[Link](" old"));
[Link]("equals 'Goodbye World': "+[Link] (" GoodbyeWorld"));
[Link]("equalsIgnorecase 'Helloworld': " +[Link]("
Helloworld"));
[Link]("LowerCase: "+[Link]());
[Link]("Uppercase: "+[Link]());
[Link]("Substring (2, 9): " +[Link](2, 9));
[Link]("Trimmed: '" +[Link]() + "'");
[Link]("Replace 'o' with '@':" +[Link]('o', '@'));
[Link]("Trim + Replace spaces: " +[Link]().replace(" ", "-"));
}
}

GTB PUBLIC SCHOOL – XII IT PRACTICAL FILE Page 18

Common questions

Powered by AI

Using 'trim()' and 'replace()' methods together as shown in the provided Java program first reduces the string by removing leading and trailing white spaces with the 'trim()' method. Subsequently, the 'replace()' method is applied to the trimmed string to substitute occurrences of specified characters or character sequences. This combination enhances string manipulation by first normalizing the string format and then systematically replacing content, resulting in a tidier and potentially more meaningful output, such as spacing being standardized .

The combination of the Scanner class, which facilitates user interaction through input processing, and Array utilities, which offer efficient sorting and searching, creates a synergistic effect enhancing both real-time user data input and subsequent batch processing. The Scanner enables dynamic data entry, while the Array class allows manipulation and evaluation, as seen in user-driven searches in arrays post-sort, streamlining data management while maintaining performance. Such duet helps build programs responsive to real-world data conditions and enables concise implementations of complex operations .

The DivisionExample program anticipates the challenge of dividing by zero, which throws an ArithmeticException. It effectively addresses this by wrapping the division operation in a try-catch block, where any ArithmeticException triggered during the operation is caught, allowing for a user-friendly error message 'Denominator cannot be zero' instead of the program crashing. This proactively handles exceptions, maintaining the program's robustness. Additionally, the use of the finally block ensures that certain clean-up operations (e.g., logging) are executed regardless of whether an exception occurred .

In the provided sources, method overloading is not explicitly demonstrated; however, understanding its impact involves recognizing its role in improving code readability and manageability. In scenarios like calculating areas or processing student information, method overloading could allow different inputs or parameters, enhancing flexibility. It enables defining multiple methods with the same name but different parameters within a class, allowing for differentiated functionalities while simplifying method calls without forcing a developer to recall multiple distinct function names .

The observed trend when utilizing Arrays.sort() to sort a string array in Java is a lexicographical order where uppercase letters precede lowercase given their ASCII values. The method facilitates this by implementing a dual-pivot quicksort for primitives, adapting its algorithm to Java's natural ordering. It processes string characters based on Unicode, resulting in alphabetical order as demonstrated by the rearrangement of 'India', 'Russia', etc., into a coherent sequence, thereby ensuring consistency and efficiency .

In the provided Java programs, the difference between while and do-while loops lies in their execution flow. The while loop checks the condition before executing the block of code, which means if the condition is false initially, the block may not execute at all. In contrast, the do-while loop executes the block of code once before checking the condition due to its bottom testing nature, ensuring the block is executed at least once. This difference implies that the do-while loop guarantees at least one execution, even if the initial condition is false .

The CalculateArea program could be improved by adding input validation to ensure users enter a valid numeric value for the radius. This includes checking for non-numeric input that would cause exceptions and validating that the radius is non-negative, as negative values are non-sensical in this context. Enhancements might include try-catch blocks for handling InputMismatchExceptions and logical checks for ensuring positive radius values before proceeding with area calculation .

Sorting an array before applying binary search is crucial because binary search is an efficient algorithm that requires the list to be ordered. Its operational efficiency stems from repeatedly dividing the search interval in half, which only works accurately if the elements are sorted; otherwise, binary search would not guarantee correct results. This reliance on elementary order underscores sorting as a prerequisite and enhances the search's complexity efficiency to O(log n) rather than a linear O(n).

The program demonstrates encapsulation by defining the 'student_class' with data attributes 'name' and 'rollNo', and a method 'showInfo' to display these attributes. Although it doesn't exemplify full encapsulation (as there's no use of private access modifiers), it lays basic groundwork by packaging related data and methods, thereby organizing code within class structures. The lack of encapsulation through access controls suggests room for improvement to protect data from external modification directly .

Dynamic instantiation of objects in the 'student_class' program highlights dynamic memory allocation and object-oriented flexibility whereby objects like 's1' are instantiated at runtime using the 'new' keyword. This approach allows programs to tailor object creation to runtime needs, facilitating memory management and allowing developers to dictate how and when objects exist within a program's lifecycle. This dynamic approach aligns with key OOP principles, enabling varied behaviors through different object instances .

You might also like