0% found this document useful (0 votes)
3 views18 pages

Java Lab Manual

The document is a Java Lab Manual containing various Java programs that demonstrate fundamental programming concepts such as data types, variable types, string operations, and control structures. It includes examples of object-oriented programming, exception handling, method overloading, and multithreading, along with their respective outputs. Each program is designed to illustrate specific programming techniques and best practices in Java.

Uploaded by

mithunnraaj124
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)
3 views18 pages

Java Lab Manual

The document is a Java Lab Manual containing various Java programs that demonstrate fundamental programming concepts such as data types, variable types, string operations, and control structures. It includes examples of object-oriented programming, exception handling, method overloading, and multithreading, along with their respective outputs. Each program is designed to illustrate specific programming techniques and best practices in Java.

Uploaded by

mithunnraaj124
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

Approved by AICTE, New Delhi, Recognized by Govt.

of Karnataka
& Affiliated to Bangalore University. Accredited by NAAC with “B+” Grade
No. 27/2, 33rd Cross, 2nd Main Rd, 7th Block, Jayanagar, Bengaluru, Karnataka 56007

JAVA LAB MANUAL


1. Java program to display “Hello World” and display the size of all data types.

public class DataTypeSize


{
public static void main(String[] args)
{
// Displaying "Hello World"
[Link]("Hello World");
// Displaying the size of all primitive data types in bits
[Link]("Size of Primitive Data Types in Bits:");
[Link]("Byte: + Byte. SIZE + " bits");
[Link]("Short: + [Link] + " bits");
[Link]("Integer: + [Link] + " bits");
[Link]("Long+ [Link] +"bits");
[Link]("Float: + [Link] + " bits");
[Link]("Double: " + [Link] + " bits");
[Link]("Character: " + [Link] + " bits");
[Link]("Boolean: Size is JVM dependent (typically 8 bits)");
}
}
Output:
2. Java program to implement the usage of static, local and global variables.

public class varDemo


{
// Instance Variable (belongs to an object)
int a = 10;
// Static Variable (belongs to the class)
static int b = 20;
public void display() {
// Local Variable (declared inside a method)
int c = 30;
[Link]("Instance Variable: " + a);
[Link]("Static Variable: " + b);
[Link]("Local Variable: " + c);
}
public static void main(String[] args)
{
// Creating an object to access instance variables
varDemo obj = new varDemo();
[Link]();

// Accessing static variable directly through class


[Link]("Accessing Static Variable Without Object:" + varDemo.b);
}
}
Output:
3. Java program to implement string operations string length, string concatenate,
substring

import [Link];
public class StringOperations
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);

// Taking input for first string


[Link] ("Enter the first string: ");
String str1 = [Link]();

// Finding length of the string


[Link]("Length of the first string: " + [Link]());

// Taking input for second string


[Link] ("Enter the second string: ");
String str2 = [Link]();

// Concatenating strings
String str3 = [Link](str2);
[Link]("Concatenated String: " + str3);

// Taking input for substring extraction


[Link]("Enter the starting index for substring: ");
int startIndex = [Link]();

[Link] ("Enter the ending index for substring: ");


int endIndex = [Link]();

// Extracting substring
if (startIndex >= 0 && endIndex <= [Link]() && startIndex < endIndex)
{
String subStr =[Link](startIndex, endIndex);
[Link]("Extracted Substring: " + subStr);
}
else {
[Link]("Invalid index values for substring.");
[Link]();
}
}
Output:

4. Java program to find the maximum of three numbers

import [Link];
public class Largest {
public static void main(String[] args) {

// Create Scanner object to read input


Scanner sc = new Scanner([Link]);

// Read three numbers from the user


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

[Link] ("Enter second number: ");


int b = [Link]();

[Link]("Enter third number: ");


int c = [Link]();

// Determine the largest number using if-else-if ladder


if (a >= b && a >= c)
[Link](a + " is the largest number.");
else if (b >= c)
[Link](b + " is the largest number.");
else
[Link](c + " is the largest number.");

// Close the scanner


[Link]();

Output:
5. Java program to check whether the number is odd or even.

import [Link];
public class EvenOdd
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);

/* To read number */
[Link]("Enter Number: ");
int num = [Link]();
if (num % 2 ==0)
[Link]("Number is Even ");
else
[Link]("Number is Odd");
}
}
Output:

6. Java program to implement default and parameterized constructors.

public class ConsDemo


{
/* Declare two instance variables */
int i,j;

/* Constructor with no arguments - No-arg Constructor */


ConsDemo() {
i=10; j=20;
}

/* Constructor with one argument - Parameterized Constructor */


ConsDemo (int a) {
i=a; j=20;
}

/* Constructor with two arguments - Parameterized Constructor*/


ConsDemo (int a, int b) {
i=a; j=b;
}
void display(){
[Link](" i = "+i);
[Link](" j = "+j);
}
public static void main(String args[])
{
ConsDemo a1 = new ConsDemo();
ConsDemo a2 = new ConsDemo (11);
ConsDemo a3 = new ConsDemo (111,222);
[Link]();
[Link]();
[Link]();
}
}
Output:

7. Java program to implement an array of objects.

class Student {
String name;
int age;
// Constructor
Student(String name, int age) {
}
[Link] = name;
[Link] = age;

// Method to display student details


void display() {
[Link]("Name: " + name + ", Age:+ age);
}
}

public class ArrayOfObjects {


public static void main(String[] args) {
// Creating an array to store Student objects
Student[] students = new Student [3];

// Initializing the array elements with Student objects


students[0] = new Student ("Srikanth", 20);
students [1]= new Student ("Priya", 22);
students[2] = new Student ("Rahul", 19);

// Displaying the student details


for (int i = 0; i < [Link]; i++) {
students[i].display();
}
}
}

Output:

8. Java program to implement Single Inheritance

class A {
int i;
void functionX()
{
[Link](" In Super Class: i = " + i);
// [Link](" In Super Class: j = "+j);// Error
}
}
public class Y extends A {
int j;
void functionY() {
}
[Link](" In Sub Class: j = " + j);
[Link](" In Sub Class: i = " + i);
public static void main(String args[]) {
Y y1 = new Y();
y1.j = 20;
y1.i = 30;
y1. functionY();
y1. functionX();
}
}
Output:

9. Java program to implement Multiple Inheritance using Interface

interface XYZ {
public void functionX();
}
interface MSD {
public void functionM();
}
interface PQR extends XYZ, MSD {
public void functionP();
}

class ABC implements PQR {


public void functionX() {
[Link](" void functionX()");
}
public void functionM() {
[Link](" void functionM()");
}
public void functionP() {
[Link](" void functionP ()");
}
}

class InterfaceMulti {
public static void main(String args[]) {
ABC a1 = new ABC();
a1. functionX();
a1. functionM();
a1. functionP();
}
}

Output:

10. Java program to implement an applet

import [Link];
import [Link];
/* <APPLET CODE="[Link]" WIDTH=300 HEIGHT=200> </APPLET> */
public class AppletLifeCycle extends Applet
{
public void init() {
[Link]("Applet Initialized");
}
public void start() {
[Link]("Applet Started");
}
public void stop() {
[Link]("Applet Stopped");
}
public void destroy() {
[Link]("Applet Destroyed");
}
public void paint (Graphics g) {
[Link]("Applet Life Cycle Demo", 20, 20);
}
}
Output:
11. Java program to demonstrate a division by zero exception

import [Link];
class DivisionbyZeroDemo
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the value of a:");
int a = [Link]();
[Link]("Enter the value of b:");
int b = [Link]();
try{
int result=a/b;
[Link]("Result:"+result);
}catch(ArithmeticException e){
[Link]("Error: Division by zero is not allowed.");
}
[Link]();
}
}
Output:

12. Java program to add two integers and two float numbers. When no arguments are
supplied give a default value to calculate the sum. Use method overloading.
class Addition
{
int add(int a, int b)
{
return a+b;

float add(float a, float b)


{
return a+b;
}
int add()
{
int a = 5;
int b = 10;
return a+b;
}
public static void main(String[]args)
{
Addition a = new Addition();
[Link]("Sum of 10 and 20:"+[Link](10, 20));
[Link]("Sum of 5.5 and 2.3:"+[Link](5.5f, 2,3f));
[Link]("Sum using default values:"+[Link]());
}
}
Output:

13. Java program that demonstrates run-time polymorphism.


import [Link];
class Animal
{
void makesound()
{
[Link]("Animal makes a sound);
}
}
class Dog extends Animal
{
@Override
void makesound()
{
[Link]("Dog Barks");
}
}
class Cat extends Animal
{
@Override
void makesound()
{
[Link]("Cat meows");
}
}
class RuntimePoly
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
[Link]("Choose an Animal");
[Link]("1. Dog");
[Link]("2. Cat");
[Link]("Enter your choice(1 or 2)");
int choice = [Link]();
Animal myAnimal;
if(choice == 1)
{
myAnimal = new Dog();
}else if(choice==2){
myAnimal = new Cat();
}else{
[Link]("Invalid choice defaulting to Animal");
myAnimal = new Animal();
}
[Link]();
[Link]();
}
}
Output:
14. Java program to catch negative array size Exception. This exception is caused when
the array is initialized to negative values.

import [Link];
class NegativeArraySizeDemo
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the size of the array");
int size = [Link]();
try{
int[]arr = new int[size];
[Link]("Array of size"+size+"created successfully");
}catch(NegativeArraySizeException e)
{
[Link]("Error: Array size cannot be negative");
}
[Link]();
}
}
Output:

15. Java program to handle null pointer exception and use the “finally” method to
display a message to the user.
import [Link];
class NullPointerExceptionDemo
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a String(or press Enter to leave it empty):");
String str = [Link]();
if([Link]())
{
str=null;
}
try{
[Link]("Length of the string:"+[Link]());
}catch(NullPointerException e){
[Link]("Error: Entered String is empty or null");
}
finally{
[Link]("Execution completed. Thank you");
}
[Link]();
}
}
Output:

16. Java program to import user-defined packages


package pack1;
public class PackageExample
{
public void packMethod()
{
[Link]("I am packageExample from pack 1");
}
}
import pack1.*;
class PackageDemo
{
public static void main(String[]args)
{
PackageExample p = new PackageExample();
[Link]();
}
}
Output:
17. Java program to check whether a number is palindrome or not
import [Link];
public class PalindromeCheck
{
public static void main (String[]args)
{
Scanner sc = new Scanner([Link]);
[Link](“Enter a number”);
int num = [Link]();
int originalNum = num, reverse = 0, remainder;
while(num>0)
{
remainder = num%10;
reverse = reverse*10+remainder;
num/=10
}
if(originalNum==reverse)
[Link](originalNum+”is a palindrome.”);
else
[Link](originalNum+”is not a palindrome.”);
[Link]();
}
}
Output:

18. Java program to find the factorial of a list of numbers reading input as command
line argument.

class FactorialCommandLine
{
public static long factorial(int num)
{
if(num<0)
{
throw new IllegalArgumentException("Factorial is not defined for negative numbers:");
}
long result = 1;
for(int i = 1; i<=num;i++)
{
result*=i;
}
return result;
}
public static void main(String[]args)
{
if([Link] == 0){
[Link]("Please provide numbers as command-line argumnets");
return;
}
//Loop through all provided argumnets
for(String arg:args)
{
try
{
int number = [Link](arg);
long fact = factorial(number);
[Link]("Factorial of"+number+"is:"+fact);
}catch(NumberFormatException e)
{
[Link]("Invalid input:"+arg+"Please enter a valid integer");
}catch(IllegalArgumentException e)
{
[Link]([Link]());
}
}
}
}
Output:
19. Java program to display all prime numbers between two limits.
import [Link];
public class PrimeNumbersBetweenLimits
{
public static void main(String[]args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the lower Limit:");
int lower = [Link]();
[Link]("Enter the upper limit:");
int upper = [Link]();
[Link]("Prime Numbers between"+lower+"and"+upper+":");
for(int num=lower;num<=upper;num++)
{
if(isPrime(num))
{
[Link](num+" ");
}
}
[Link]();
}
public static boolean isPrime(int n)
{
if(n<2) return false;
for(int i=2; i<=[Link](n);i++)
{
if(n%i==0)
return false;
}
return true;
}
}
Output:
20. Java program to create a thread using Runnable Interface.
class MyThread implements Runnable
{
public void run()
{
[Link]("run() started");
for(int i=1; i<=10; i++)
{
[Link]("The value is: "+i);
}
[Link]("run() completed");
}
}

public class ThreadRunnable


{
public static void main(String[]args)
{
[Link]("Main Thread started");
MyThread obj = new MyThread();
Thread t1 = new Thread(obj, "Thread One");
[Link]();
[Link]("Main Thread Completed");
}
}
Output:

You might also like