Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
74 views

jAVA LAB Programs

The document contains Java programs demonstrating various programming concepts like Hello World, data types, control structures, methods, classes, arrays, applets and event handling. The programs cover basic to advanced Java topics ranging from simple print statements, calculations to object oriented concepts like classes, methods and event handling.

Uploaded by

ashish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

jAVA LAB Programs

The document contains Java programs demonstrating various programming concepts like Hello World, data types, control structures, methods, classes, arrays, applets and event handling. The programs cover basic to advanced Java topics ranging from simple print statements, calculations to object oriented concepts like classes, methods and event handling.

Uploaded by

ashish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

1.

Java program to print hello world


class HelloWorld
{
    // Your program begins with a call to main().
    // Prints "Hello, World" to the terminal window.
    public static void main(String args[])
    {
        System.out.println("Hello, World");
    }
}

2. Java program to add two numbers

3. Java program to find whether the person is eligible for voting or not.
4. Java program to find grade of the student using if else if
5. Java program to perform calculator program using switch
6. Java program to print number from 1 t 5 using for loop
7. To print pyramid using for loop
8. Java program using scanner class to accept name from the user and display it
9. Factorial of a number using scanner class

10.Java program for swapping of two numbers using scanner class

import java.util.*;  
class Swap_With {  
    public static void main(String[] args) {  
       int x, y, t;// x and y are to swap   
       Scanner sc = new Scanner(System.in);  
       System.out.println("Enter the value of X and Y");  
       x = sc.nextInt();  
       y = sc.nextInt();  
       System.out.println("before swapping numbers: "+x +"  "+ y);  
       /*swapping */  
       t = x;  
       x = y;  
       y = t;  
       System.out.println("After swapping: "+x +"   " + y);  
       System.out.println( );  
    }    
}  

11. Java program for checking whether the number is greater than 2 by passing argument.
12. Java program to analyses the use of static in main function
13. Java program with the application of two classes.

14. Write a program to add ‘n’ numbers using command line argument.
class Addition
{
public static void main(String args[])
{
int sum=0;
for(int i=0;i<args.length;i++)
{
sum+=Integer.parseInt(args[i]);
}
System.out.println("Total:" +sum);
}
}

15. Java array program to print the values.


public class TestArray {

public static void main(String[] args) {

double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements

for (int i = 0; i < myList.length; i++) {

System.out.println(myList[i] + " ");

// Summing all elements

double total = 0;

for (int i = 0; i < myList.length; i++) {

total += myList[i];

System.out.println("Total is " + total);

}
}

16. Java program to take string values and display

public class JavaStringArrayExample {


 public static void main(String args[]) {
 // declare a string array with initial size
 String[] schoolbag = new String[4];
 // add elements to the array
 schoolbag[0] = "Books";
 schoolbag[1] = "Pens";
 schoolbag[2] = "Pencils";
 schoolbag[3] = "Notebooks";
 // this will cause
ArrayIndexOutOfBoundsException
 // schoolbag[4] = "Notebooks";
 }
}
17.Write a java program to pass array value as argument to function

class arrayargument{  
//creating a method which receives an array as a parameter  
static void display(int arr[]){  
for(int i=1;i<arr.length;i++)  
System.out.println(arr[i]);  
}  
public static void main(String args[]){  
int a[]={33,3,4,5};//declaring and initializing an array  
display(a);//passing array to method  
}}  

18.Write a java 2D array program to accept the values of rows and columns
from the user and display it.
TwoDimensionalScanner
{
   public static void main(String args[])
   {    
Scanner sc=new Scanner(System.in);
System.out.println("Enter Row length of an array : ");
int row=sc.nextInt();
System.out.println("Enter column length of an array : ");
int column=sc.nextInt();
int a[][]=new int[row][column];//declaration    
System.out.print("Enter " + row*column + " Elements to Store in Array :\n");
for (int i = 0; i < row; i++)
{
    for(int j = 0; j < column; j++)
    {
           a[i][j] = sc.nextInt();
    }
}  
        System.out.print("Elements in Array are :\n");
        for (int i = 0; i < row; i++)
{
    for(int j = 0; j < column; j++)
    {
       System.out.println("Row ["+i+"]:  Column ["+j+"] :"+a[i][j]);
    }
}  
   }
}
19. WAP to sort an array of integers accept the values of array
from user.

20.Write a java program for Jagged array

21.Write a simple program to call a method called simple from a main


function. The method simple should accept an integer as an argument
and calculate the square of the number in the method simple.

22.Asimple java program using class and methods for finding area of rectangle.
23. Write a separate Java program to explain the use of public, private
,protected and default access specifier Also display the output for errors.
24. Write functions get and print to read data of objects and to print
objects data.(Static Function)

class Student
{
int roll_num;
void getData(int n)
{
roll_num=n;
}

void printData()
{
System.out.println("Roll Number is"+roll_num);
}
}

class PrintData
{
public static void main(String args[])
{

Student s=new Student ();


s.getData(10);
s.printData();

}
}
Output:
Roll Number is 10

25. Write a java array list to add string values to the array and remove a[3]
value from the array. Also display total size of string array and clear all the
list of values from array and again display total size of array

Use the reference of the program given below


26. Write a java applet program to display WELCOME
//First.java  
import java.applet.Applet;  
import java.awt.Graphics;  
public class First extends Applet{  
  
public void paint(Graphics g){  
g.drawString("welcome",150,150);  
}  

}  

//save as first.html
<html>  
<body>  
<applet code="First.class" width="300" height="300">  
</applet>  
</body>  
</html>  
Save as First.html

Execute as

27 . Create an applet program to draw various shapes using the following methods of paint class of awt
package.

• public abstract void drawString(String str, int x, int y): is used to draw the specified string.

• public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.

• public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
default color and specified width and height.

• public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.

• public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default
color and specified width and height.

• public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
• public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used
draw the specified image.

• public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used draw a circular or elliptical arc.

• public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used
to fill a circular or elliptical arc.

• public abstract void setColor(Color c): is used to set the graphics current color to the specified
color.

• public abstract void setFont(Font font): is used to set the graphics current font to the specified
font.
28. Write an applet program which shows the life cycle of applet.

29. Applet program to set background color


//exampleapplet.java

import java.applet.*;

import java.awt.*;

public class exampleapplet extends Applet{

public void paint(Graphics g)

setBackground(Color.YELLOW);

g.setColor(Color.RED);

g.drawString("welcome",100,100);

Output:
30)Write an applet event handling program to generate button click event

//myapplet.html

<html>  

<body>  

<applet code="EventApplet.class" width="300" height="300">  

</applet>  

</body>  

</html>

Output:   
Applet2.java

31. //Evening handling in an applet

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="Applet2" width=250 height=200>

*lt;/applet>

*/

public class Applet2 extends Applet implements ActionListener, ItemListener

Label label1, label2, label3;

TextField tf1, tf2, tf3;


Checkbox ck1, ck2;

CheckboxGroup cb;

public void init()

System.out.println("Initializing an applet");

label1 = new Label("Enter your name");

tf1= new TextField(10);

label2 = new Label("Enter your city");

tf2= new TextField(10);

label3 = new Label("Gender");

cb= new CheckboxGroup();

ck1 = new Checkbox("Male",cb,false);

ck2 = new Checkbox("Female",cb,false);

add(label1); //adding first label to the applet window.

add(tf1); //adding first textfield to the applet window.

add(label2); //adding second label to the applet window.

add(tf2); //adding second textfield to the applet window.

add(label3); //adding third label to the applet window.

add(ck1); //adding the first checkbox to the applet window

add(ck2); //adding the second checkbox to applet window

tf1.addActionListener(this); //Applet2 class registering to listen to textfield events

tf2.addActionListener(this); //Applet2 class registering to listen to textfield events

ck1.addItemListener(this); //Applet2 class registering to listen to checkbox events

ck2.addItemListener(this); //Applet2 class registering to listen to checkbox events

public void actionPerformed(ActionEvent ae) //listening to textfields events when enter is pressed in a
textField

repaint(); //repaint() calls paint() method when a button click event is generated.

public void itemStateChanged(ItemEvent ie) //Listening to checkboxes when a checkbox is selected


{

repaint(); //repaint() calls paint() method when a checkbox is checked or unchecked.

public void paint(Graphics g)

g.drawString("Your name is "+ tf1.getText(), 10, 150 );

g.drawString("Your city is "+ tf2.getText(), 10,170 );

if(cb.getSelectedCheckbox()!=null)

g.drawString("Your gender is "+ cb.getSelectedCheckbox().getLabel(), 10,190);

}
32. Java program to create Package

//save as Simple1.java  
1. package mypack;  
2. public class Simple1{  
3.  public static void main(String args[]){  
4.     System.out.println("Welcome to package");  
5.    }  
6. }  

Execute:

C:\>javac -d . Simple1.java

C:\>java mypack.Simple1
33. Write a program to import packages.

// Filename : Balance.java
package core;
public class Balance
{
public String name;
public double bal;
public Balance(String n, double b)
{
name = n;
bal = b;
}
public void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
//Filename: AccountBalance.java

import core.Balance;
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++)
current[i].show();
}
}

Execution:
34. Create character array. Check and print whether it is digit, letter,uppercase or
white space.

char a[]={'a','I','5',' '};


for(int i=0;i<a.length;i++)
{ if(Character.isDigit(a[i]))
{ System.out.println(a[i]+"is Digit");
}
if(Character.isLetter(a[i]))
{ System.out.println(a[i]+"is Letter");
}
if(Character.isUpperCase(a[i]))
{ System.out.println(a[i]+"is Upper Case");
}
if(Character.isLowerCase(a[i]))
{ System.out.println(a[i]+"is Lower Case");
}
if(Character.isWhitespace(a[i]))
{ System.out.println(a[i]+"is Whitespace");
}
35. Write a program to demonstrate use of the Static keyword.

36. Write a program using Static member functions to display the details of
students such as name, age ,mobile,course where course is static data
member. Refer this program
import java.io.*; class GFG {

class abc{     public static void main (String[] args) {

    public static String Name = "";           

               // Accessing the static method assign1() and 

    public static void assign1(String         // field by class name itself.


name)
      abc.assign1("vaibhav"); 
{
        System.out.println(abc. Name);
        Name = name;
         
    }
        // Accessing the static method assign1() by using
} Object's reference.

        abc obj = new abc();

        obj.asign1("mohit");

        System.out.println(obj. Name);   

    }

37. Write a java program to perform complex number addition,


multiplication, subtraction using constructor overloading.

import java.io.*;
class Complex
{
int Real,Imag;
Complex()
{}
Complex(int Real1,int Imag1)
{
Real=Real1;
Imag=Imag1;
}
Complex AddComplex(Complex C1,Complex C2)
{
Complex CSum=new Complex();
CSum.Real=C1.Real+C2.Real;
CSum.Imag=C1.Imag+C2.Imag;
return CSum;
}
Complex SubtractComplex(Complex C1,Complex C2)
{
Complex CSum=new Complex();
CSum.Real=C1.Real-C2.Real;
CSum.Imag=C1.Imag-C2.Imag;
return CSum;
}
Complex MultiplyComplex(Complex C1,Complex C2)
{
Complex CSum=new Complex();
CSum.Real=C1.Real*C2.Real;
CSum.Imag=C1.Imag*C2.Imag;
return CSum;
}

class Complexmain
{
public static void main(String[] a)
{
Complex C1=new Complex(4,8);
Complex C2=new Complex(5,7);
Complex C3=new Complex();
Complex C4=new Complex();
Complex C5=new Complex();
C3=C3.AddComplex(C1,C2);
C4=C4.SubtractComplex(C1,C2);
C5=C5.MultiplyComplex(C1,C2);
System.out.println("SUM:" + C3.Real +"+i" + C3.Imag);
System.out.println("subtraction:" + C3.Real +"-i" + C3.Imag);
System.out.println("subtraction:" + C3.Real +"*i" + C3.Imag);
}
}

38. Count the number of objects created for a class using


static member function.

public class numberobjects


{
static int count=0;
numberobjects()
{
count++;
}
public static void main(String[]args)
{
numberobjects obj1=new numberobjects();
numberobjects obj2=new numberobjects();
numberobjects obj3=new numberobjects();
numberobjects obj4=new numberobjects();
System.out.println("Number of objetcs created:" +count);
}
}

39. Write a program to display the values of the variables using no


argument constructor.

class Demo{
int value1;
int value2;
Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
d1.display();
}
}

39. Write a program to pass the values of rollno, name and age
using parameterized constructor and display it.

public class exconstructor {


String studentName;
int studentAge;

//constructor
exconstructor(String name, int age){
studentName = name;
studentAge = age;
}
void display(){
System.out.println(studentName+ " "+studentAge);
}
public static void main(String args[])
{
exconstructor myObj = new exconstructor("Manan" , 19);
myObj.display();
}
}

39. Suppose that a class, Employee, is defined as follows:


class Employee { String lastName; String firstName; double hourlyWage; int
yearsWithCompany; }
accept the value of 10 employees
Employee[] employeeData = new Employee[10];
Write a code segment that will output the first name, last name, and hourly wage of each
employee who is been with the company for more than 20 years.
class Employee public class print

{ {

String lastName; public static void main(String[] args) {

String firstName; Employee[] emparray=new Employee[10];

double hourlyWage; emparray[0]=new Employee();


int yearsWithCompany; emparray[0].accept("aaa","ddd",45,9);

void accept(String a,String b,double h,int emparray[1]=new Employee();


q)
emparray[1].accept("pqr","abc",48,10);
{
}
lastName=a;
}
firstName =b;

hourlyWage=h;

yearsWithCompany=q;

System.out.println(lastName);

System.out.println(firstName);

System.out.println(hourlyWage);

System.out.println(yearsWithCompany);

}
40. WAP to demonstrate the banking operations such as debit and
credit with the help of packages.

PACKAGE
package Bank;
import java.io.*;

public class PackBank


{
int ch;
int amt;
int balance=1000;
public PackBank(int choice,int amount)
{
ch=choice;
amt=amount;
}
public void calc()
{
switch(ch)
{
case 1:
if(amt < balance)
{
balance = balance - amt;
System.out.println("Your balance after debit transaction is " + balance);
}
else
System.out.println("Your account only has " +balance+ "as balance amount");
break;
case 2: balance = balance + amt;
System.out.println("Your balance after credit transaction is " + balance);
break;
default:
System.out.println("No such transaction available");
}
}
}

Program
import Bank.PackBank;
import java.io.*;

public class MainTrans


{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Bank Transaction");
System.out.println("Enter");
System.out.println("1:Debit");
System.out.println("2:Credit");
int ch = Integer.parseInt(br.readLine());
System.out.println("Enter amount");
int amt = Integer.parseInt(br.readLine());
PackBank pb = new PackBank(ch,amt);
pb.calc();
}
}

Output:
Bank Transaction
Enter
1:Debit
2:Credit
2
Enter amount
1000
Your balance after credit transaction is 2000
41. Write a program to perform mathematical operations. Create a class
called AddSub with methods to add and subtract. Create another class
called MultDiv that extends from AddSub class to use the member data
of the superclass. MultDiv should have methods to multiply and divide.
A main method should access the methods and perform the
mathematical operations using Inheritance.

42. Create class A which accept 3 numbers from the user .Create
another class B which performs sum of the accepted numbers and
display it using single inheritance.

43. Create 2 classes A and B which has same method display. Display
the method of base class using method overriding.

44. Write a program for multilevel inheritance.


45. Write a program for hierarchical inheritance.
46. Create an interface Drawable with draw method. Create two classes
circle and rectangle which calculates area of circle and area of
rectangle rept. And display the result Using interface write a program
(multiple inheritance .)

You might also like