[Go to site: main page, start]

0% found this document useful (0 votes)
24 views7 pages

Java Practical Programs Overview

The document contains a series of Java programming exercises that cover various concepts such as printing odd numbers, calculating series summation, comparing numbers, generating random numbers, using arrays, user-defined functions, constructors, string manipulation, input streams, sorting arrays, and control flow statements like loops and switch cases. Each exercise includes a code snippet and its corresponding output. The exercises are designed to help learners practice and understand fundamental Java programming skills.

Uploaded by

sakshamsingla295
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)
24 views7 pages

Java Practical Programs Overview

The document contains a series of Java programming exercises that cover various concepts such as printing odd numbers, calculating series summation, comparing numbers, generating random numbers, using arrays, user-defined functions, constructors, string manipulation, input streams, sorting arrays, and control flow statements like loops and switch cases. Each exercise includes a code snippet and its corresponding output. The exercises are designed to help learners practice and understand fundamental Java programming skills.

Uploaded by

sakshamsingla295
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

Java Lab

Practicals
1) Write a program to Print Odd numbers from 1 to 9 :
class odd { public static void main(String[] args)
{
[Link]("Odd table is ");
for (int i=1;i<=10;i=i+2)
{ [Link](i);
} }}
OUTPUT: 1
3
5
7
9
2) Write a program to print series summation program that uses a Java variable n :
public class SeriesSum
{
public static void main (String [] args)
{
int n = 9;
[Link]((n * (n + 1)) / 2);
}
}
OUTPUT: 45

3) Write a program to compare two numbers using if else if statements:


public class CompareTwoNumbers
{
public static void main(String[] args)
{
int num1 = 324;
int num2 = 234;
if(num1 > num2)
{
[Link](num1 + " is greater than " + num2);
}
else if(num1 < num2)
{
[Link](num1 + " is less than " + num2);
}
Else
{ [Link](num1 + " is equal to " + num2);
}}}
OUTPUT: 324 is greater than 234
4) Write a program to generate 5 Random nos. between 1 to 100, and it should not
follow with decimal point :
class RandomDemo
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
[Link]((int)([Link]()*100));
}}}
5) Write a program to declare, Initialize and print an Array :
class ArrayProgram
{
public static void main(String args[])
{
double[] marks = {346, 144, 103, 256.5, 387.5};
for (int i = 0; i<[Link] ; i++)
{
[Link](marks[i]);
}
OUTPUT: 346
144
103
256.5
387.5
6) Write a program to show the use of User Defined Function :
class MethodProgram
{
static double rectangle_area (double length, double breadth)
{
return (length * breadth);
}
public static void main(String args[])
{
double a = 0;
a = rectangle_area(45.5, 78.5);
[Link]("Area of the rectangle = "+ a);
}
}
OUTPUT: Area of the rectangle = 3571.75
7) Write a program to show the use of Constructor :
class Book
{
Book()
{
title = "";
author = "";
publisher = "";
price = 0;
[Link](“Title=”+title);
[Link](“Author=”+author);
[Link](“Publisher=”+publisher);
[Link](“Price=”+price);
}
public static void main(String[] args)
{
Book book1 = new Book( );
[Link]="Game of Thrones";
[Link]="George R Martin";
[Link]= "Harper Collins";
[Link]= 320.0;
[Link]();
}
OUTPUT: title="Game of Thrones";
author="George R Martin";
publisher= "Harper Collins";
price= 320.0;

8) Write a java program to create a String :


class Book
{
public static void main(String[] args)
{
String first =”Java”;
String second=”C++”;
[Link](first);
[Link](second);
}}
OUTPUT: Java
C++
9) Write a java program to use Input Stream:
import [Link].*;
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner([Link]); //[Link] is a standard input stream
[Link]("Enter first number- ");
int a= [Link]();
[Link]("Enter second number- ");
int b= [Link]();
[Link]("Enter third number- ");
int c= [Link]();
int d=a+b+c;
[Link]("Total= " +d);
}
}
OUTPUT: Enter first number-10
Enter second number-20
Enter first number-30
Total= 60
10) Write a Java Program to have taken string input:
import [Link].*;
class UserInputDemo1
{
public static void main(String[] args)
{
Scanner sc= new Scanner([Link]); //[Link] is a standard input stream
[Link]("Enter a string: ");
String str= [Link](); //reads string
[Link]("You have entered: "+str);
}
}
11) Write a Java Program to sort an array:
import [Link];
public class SortArrayExample1
{
public static void main(String[] args)
{
//defining an array of integer type
int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};
//invoking sort() method of the Arrays class
[Link](array);
[Link]("Elements of array sorted in ascending order: ");
//prints array using the for loop
for (int i = 0; i < [Link]; i++)
{
[Link](array[i]);
}}}
OUTPUT : Array elements in ascending order:
5
12
22
23
34
67
90
109

12) Write a Java Program to show the use of DoWhile loop :


public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
[Link](i);
i++;
}while(i<=10);
}} OUTPUT : 1
2
3
4
5
6
7
8
9
10
13) Write a Java Program to show the use of While loop :
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
[Link](i);
i++;
}} }
14) Write a Java Program to show the use of break statement :
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
[Link](i);
} } }

15) Write a Java Program to show the use of Switch :


public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: [Link]("10");
break;
case 20: [Link]("20");
break;
case 30: [Link]("30");
break;
//Default case statement
default:[Link]("Not in 10, 20 or 30");
} }}

OUTPUT : 20

Common questions

Powered by AI

The 'for' loop is used for a known number of iterations determined by initialization, condition, and update in a single expression, ideal for collections or ranges. The 'while' loop, seen in Source 2, depends on continuous condition evaluation and repeats until the condition evaluates false and is suitable for cases where iterations depend on dynamic conditions potentially unknown beforehand. Evaluative choice between them relies on readability and operational context .

Source 1 uses the Scanner class to handle user inputs in two separate ways: as integers with `nextInt()` and as strings with `nextLine()`. The program prompts for three integers, sums them, and displays the total in one instance, while another example reads a string from the user, showcasing input handling for both numerical and textual data types using System.in .

The program in Source 1 prints odd numbers from 1 to 9 using a 'for' loop that starts at 1, increments by 2, and continues as long as the loop counter is less than or equal to 10. This ensures only odd numbers (1, 3, 5, 7, 9) are printed. The termination condition of the loop is set by 'i<=10', ensuring no even numbers are included .

The 'do-while' loop in Source 2 guarantees execution of the loop body at least once before checking the continuation condition. This contrasts with the standard 'while' loop, where the condition is checked before the body can execute. This feature of 'do-while' supports conditions where initial iteration is necessary prior to evaluation and continued loops are contingent on post-run verification .

The switch statement in Source 2 directs program execution based on the value of the variable 'number'. Different cases correspond to specific values (10, 20, 30), executing the associated block of code. If none match, the default case is executed, demonstrating a clear alternative execution path when none of the specified cases apply. This illustrates a structured approach to branching logic beyond simple if statements .

The program uses if-else if statements to compare two integers, num1 and num2. If num1 is greater than num2, it prints that num1 is greater; otherwise, if num1 is less, it prints num1 is less. If neither condition is true, then the numbers are equal. The structure allows for clear, conditional checking of each possible relationship between the two numbers .

The program stores double values in an array named 'marks'. It initializes the array with specific values (346, 144, 103, 256.5, 387.5) and uses a for-loop to iterate through the array's elements, printing each value to the console in sequence, demonstrating array initialization and iteration in Java .

In the Java program, random numbers are generated by Math.random(), which returns a double value greater than or equal to 0.0 and less than 1.0. The numbers are then multiplied by 100 to scale up to the range 1 to 100, and an explicit cast to int (int)(Math.random()*100) is performed to truncate any decimal portion, ensuring whole numbers .

The 'rectangle_area' method serves as a user-defined function to calculate the area of a rectangle given its length and breadth. It takes two parameters, performs the area calculation via the formula (length * breadth), and returns the computed area. This demonstrates encapsulation, reusability, and abstraction in Java programming by allowing rectangle area calculations to be defined in a single place and called with different input values .

The Book class includes a constructor that initializes the object's String attributes to empty values and the double attribute ‘price’ to 0. It also contains a display method to print these properties. The program demonstrates object instantiation and initial property setting via the constructor, illustrating encapsulation. Following object creation, the Book's attributes are set to specific values and printed, leveraging the constructor for default configuration and subsequent attribute customization .

You might also like