Programming in JAVA
NOTE: 1) These 26 programs are the reference. You have to create Java Program yourself.
2) You must explain your code during submission. And your code must be in proper format.
ASSIGNMENT-1
1. WAP that implements the Concept of Encapsulation.
Encapsulation: wrapping up of data into a single unit.
CODE:
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String n) {
name = n;
}
public int getAge() {
return age;
}
public void setAge(int a) {
age = a;
}
}
public class Main {
public static void main(String[] args)
{
Person person = new Person();
person.setName("John");
person.setAge(30);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
OUTPUT:
Name: John
Age: 30
1
MS
Programming in JAVA
ASSIGNMENT-2
2(a).WAP to demonstrate concept of Polymorphism function Overloading .
Polymorphiam: - ability to take more than one form.
CODE:
class Fun
{
void add(int i, int j)
{
int s=i+j;
System.out.println(“sum=”+s);
}
void add(inti,int j, int k)
{
int s=i+j+k;
System.out.println(“sum=”+s);
}
}
class overloading
{
public static void main(String rags[])
{
Fun obj =new Fun();
obj.add(10,20);
obj.add(20,30,40);
}
}
OUTPUT:
sum=30
sum=90
2
MS
Programming in JAVA
2(b). WAP to demonstrate concept of Polymorphism constructor Overloading.
CODE:
class cons
{
cons() //default constructor
{
System.out.println("default constructor");
}
cons(String s) //parameterized constructur
{
System.out.println(s);
}
}
class consover
{
public static void main(String rags[])
{
cons o=new cons();
consol =new cons("parameterized constructor");
}
}
OUTPUT:
3
MS
Programming in JAVA
ASSIGNMENT-3
3)WAP to check the entered number is prime or not.
CODE:
public class Main {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {
// condition for nonprime number
if (num % i == 0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
OUTPUT:
29 is a prime number.
4
MS
Programming in JAVA
ASSIGNMENT-4
4. WAP to print first 10 number of the following Series using Do---While Loops 0, 1, 1, 2,
3, 5, 8, 11......(Fibonacci series)
CODE:
class dowhile
{
int a =-1,b=1,c;
void series()
{
int i =1;
do
{
c =a+b;
System.out.println(c);
a =b;
b =c;
i++;
}while(i<=10);
}
}
class loop
{
public static void main(String rags[])
{
dowhile d =new dowhile();
d.series();
}
}
OUTPUT:
5
MS
Programming in JAVA
ASSIGNMENT-5
5. WAP to take input of two number and perform arithmetic operation.
CODE:
OUTPUT:
Assignment-6
6. WAP in java to check entered number is factorial or not
CODE:
OUTPUT:
ASSIGNMENT-7
7. WAP to illustrate the Vector class.
Vector: dynamic array that can hold object of any type & any number.
CODE:
import java.util.*;
class LVector
{
public static void main(String rags[])
{
String s1=new String("Rahul");
String s2=new String("Sohan");
String s3=new String("Deepesh");
Vector<String> list = new Vector<String>();
list.addElement(s1);
list.addElement(s2);
list.addElement(s3);
//get the each object from vector class
for(String s: list)
{
System.out.println(s);
}
//remove all elements from list
list.removeAllElements();
}
}
OUTPUT:
Rahul
Sohan
Deepesh
6
MS
Programming in JAVA
ASSIGNMENT-8
8. WAP for String class which perform the all methods of that class.
CODE:
public class StringMethodsDemo {
public static void main(String[] args) {
String str = "Java is fun to learn";
String s1= "JAVA";
String s2= "Java";
String s3 = " Hello Java ";
System.out.println("Char at index 2(third position): " + str.charAt(2));
System.out.println("After Concat: "+ str.concat("-Enjoy-"));
System.out.println("Checking equals ignoring case: " +s2.equalsIgnoreCase(s1));
System.out.println("Checking equals with case: " +s2.equals(s1));
System.out.println("Checking Length: "+ str.length());
System.out.println("Replace function: "+ str.replace("fun", "easy"));
System.out.println("SubString of targetString: "+ str.substring(8));
System.out.println("SubString of targetString: "+ str.substring(8, 12));
System.out.println("Converting to lower case: "+ str.toLowerCase());
System.out.println("Converting to upper case: "+ str.toUpperCase());
System.out.println("Triming string: " + s3.trim());
System.out.println("searching s1 in targetString: " + str.contains(s1));
System.out.println("searching s2 in targetString: " + str.contains(s2));
char [] charArray = s2.toCharArray();
System.out.println("Size of char array: " + charArray.length);
System.out.println("Printing last element of array: " + charArray[3]);
}
}
OUTPUT:
7
MS
Programming in JAVA
ASSIGNMENT-9
9. WAP to check that the given String is palindrome or not.
CODE:
class Student
{
public static void main(String rags[])
{
String s=new String("av");
String s1=new String();
char a;
int l=s.length();
for(int i=l-1;i>=0;i--)
s1=s1+s.charAt(i);
System.out.println(s1);
int m=s.compareTo(s1);
if(m==0)
System.out.println("String is palindrome");
else
System.out.println("String is not palindrome");
}
}
OUTPUT:
8
MS
Programming in JAVA
ASSIGNMENT-10
10. WAP for StringBuffer class which perform the all methods of that class.
StringBuffer:- peer class of String, that creates String of flexible length that can be modified length and content.
CODE:
class string
{
public static void main(String rags[])
{
StringBuffer str=new StringBuffer("Object Language");
System.out.println("Original String: "+str);
System.out.println("Length of String: "+str.length());
for(int i=0;i<str.length();i++)
{
int p=i+1;
System.out.println("Character Position "+p+" is "+str.charAt(i));
}
String aString=new String(str.toString());
int pos =aString.indexOf("Language");
str.insert(pos,"oriented");
System.out.println("modify String: "+str);
str.setCharAt(6,'-');
System.out.println("String now: "+str);
str.append(" improves"); // setLength();
System.out.println("Appended String: "+str);
}
}
OUTPUT:
9
MS
Programming in JAVA
ASSIGNMENT-11
11. WAP to calculate Simple Interest using the Wrapper Class.
WrapperClass: used for converting primitive datatypes into object.
CODE:
import java.io.*;
class wrapper
{
public static void main(String rags[]) throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
//use the wraper class to convert the String value into integer
System.out.println("Enter the value of P: ");
int P = Integer.parseInt(br.readLine());
System.out.println("Enter the value of R: ");
int R=Integer.parseInt(br.readLine());
System.out.println("Enter the value of T: ");
int T=Integer.parseInt(br.readLine());
float simint = (float)(P*R*T)/100;
System.out.println("Simple Interest: "+simint);
}
}
OUTPUT:
10
MS
Programming in JAVA
ASSIGNMENT-12
12. WAP to calculate Area of various geometrical figures using the abstract class.
Abstract class: when a class contains one or more abstract methods, it should be declared abstract.
CODE:
abstract class Shape
{
static final float pi=3.14f;
abstract float area(float x);
}
class Circle extends Shape
{
public float area(float x)
{
float A=pi*x*x;
return A;
}
}
class av
{
public static void main(String rags[])
{
Circle obj=new Circle();
float z=obj.area(5f);
System.out.println("area of Circle"+z);
}
}
OUTPUT:
11
MS
Programming in JAVA
ASSIGNMENT-13
13. WAP where Single class implements more than one interfaces and with help of interface reference variable
user call the methods.
Interface: a kind or class that define only abstract method and final fields.
CODE:
interface Area
{
final static float pi=3.14F;
float compute(float x,float y);
}
interface RectArea
{
int calculate(int i,int w);
}
class Test implements Area,RectArea
{
public float compute(float x,float y)
{
return(pi*x*y);
}
publicint calculate(inti,int w)
{
return(i*w);
}
}
classinterfaceTest
{
public static void main(String rags[])
{
Area o;
RectArea t;
Test e =new Test();
o=e;
System.out.println("Area of circle"+o.compute(20,30));
t=e;
System.out.println("Area of Rectangale"+t.calculate(10,30));
}
}
OUTPUT:
12
MS
Programming in JAVA
ASSIGNMENT-14
14. WAP that use the multiple catch statements within the try-catch mechanism.
Try: Exception object creator.
Catch: Exception object handler.
CODE:
class Exception
{
public static void main(String rags[])
{
int a=10,b=0,c=20;
try
{
int z=a/b;
}
catch(ArithmeticException e) //diivde by zero exception
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e) //when argument any not found(a or b)
{
System.out.println("e");
}
catch(NumberFormatException e) //when string could no convert in integer
{
System.out.println("e");
}
int y=(a/c);
System.out.println("value of y: "+y);
}
}
OUTPUT:
13
MS
Programming in JAVA
ASSIGNMENT-15
15. WAP where user will create a self-Exception using the “throw” keyword.
Throw: to manually throw an exception, we use a keyword throw.
CODE:
importjava.lang.Exception;
class SelfException extends Exception
{
SelfException(String message)
{
super(message);
}
}
class TestSelfException
{
public static void main(String rags[])
{
int x=8,y=8000;
try
{
float z=(float)x / (float)y;
if(z<0.01)
throw new SelfException("Number is Small");
}
catch(SelfException e)
{
System.out.println("Caught My Exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am Always Here");
}
}
}
OUTPUT:
14
MS
Programming in JAVA
ASSIGNMENT-16
16. WAP for multithread using the isAlive(), join() and synchronized() methods of Thread class.
Thread: that has single flow of control, independent path of execution.
Multithreading: program is divided in subprogram ,a single program perform two or more task at the same time.
Which runs in parallel.
CODE:
class Abc extends Thread
{
Abc(String str)
{
setName(str);
}
public void run()
{
for(int i=1; i<=5;i++)
{
System.out.println(getName()+"."+i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}
}
class TestAlive
{
public static void main(String rags[])throws Exception
{
Abc t1 = new Abc("One");
t1.start();
Abc t2 = new Abc("two");
t2.start();
System.out.println(t1.isAlive()+","+t2.isAlive());
Thread.sleep(10000);
System.out.println(t1.isAlive()+","+t2.isAlive());
}
}
OUTPUT:
15
MS
Programming in JAVA
ASSIGNMENT-17
17. WAP to create a package using command and one package will import another package.
Package: Collection of classes, interfaces, and their methods. It is similar to folder.
CODE:
package meghraj;
public class Value
{
public void show()
{
int a= 10;
System.out.println("Value of A:"+a);
}
}
package xyz1;
public class Value1
{
public void show1()
{
int b = 20;
System.out.println("value of b"+b);
}
public void sum()
{
int c = 24, h=30;
int sum = c+h;
System.out.println("Sum" +sum);
}
}
import meghraj.Value;
import xyz1.Value1;
class Display
{
public static void main(String rags[])
{
Value ob = new Value();
Value1 ob1 = new Value1 ();
ob.show();
ob1.show1();
ob1.sum();
}
}OUTPUT:
16
MS
Programming in JAVA
ASSIGNMENT-18
18. WAP for Applet that handle the KeyBoard Events.
Applet: small programs that runs on internet as a part of web.
CODE:
Import java.awt.*;
Import java.applet.*;
Import java.awt.event.*;
public class keys extends Applet implements KeyListener
{
String s;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
showStatus("Key pressed");
repaint();
}
public void keyReleased(KeyEvent e)
{
s="key released";
repaint();
}
public void keyTyped(KeyEvent e)
{
s="key typed";
repaint();
}
public void paint(Graphics g)
{
g.drawString(s,30,40);
}
}
OUTPUT:
17
MS
Programming in JAVA
ASSIGNMENT-19
19. WAP, which support the TCP/IP protocol, where client gives the message and server will receive the message.
CODE:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.DataInputStream;
public class WishesServer
{
public static void main(String rags[]) throws Exception
{
ServerSocket sersock = new ServerSocket(5000);
System.out.println("server is ready"); // message to know the server is running
Socket sock = sersock.accept();
InputStream istream = sock.getInputStream();
DataInputStream dstream = new DataInputStream(istream);
String message2 = dstream.readLine();
System.out.println(message2);
dstream .close();
istream.close();
sock.close();
sersock.close();
}
}
//Client
import java.net.Socket;
import java.io.OutputStream;
import java.io.DataOutputStream;
public class WishesClient
{
public static void main(String rags[]) throws Exception
{
Socket sock = new Socket("127.0.0.1", 5000);
String message1 = "Accept Best Wishes, Server Avdhesh!";
OutputStreamostream = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(ostream);
dos.writeBytes(message1);
dos.close();
ostream.close();
sock.close();
}
}
OUTPUT:
18
MS
Programming in JAVA
ASSIGNMENT-20
20. WAP to illustrate the use of all methods of URL class.
CODE:
import java.io.*;
import java.net.*;
public class URLDemo
{
public static void main(String[] rags)
{
try
{
URL url=new URL("http://localhost/mycollege/library/library.php");
System.out.println("Protocol:"+url.getProtocol());
System.out.println("Host Name:"+url.getHost());
System.out.println("Port Number:"+url.getPort());
System.out.println("File Name:"+url.getFile());
}
catch(IOException e)
{
System.out.println(e);
}
}
}
OUTPUT:
19
MS
Programming in JAVA
ASSIGNMENT-21
21. WAP for JDBC to display the records from the existing table.
CODE:
Import java.sql.*;
Class jdbc1
{
public static void main(String rags[])
{
int r;
String n;
try
{
Class.forName("Sun.jdbc.odbc.jdbcOdbcDriver");
Connection c=DriverManager.getConnection("jdbc:odbc:stu");
Statement s=c.createStatement();
ResultSet p=s.executeQuery("select*from stu");
while(p.next())
{
r=p.getInt(1);
n=p.getString(2);
System.out.println("Roll No:="+r);
System.out.println("Name:="+n);
}
s.close();
c.close();
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
catch(SQLException e)
{
System.out.println(e);
}
}
}
OUTPUT:
20
MS
Programming in JAVA
ASSIGNMENT-22
22. WAP to demonstrate the Border Layout using applet.
CODE:
Import java.applet.*;
Import java.awt.*;
public class BorderLine extends Applet
{
public void init()
{
this.setLayout(new BorderLayout(50, 50));
this.add(new Button("Center"), BorderLayout.CENTER);
//note: you have to add more element here
}
}
OUTPUT:
21
MS
Programming in JAVA
ASSIGNMENT-23
23. WAP for display the checkboxes, Labels and TextFields on an AWT.
CODE:
Import java.awt.*;
Import java.applet.*;
public static com extends Applet
{
TextField t1,t2;
Lable l1,l2;
Checkbox c1;
public void init()
{
checkbox=new Checkbox("Gender");
t1 =new TextField();
t2 =new TextField();
l1 =new Lable("Value Of Text:");
l2 =new Lable("Value Of Text:");
add(c1);
add(t1);
add(t2);
add(l1)
add(l2);
}
}
OUTPUT:
22
MS
Programming in JAVA
ASSIGNMENT-24
24. WAP for creating a file and to store data into that file.(Using the FileWriterIOStream).
CODE:
import java.io.*;
class Bytewrite
{
public static void main(String rags[])
{
byte b[]={'M','E','G','H','R','A','J'};
try
{
FileOutputStream s =new FileOutputStream("c.txt");
s.write(b);
s.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
OUTPUT:
23
MS
Programming in JAVA
ASSIGNMENT-25
25. WAP to display your file in DOS console use the Input/Output Stream.
CODE:
import java.io.*;
class ByteRead
{
public static void main(String rags[])
{
int b;
try
{
FileInputStream s =new FileInputStream("c.txt");
while((b=s.read())!=-1)
{
System.out.println((char)b);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
OUTPUT:
24
MS
Programming in JAVA
ASSIGNMENT-26
26. WAP to create an Applet using the HTML file, where Parameter Pass for Applet Class.
CODE:
import java.awt.*;
import java.applet.*;
public class MeghrajClass extends Applet
{
String str;
public void init()
{
str=getParameter("string");
if(str==null)
{
str="JAVA";
}
str="Hello "+str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
// helloapplet.html
html>
<head>
<title>my first appler programm</title>
</head>
<body>
<APPLET CODE=MeghrajClass.class
WIDTH=400
HEIGHT=200>
<PARAM NAME="Message"
VALUE="Meghraj!">
</APPLET>
</body>
</html>
OUTPUT:
25
MS