[Go to site: main page, start]

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

Java Lab Programs and Examples

Uploaded by

Tejaswini Beri
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)
10 views7 pages

Java Lab Programs and Examples

Uploaded by

Tejaswini Beri
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 Programming Lab Programs

Additional Lab Programs:


1. Develop a java program to display the following output.
1
12
123
1234
A. Source Code:

class Display{
public static void main(String[] args){
for(short i=1;i<=4;i++)
{
for(short j=1;j<=i;j++)
{
[Link](j);
}
[Link]();
}
}
}

Output:1
12
123
1234
2. Design a java program to find the factorial of a given number.
[Link] code:
import [Link];
class Factorial{
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
[Link]("Enter a number : ");
int fact=1,n;
n=[Link]();
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
[Link]("Factorial of"+n+" is "+fact);
}
Output:
Enter a number :
5
Factorial of5 is 120

3. Develop a java program to display the following output.


*
**
***
****
Source Code:
class Display1 {
public static void main(String[] args) {
for(short i=1;i<=4;i++)
{
for(short j=1;j<=i;j++)
{
[Link](“*”);
}
[Link]();
}
}
}
Output:*
**
***
****
4. Write a java method to find minimum value in given two values.
A. Source Code:
import [Link];
class Display{
void min(int n1,int n2)
{
if(n1<n2)
{
[Link](n1+" is minimum value");
}
else
{
[Link](n2+" is minimum value");
}
}
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
[Link]("Enter two Values :");
int n1,n2;
n1=[Link]();
n2=[Link]();
Display d=new Display();
[Link](n1,n2);
}
}
Output:
Enter two Values :
16
24
16 is minimum value

5. Write a Java program to check whether given number is Armstrong or not.

[Link] Code:

import [Link];
class ArmstrongNumber {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
int temp = number;
int result = 0;
int n = [Link](number).length();
while (temp!= 0) {
int remainder = temp% 10;
result +=+[Link](remainder, n);
temp=temp/10;
}
if (result == number) {
[Link](number + " is an Armstrong number.");
}
else {
[Link](number + " is not an Armstrong number.");
}
}
}

Output:
Enter a number:153
153 is an Armstrong number.
6. Write a java program that checks whether the given number is Palindrome or not.
[Link] Code:
import [Link];
class Palindrome {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
int temp = number;
int rev=0;
while (temp!= 0) {
int remainder = temp% 10;
rev=rev*10+remainder;
temp=temp/10;
}
if (rev== number) {
[Link](number + " is Palindrome.");
}
else {
[Link](number + " is not Palindrome.");
}
}
}
Output:
Enter a number: 121
121 is Palindrome.

7. Write a java program to implement constructor overloading.


Source Code:

class Sum{
int a,b,c;
Sum(int x, int y)
{
a=x;
b=y;
}
Sum(int x, int y,int z)
{
a=x;
b=y;
c=z;
}
void display()
{
[Link]("sum is "+(a+b+c));
}
public static void main(String[] args)
{
Sum s1=new Sum(10,20);
Sum s2=ne Sum(10,20,30);
[Link]();
[Link]();
}
}

Output: Sum is 30
Sum is 60

8. Write a program that creates two threads. Fist thread prints the numbers from 1 to 10
and the other thread prints the numbers from 10 to 1.
[Link] Code:
class Thread1 extends Thread{
public void run(){
for(int i=1;i<=10;i++){
[Link]("Thread 1 i= "+i);
}
}
}
class Thread2 extends Thread{
public void run(){
for(int i=10;i>=0;i--){
[Link]("Thread 2 i= "+i);
}
}
}
class ThreadRun
{
public static void main(String[] args){
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
[Link]();
[Link]();
}
}
Output:
Thread 1 i= 1
Thread 1 i= 2
Thread 1 i= 3
Thread 1 i= 4
Thread 1 i= 5
Thread 1 i= 6
Thread 1 i= 7
Thread 1 i= 8
Thread 2 i= 10
Thread 1 i= 9
Thread 1 i= 10
Thread 2 i= 9
Thread 2 i= 8
Thread 2 i= 7
Thread 2 i= 6
Thread 2 i= 5
Thread 2 i= 4
Thread 2 i= 3
Thread 2 i= 2
Thread 2 i= 1
Thread 2 i= 0

9. Write an applet code to display “Hello World!”.


[Link] code:

File name:[Link]

import [Link];
import [Link];
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello World!", 20, 20);
}
}
File name: [Link]

<html>
<head>
<title>HelloWorld Applet</title>
</head>
<body>
<applet code="[Link]" width="300" height="200"></applet>
</body></html>
Compilation :javacHelloWorld [Link]
appletviewerHelloWorld [Link]

Output:

Common questions

Powered by AI

The potential pitfalls include an integer overflow due to the factorial growing very rapidly, which will yield incorrect results for large inputs. Since the factorial is defined for positive integers, the use of an integer data type limits the size of calculable factorials to the range of an int. This limitation makes the program unsuitable for inputs larger than 12 with accurate results. To handle larger inputs, convert the integer to BigInteger .

To make the Armstrong number program robust against invalid inputs, use a try-catch block around the input parsing logic. Surround the nextInt() method with try-catch to catch InputMismatchException. Prompt the user for a correct input instead of letting the program crash with an error message. Example: try { number = sc.nextInt(); } catch (InputMismatchException e) { System.out.println("Invalid input, please enter a valid integer."); } .

Constructor overloading in Java enhances class design by allowing different ways to initialize an object, giving more flexibility and providing a clear separation of various object configurations. It improves usability by allowing developers to create instances with varying initial conditions without needing multiple different methods. This leads to cleaner code with intuitive object creation, as seen in the class Sum example where different constructors are used to initialize objects with or without the third parameter .

If the program is to handle negative numbers, it should start by checking if the input number is negative and immediately print that it cannot be an Armstrong number. Armstrong numbers are defined only for non-negative integers, as they involve sums of digits powered to a certain length. Thus, the program could include an initial condition: if(number < 0) { System.out.println(number + " is not an Armstrong number."); return; } .

Advantages of using the Scanner class include ease of use, as it provides methods for parsing primitive types and strings with regular expressions. It's also versatile for different input types (e.g., int, double). However, disadvantages include overhead with small I/O operations due to buffering and a potential delay in handling non-integer inputs, which require additional parsing logic or exception handling to prevent crashes on invalid inputs .

To synchronize the output sequence of numbers from the two threads, you can use synchronization primitives like wait() and notify() or Locks. You'd create a shared monitor object and control sequence execution within the run methods using synchronized blocks. For each increment or decrement in a thread, call wait() on the monitor in one thread and notify() in another thread to alternate the execution between two threads .

The primary difference between implementing a palindrome check for strings versus numbers lies in the data type and operations used. For numbers, you convert the integer to its reverse using mathematical operations (modulus and division), whereas for strings, you use character access and comparison. The structure of the code for numbers involves arithmetic within a while loop to reverse the number, while for strings, it involves using methods like reverse() from the StringBuilder class or manually iterating to compare characters from the start and the end .

To handle very large numbers beyond the range of integers, you can use the java.math.BigInteger class. Replace the variable 'fact' with a BigInteger and modify the loop to use the multiply method. Example modification: import java.math.BigInteger; BigInteger fact = BigInteger.ONE; for(int i = 1; i <= n; i++) { fact = fact.multiply(BigInteger.valueOf(i)); } Now, it will correctly compute factorials for larger values of 'n' that are beyond the range of an int .

Using an applet for displaying "Hello World!" faces browser compatibility issues since modern browsers have largely discontinued Java applet support due to security risks. Applets require a Java plugin, which is typically unstable and disabled by default; whereas, standalone Java applications execute in a controlled environment independent of browser limitations, making them more versatile and secure compared to applets .

The star pattern printing program can be improved by separating the logic that handles the pattern generation from the printing logic. Furthermore, use of a StringBuilder instead of repeated calls to System.out.print can enhance efficiency, especially for large patterns, by reducing the overhead incurred from multiple I/O operations. This approach also improves clarity and maintainability, as it segregates concerns within the program .

You might also like