You are on page 1of 80

Assignments --16-Dec-2016

1. Write a JSP that prints the following


for 100 levels
*
* *
* * *
* * * * *................
<html>
<head>
</head>
<body>
<%
for(int i=1;i<=100;i++)
{
for(int j=1;j<i+1;j++)
{
%>
*
<% }%>
<br></br>
<% } %>
</body>
</html>
________________________________________________________________________________
_____________________________
2. Modify the above example and accept the symbol and levels from user.
<html>
<head>
</head>
<body>
<form action="">
Enter Level Range<input type="text" name="range"/>
Enter Symbol To Print<input type="text" name="symbol"/><br></br>
<input type="submit" value="Print"/><br></br>
</form>
<%
String in = request.getParameter("range");
String sys = request.getParameter("symbol");
if(in!=null)
{
for(int i=1;i<=Integer.parseInt(in);i++)
{
for(int j=1;j<i+1;j++)
{
%>
<%=sys %>
<% }%>
<br></br>
<% } } %>
</body>
</html>
________________________________________________________________________________

_____________________________
3. Write a jsp that will accept name from user and print it.
jsp may be accessed from different browsers
or tabs or refreshed
everytime u add a name all earlier names should be displayed.
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Arrays"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
g/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="">
Enter Name To Store<input type="text" name="uin"/>
<input type="submit" value="Add Name"/>
</form>
<%! ArrayList<String> al = new ArrayList<String>(); %>
<%
String str = request.getParameter("uin");
if(str!=null)
al.add(str);
for(int i=0;i<al.size();i++)
{
String name = al.get(i);
%>
<%=name %>
<%} %>
</body>
</html>
________________________________________________________________________________
_____________________________
4. Write a JSP application that will
Textfield drop-down-list textfield
36
conver-to-farhenheit
98
101
convert-to-celsius
35
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
g/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="">
<%
double res=0.0;

if("POST".equalsIgnoreCase(request.getMethod()))
{
String per = "FToC";
String per1 = "CToF";
String str=request.getParameter("list");
String val=request.getParameter("out");
double num1=Double.parseDouble(request.getParameter("in"));
if(str.equals(per))
{
res = (num1-32)*5/9;
}
else if(str.equals(per1))
{
res = (num1 * 1.8) + 32;
}
%>
<%} %>
<input type="text" name="in">
<select name="list">
<option value="FToC">F To C</option>
<option value="CToF">C To F</option>
</select>
<input type="text" name="output" value="<%=res%>">
<input type="submit" value="Calculate">
</form>
</body>
</html>
________________________________________________________________________________
_____________________________
5. write a jsp application that will have
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
g/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="">
<select name="list" size=3 multiple="multiple">
<option >Jalgaon</option>
<option>Pune</option>
<option>Mumbai</option>
</select>
<input type="submit" value="Show">
<%!ArrayList<String> al = new ArrayList<String>(); %>
<%
String[] cities=request.getParameterValues("list");
if(cities!=null)
{
for(int i=0;i<cities.length;i++)

{
al.add(cities[i]);
}
for(int j=0;j<al.size();j++)
{
%>
<%=al.get(j)+"," %>
<%}}
else
{
al.clear();
}%>
</form>
</body>
</html> --- preferred cities of work
ok button
Once user selects the preffered cities
display === u have provided n preffered cities
comma separated list
( String[] selectedValues = request.getParameterValues("listname") ;)

________________________________________________________________________________
_____________________________
6. Show a jsp having a few checkboxes
Education
cb ssc
cb hsc cb BE cb bsc ...................
Radiobutton
rb fresher rb experienced } select any one
ok button
Show output as a table
Your educational qualification is
1.
2.
3.
4.
You are a frsher/exp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
g/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="POST" action="">
<input type="checkbox" value="SSC" name="1"/>SSC<br/>
<input type="checkbox" value="HSC" name="1"/>HSC<br/>
<input type="checkbox" value="BE" name="1"/>BE<br/>
<input type="checkbox" value="PG" name="1"/>PG<br/><br/>
<input type="radio" id="Freshers" value="Freshers" name="2"/>Freshers
<input type="radio" id="Exprience" value="Exprience" name="2"/>Exprience

<br/>
<input type="submit" id="Submit"/>
</form>
<table border=1>
<tr><th>SrNo.</th><th>Education Details</th></tr>
<%
int count=1;
String[] vals = request.getParameterValues("1");
String val = request.getParameter("2");
if(vals!=null)
{
for(int i=0;i<vals.length;i++)
{
%>
<tr><td><%=count%></td><td><%=vals[i]%></td></tr>
<%
count++;
}}%>
</table>
<%
if(val!=null)
{
%>
You are a <%=val %>
<%} %>
</body>
</html>
________________________________________________________________________________
_____________________________
7. Write a JSP application that will accept a comma separated list of
names from the user and display the list in sorted order
radiobuttons rb asc rb desc.
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Collections"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
g/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="">
Enter Comma Separated Names<input type="text" name="in">
<input type="submit" value="Show Sorted"></br>
<input type="radio" value="ascending" name="2"/>Ascending
<input type="radio" value="descending" name="2"/>Descending
</form>
<%
ArrayList<String> al = new ArrayList<String>();
String str= request.getParameter("in");
if(str!=null)
{
String[] Sorted = str.split(",");

for(int i=0;i<Sorted.length;i++)
{
al.add(Sorted[i]);
}
String val = request.getParameter("2");
Collections.sort(al);
if(val.equalsIgnoreCase("Ascending"))
{%>
Sorted data in ascending order .... <br>
<%
for(int j=0;j<al.size();j++)
{
%>
<%=al.get(j) %>
<%}}
else if(val.equalsIgnoreCase("Descending"))
{
%>
Sorted data in descending order.... <br>
<%
Collections.reverse(al);
for(int j=0;j<al.size();j++)
{
%>
<%=al.get(j) %>
<%}
}
} %>
</body>
</html>
________________________________________________________________________________
_____________________________
8. Write a JSP application for Updating the records in the Student table.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.SQLException"%>
<%@ page import="java.sql.Statement"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="cdac.util.connect.DbConnect" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
g/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="Perform.jsp">
<select name="rno">
<%
Connection con = DbConnect.myConnection();
Statement state= con.createStatement();
String Roll = "select Roll_No from Students";
ResultSet Rollres = state.executeQuery(Roll);
while(Rollres.next())

{
int no = Rollres.getInt(1);
%>
<option> <%=no %> </option>
<%}
%>
</select>
<input type="submit" value="Update It">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.SQLException"%>
<%@ page import="java.sql.Statement"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="cdac.util.connect.DbConnect" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
g/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="Modify.jsp">
<%
Connection con = DbConnect.myConnection();
if("POST".equalsIgnoreCase(request.getMethod()))
{
String val=request.getParameter("rno");
String select = "select * from Students where Roll_No="+Integer.parseInt
(val);
Statement state = con.createStatement();
ResultSet dresult = state.executeQuery(select);
%>
<%
while(dresult.next())
{
int no = dresult.getInt(1);
String nm = dresult.getString(2);
int mrk = dresult.getInt(3);
%>
<input type="text" value="<%=no %>" readonly name="rno"><br/>
<input type="text" value="<%=nm %>" name="Name"><br/>
<input type="text" value="<%=mrk %>" name="Mark"><br/>
<%}}
%>
<input type="submit" value="Modify It">
</form>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.SQLException"%>
<%@ page import="java.sql.Statement"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="cdac.util.connect.DbConnect" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
g/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
Connection con = DbConnect.myConnection();
if("POST".equalsIgnoreCase(request.getMethod()))
{
String r=request.getParameter("rno");
String n=request.getParameter("Name");
String m=request.getParameter("Mark");
String update = "update Students set Marks=?,Name=? where Roll_No=?";
PreparedStatement upstate = con.prepareStatement(update);
upstate.setInt(3,Integer.parseInt(r));
upstate.setString(2,n);
upstate.setInt(1,Integer.parseInt(m));
upstate.executeUpdate();
Statement state= con.createStatement();
String Roll = "select * from Students";
ResultSet Rollres = state.executeQuery(Roll);
%>
<table border=1>
<%
while(Rollres.next())
{
int no = Rollres.getInt(1);
String nm = Rollres.getString(2);
int mrk = Rollres.getInt(3);
%>
<tr><td><%=no %></td><td><%=nm %></td><td><%=mrk %></td></tr>
<%}}
%>
</table>
</body>
</html>
________________________________________________________________________________
_____________________________
9. Write a JSP applciation to delete a record.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager"%>

<%@ page import="java.sql.SQLException"%>


<%@ page import="java.sql.Statement"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
g/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="">
<%
Class.forName("com.mysql.jdbc.Driver");//Gives mysql Drivers
String URL = "jdbc:mysql://localhost:3307/StudentData"; //Url of Databas
e
Connection con = DriverManager.getConnection(URL,"root","root");
//Connetcts To Database
%>
<select name="list">
<%
Statement state=con.createStatement();
String Roll = "select Roll_No from Students";
ResultSet Rollres = state.executeQuery(Roll);
while(Rollres.next())
{
int no = Rollres.getInt(1);
%>
<option> <%=no %> </option>
<%}
%>
</select>
<input type="submit" value="Delete">
<%
if("POST".equalsIgnoreCase(request.getMethod()))
{
String val=request.getParameter("list");
String delete = "delete from Students where Roll_No=?";
PreparedStatement dstate = con.prepareStatement(delete);
dstate.setInt(1,Integer.parseInt(val));
dstate.executeUpdate();
if(val!=null)
{
String dselect = "select * from Students";
ResultSet dresult = state.executeQuery(dselect);
%>
<table border=1>
<%
while(dresult.next())
{
int no = dresult.getInt(1);
String nm = dresult.getString(2);
int mrk = dresult.getInt(3);
%>
<tr><td><%=no %></td><td><%=nm %></td><td><%=mrk %></td></tr>

<%}}}
%>
</table>
</form>
</body>
</html>
________________________________________________________________________________
_____________________________
10. (optional) Write a JSP search application that will
show two textfields
dob-from
dob-to
show all students in this range.
________________________________________________________________________________
_____________________________
15-Dec-2016
1. Write a simple web application that does not have any servlet
it has only one html = poem.html
url = http://localhost:8080/PoemApp/poem.html
<body>
<h3>Twinkle twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.
Twinkle twinkle, little star,
How I wonder what you are.</h3>
<h1><marquee>This is First Demo</marquee></h1>
</body>
_____________________________________________________________________________
2. Write a web application that will display a login page from a
LoginServlet
url = http://localhost:8080/LoginApp/login
protected void doGet(HttpServletRequest request, HttpServletResponse response) t
hrows ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = new PrintWriter(response.getOutputStream());
pw.println("<html><body><table border=1>");
pw.println("<tr>");
pw.print("<td><h3>Enter User Name</h3></td>");
pw.print("<td><input type=text></td>");
pw.println("</tr>");
pw.println("<tr>");
pw.print("<td><h3>Enter Password</h3></td>");
pw.print("<td><input type=password></td>");
pw.println("</tr>");
pw.println("<tr>");
pw.print("<td colspan=2><input type=button value=Login></td>");
pw.println("</tr>");
//pw.println();
//pw.print("<h2>Enter User Name</h2>"+"<input type=text/>");
pw.println("</table></body></html>");
pw.close();
}

_____________________________________________________________________________
3. Write a PrimeServlet that will take the min and max from request
and show all prime numbers in between
url = http://localhost:8080/PrimeApp/show_prime?min=3&max=900
protected void doGet(HttpServletRequest request, HttpServletResponse response) t
hrows ServletException, IOException
{
String in1 = request.getParameter("min");
String in2 = request.getParameter("max");
response.setContentType("text/html");
PrintWriter pw = new PrintWriter(response.getOutputStream());
int num1 = Integer.parseInt(in1);
int num2 = Integer.parseInt(in2);
int count;
System.out.println("Prime nos are");
for(int j=num1;j<=num2;j++)
{
count = 0;
for (int i = 2; i<= j / 2; i++)
{
if (j % i == 0)
{
count++;
break;
}
}
if (count == 0)
{
pw.println(j);
}
}
pw.close();
}
_____________________________________________________________________________
4. Write a DBServlet that will show all the students having birthdate
greater than that passed in the url
url = http://localhost:8080/DBApp/show?dob=12-12-1998
try
{
String mr = request.getParameter("mark");
int mrk = Integer.parseInt(mr);
Class.forName("com.mysql.jdbc.Driver");//Gives mysql Dri
vers

String URL = "jdbc:mysql://localhost:3307/StudentData";


//Url of Database
Connection con = DriverManager.getConnection(URL,"root",
//Connetcts To Database

"root");

System.out.println("Connection Established");
String select = "select * from Students where Marks > ?"
;
PreparedStatement state = con.prepareStatement(select);
state.setInt(1,mrk);
ResultSet rs = state.executeQuery();
while(rs.next())
{
pw.println("<tr>");
pw.println("<td>"+rs.getInt(1)+"</td>");
pw.println("<td>"+rs.getString(2)+"</td>");
pw.println("<td>"+rs.getString(3)+"</td>");
pw.println("</tr>");
}
pw.println("</table></body></html>");
pw.close();
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) t
hrows ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = new PrintWriter(response.getOutputStream());
String val1 = request.getParameter("rno");
String val2 = request.getParameter("name");
String val3 = request.getParameter("marks");
int Rno = Integer.parseInt(val1);
int Marks = Integer.parseInt(val3);
try
{
Class.forName("com.mysql.jdbc.Driver");//Gives mysql Dri
vers

String URL = "jdbc:mysql://localhost:3307/StudentData";


//Url of Database
Connection con = DriverManager.getConnection(URL,"root",
//Connetcts To Database

"root");

System.out.println("Connection Established");
String insert = "insert into Students values(?,?,?)";
PreparedStatement state = con.prepareStatement(insert);
state.setInt(1,Rno);
state.setString(2,val2);
state.setInt(3,Marks);
state.executeUpdate();
pw.println("Record Inserted Successfully");
pw.close();
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
_____________________________________________________________________________
14-Dec-2016
1. Write a JDBC client that will ask the use about tablename
fieldname and type
create the table as specified.
Student table ---- rollno, name, address, dob
package cdac.DatabaseDemo;
import
import
import
import
import

java.sql.Connection;
java.sql.DriverManager;
java.sql.SQLException;
java.sql.Statement;
java.util.Scanner;

public class StudentDemo


{
public static void main(String[] args) throws ClassNotFoundException, SQ
LException
{
Class.forName("com.mysql.jdbc.Driver");//Gives mysql Drivers
String URL = "jdbc:mysql://localhost:3307/StudentData"; //Url of
Database
Connection con = DriverManager.getConnection(URL,"root","root");
Statement state = con.createStatement();//Connetcts To Database
Scanner sc = new Scanner(System.in);
System.out.println("Connection Established");
System.out.println("Enter the table name");

String name=sc.nextLine();
System.out.println("enter Attributes of table in comma seperated
");
String data= sc.nextLine();
try
{
String query = "create table "+name+"("+data+")";
state.execute(query);//for DDL Commands
System.out.println("table created");
}
catch(Exception e)
{
System.out.println("Table is all ready created..");
}
}
}
________________________________________________________________________________
________________________
2. Write a CRUD application for Student table .
a menu driven code.
Use statment for select query
Use PreparedStament for DML queries
package cdac.DatabaseDemo;
import
import
import
import
import
import
import

java.sql.Connection;
java.sql.DriverManager;
java.sql.PreparedStatement;
java.sql.ResultSet;
java.sql.SQLException;
java.sql.Statement;
java.util.Scanner;

public class CrudOperation


{
public static void main(String[] args) throws ClassNotFoundException, SQ
LException
{
Class.forName("com.mysql.jdbc.Driver");//Gives mysql Drivers
String URL = "jdbc:mysql://localhost:3307/StudentData"; //Url of
Database
Connection con = DriverManager.getConnection(URL,"root","root");
//Connetcts To Database
Scanner sc = new Scanner(System.in);
System.out.println("Connection Established");
Statement state = con.createStatement();
while(true)
{
System.out.println("\n1.Create Table \n2.Insert Record \
n3.Fetch Details \n4.Update Record \n5.Delete Record \n6.Exit \n enter u r choic
e");

int ch = sc.nextInt();
switch(ch)
{
case 1:
try
{
String Query = "create table Stu
dents(Roll_No int,Name varchar(30),Marks int)";
state.execute(Query);//for DDL C
ommands
System.out.println("table create
d");
}
catch(Exception e)
{
System.out.println("Tabl
e is all ready created..");
System.exit(0);
}
break;
case 2:
System.out.println("enter values
to insert into Table");
System.out.println("enter Roll_N
o");
int rno = sc.nextInt();
System.out.println("enter Name")
;
String name = sc.next();
System.out.println("enter Marks"
);
int mark = sc.nextInt();
String insert = "insert into Stu
dents values(?,?,?)";
PreparedStatement pstate = con.p
repareStatement(insert);
pstate.setInt(1,rno);
pstate.setString(2,name);
pstate.setInt(3,mark);
pstate.executeUpdate();
System.out.println("inserted suc
cessfully");
break;
case 3:
String select = "select * from S
tudents";
ResultSet result = state.execute
Query(select);
while(result.next())
{
int no = result.getInt(1
);
String nm = result.getSt
ring(2);
int mrk = result.getInt(
3);
System.out.println(no +"

\t"+nm+"\t"+mrk);
}
System.out.println("data fetched
successfully");
break;
case 4:
String Roll = "select Roll_No fr
om Students";
ResultSet Rollres = state.execut
eQuery(Roll);
while(Rollres.next())
{
int no = Rollres.getInt(
1);
System.out.println(no);
}
System.out.println("\n\n\nenter
Student Rno from above available data in which u want to update");
int chrno = sc.nextInt();
System.out.println("enter marks"
);
int newmarks= sc.nextInt();
String update = "update Students
set Marks=? where Roll_No=?";
PreparedStatement upstate = con.
prepareStatement(update);
upstate.setInt(1,newmarks);
upstate.setInt(2,chrno);
upstate.executeUpdate();
System.out.println("records Upda
ted successfully");
String nselect = "select * from
Students";
ResultSet nresult = state.execut
eQuery(nselect);
while(nresult.next())
{
int no = nresult.getInt(
1);
String nm = nresult.getS
tring(2);
int mrk = nresult.getInt
(3);
System.out.println(no +"
\t"+nm+"\t"+mrk);
}
break;
case 5:
System.out.println("enter Studen
t Rno of which u want to delete record");
int drno = sc.nextInt();

String delete = "delete from Stu


dents where Roll_No=?";
PreparedStatement dstate = con.p
repareStatement(delete);
dstate.setInt(1,drno);
dstate.executeUpdate();
System.out.println("records Dele
ted successfully");
String dselect = "select * from
Students";
ResultSet dresult = state.execut
eQuery(dselect);
System.out.println("Updated Reco
rd is: \n");
while(dresult.next())
{
int no = dresult.getInt(
1);
String nm = dresult.getS
tring(2);
int mrk = dresult.getInt
(3);
System.out.println(no +"
\t"+nm+"\t"+mrk);
}
break;
case 6:
System.exit(0);
default:
System.out.println("U Have Enter
ed Inavalid Choice");
break;
}
}
}
}
________________________________________________________________________________
________________________
3. Try out the transaction code such that once it will rollback and once it will
commit.
package cdac.DatabaseDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TransactionDemo
{

public static void main(String[] args) throws ClassNotFoundExcep


tion, SQLException
{
Class.forName("com.mysql.jdbc.Driver");//Gives mysql Dri
vers
String URL = "jdbc:mysql://localhost:3307/StudentData";
//Url of Database
Connection con = DriverManager.getConnection(URL,"root",
"root");
String sql = "insert into Studdemo values (?,?,?)";
PreparedStatement pstmt=null;
try {
pstmt = con.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
try{
con.setAutoCommit(false);
pstmt.setInt(1, 104);
pstmt.setString(2, "chetan");
pstmt.setInt(3, 88);
pstmt.executeUpdate();
pstmt.setInt(1, 17);
pstmt.setString(2, "Milind");
pstmt.setInt(3, 78);
pstmt.executeUpdate();
pstmt.setInt(1, 18);
pstmt.setString(2, "Lokesh");
pstmt.setInt(3, 77);
pstmt.executeUpdate();
con.commit();
System.out.println("COMMITTED....");
}
catch(SQLException sqle)
{
try {
con.rollback();
System.out.println("ROLLING BACK...");
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
}

________________________________________________________________________________

__________________________
4. Find out what is MIME type and google the different mime types.
MIME stands for "Multipurpose Internet Mail Extensions. It's a way of
identifying files on the Internet according to their nature and format.
For example, using the "Content-type" header value defined in a HTTP
response, the browser can open the file with the proper extension/plugin.
________________________________________________________________________________
__________________________
5. Browse the net to see examples of Http Request and
HttpResponse
________________________________________________________________________________
____________________________
13-Dec-2016
1. Write a Thread application using runnable
Job1 compute the Fibonacci series
Job 2 display prime numbers within range entered by user
MainThread will create the threads .
Give name to each thread and display it with their output
package test;
import java.util.Scanner;
public class JobFiboo implements Runnable
{
@Override
public void run()
{
System.out.println("Ur runnig "+Thread.currentThread().getName()
);
Scanner sc = new Scanner(System.in);
System.out.println("enter the range upto fiboo u want");
int len = sc.nextInt();
int[] arr = new int[len];
arr[0]=1;
arr[1]=1;
for(int i=2;i<arr.length;i++)
{
arr[i]=arr[i-2]+arr[i-1];
}
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}
package test;
import java.util.Scanner;
public class JobPrime implements Runnable
{
@Override
public void run()
{
System.out.println("Ur runnig "+Thread.currentThread().getName()

);
Scanner sc = new Scanner(System.in);
System.out.println("enter the range in between prime no u want")
;
int start = sc.nextInt();
int end=sc.nextInt();
int count;
System.out.println("Prime nos are");
for(int j=start;j<=end;j++)
{
count = 0;
for (int i = 2; i<= j / 2; i++)
{
if (j % i == 0)
{
count++;
break;
}
}
if (count == 0)
{
System.out.println(j);
}
}
}
}
package test;
public class MainThread
{
public static void main(String[] args) throws InterruptedException
{
JobFiboo f1=new JobFiboo();
Thread tf=new Thread(f1);
tf.setName("Fibbonacci");
JobPrime p1=new JobPrime();
Thread tp=new Thread(p1);
tp.setName("Prime");
tf.start();
tf.join();
Thread.sleep(1000);
tp.start();
}
}
________________________________________________________________________________
________________________
2. Write a thread application
that will have a mainthread that starts a tablethread
that displays tables specified by user till the user says quit
main thread will wait for table thread to end
in the end print --- the cost of printint tables is ______
Thank u for using our service

( join )
package tableDemo;
import java.util.Scanner;
public class TableThread implements Runnable
{
@Override
public void run()
{
while(true)
{
System.out.println("enter number of table u want to View
");
Scanner sc = new Scanner(System.in);
String num = sc.next();
if(!num.equalsIgnoreCase("quit"))
{
for(int i=1;i<=10;i++)
{
System.out.println(num+"*"+i+"="+Integer
.parseInt(num)*i);
}
}
else
{
break;
}
}
}
}
package tableDemo;
public class MainThread
{
public static void main(String[] args) throws InterruptedException
{
TableThread th=new TableThread();
Thread t1=new Thread(th);
t1.start();
t1.join();
System.out.println("Cost of the table is...40");
System.out.println("Thanku....");
}
}
________________________________________________________________________________
__________________________
3.(optional) Implement a Producer Consumer application using multithreading
T1 = Producer
run ---while(true)
--- produce item
--- add to the tray

====== tray.notifyAll
if tray is full
tray.wait
T2 = Consumer
run ----while(true)
if tray is empty
tray.wait()
--- pick from tray
--- consume item
===== tray.notifyAll()

Write a threadsafe Tray that has a capacity of 10


array of int
push ---- Thread safe
pop ----- Thread safe
________________________________________________________________________________
____________________________________
4. Modify the Multithreaded server to make it a broadcastMultithreadedserver.
Test it on different machines.
package MultithreadServer;
import java.io.PrintWriter;
import java.net.Socket;
public class MessegeThread extends Thread
{
Socket clientSocketInfo;
String news;
public MessegeThread(Socket clientSocketInfo2,String news)
{
super();
this.clientSocketInfo = clientSocketInfo2;
this.news=news;
}
@Override
public void run()
{
try
{
PrintWriter pw = new PrintWriter(clientSocketInfo.ge
tOutputStream());
while(true)
{
pw.println(news);
pw.flush();
}
}
catch(Exception e)
{
e.printStackTrace();
}

}
}
package MultithreadServer;
import
import
import
import

java.io.IOException;
java.net.ServerSocket;
java.net.Socket;
java.util.Scanner;

public class ThreadServer


{
public static void main(String[] args) throws IOException
{
ServerSocket server = new ServerSocket(4324);
Scanner sc = new Scanner(System.in);
String news;
System.out.println("Enter ur news");
news=sc.nextLine();
while(true)
{
System.out.println("Server is waiting for the client ...
");
Socket clientSocketInfo = server.accept(); //blocking ca
ll
System.out.println("Client requested.."+clientSocketInfo
);
new MessegeThread(clientSocketInfo,news).start();
}
}
}
package MultithreadServer;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class MyCliet
{
public static void main(String[] args) throws IOException
{
Socket connectToServer = new Socket("127.0.0.1", 4324);
Scanner readFrmSoc = new Scanner(connectToServer.getInpu
tStream());
String msg = readFrmSoc.nextLine();
System.out.println("The server said "+msg);
}
}

________________________________________________________________________________
__________________________________
5. Create a new Project Leopard and write a class that uses the
study.hasa.Product class or any other class in current project
( make the classes available using jar )
run the same program on cmd prompt.
package Demo;
import MultithreadServer.MyCliet;
public class TestJar {
public static void main(String[] args)
{
MyCliet m=new MyCliet();
System.out.println(m);
}
}
________________________________________________________________________________
____________________________________
12-Dec-2016
1. Complete the TestReflection class written in the classroom.
package cdac.Reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class ReflectionDemo
{
public static void main(String[] args) throws ClassNotFoundException {
MyDate d = new MyDate();
//Class Obj1 = Class.forName("java.lang.String");
Class Obj2 = java.lang.String.class;
//Class Obj3 = d.getClass();
getClassMetadata(Obj2);
}
public static void getClassMetadata(Class obj)
{
System.out.println("name of the class is :"+ obj.getName());
System.out.println("super class of the class is :"+ obj.getSuperclass())
;
System.out.println("Packages of the class is :"+ obj.getPackage());
System.out.println("the constructors of this class are ");
Constructor [] con = obj.getDeclaredConstructors();
for(Constructor c : con)

{
System.out.println(c);
}
System.out.println();
System.out.println("the methods of this class are :");
Method[] meth = obj.getDeclaredMethods();
for(Method m : meth)
{
System.out.println(m);
}
System.out.println();
System.out.println("the fileds of this class are :");
Field[] field = obj.getDeclaredFields();
for(Field f : field)
{
System.out.println(f);
}
System.out.println();
System.out.println("the Interfaces implemented by this class are :");
Class[] intr = obj.getInterfaces();
for(Class i : intr)
{
System.out.println(i);
}
boolean t = Modifier.isPublic(0);
System.out.println(t);
// show all the modifiers of the class
}
}
________________________________________________________________________________
___________
2. Try out the instantiation and method invocation code with different values.
package cdac.Reflection;
import java.util.Scanner;
public class InstantiationDemo
{
public static void main(String[] args) throws ClassNotFoundException, In
stantiationException, IllegalAccessException
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the class FQCN");
String fqcn = sc.next();
Class Obj = Class.forName(fqcn);
Object obj1 = Obj.newInstance();
System.out.println(obj1);
}

}
package cdac.Reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;
public class MethodInvokeDemo
{
public static void main(String[] args) throws ClassNotFoundException, In
stantiationException, IllegalAccessException, NoSuchMethodException, SecurityExc
eption, IllegalArgumentException, InvocationTargetException
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the class FQCN");
String fqcn = sc.next();
Class Obj = Class.forName(fqcn);
Object obj = Obj.newInstance();
System.out.println("enter the method name");
String methodName = sc.next();
Method method =Obj.getMethod(methodName,null);
Object returnValue = method.invoke(obj, null);
System.out.println(returnValue);
//if method not return..
method.invoke(obj, null);
//For Static method
//Method m =Obj.getMethod(methodName, null);
//m.invoke(null, null);
}
}
________________________________________________________________________________
______________
3. Write a multithreaded application
thread1 = accept 10 names from user and add it to the file
thread2 = read names from files and show the length of each name
main thread should create both the threads.
package cdac.MultiThreading;
import
import
import
import

java.io.FileNotFoundException;
java.io.FileOutputStream;
java.io.PrintWriter;
java.util.Scanner;

public class AcceptThread extends Thread


{
public void run()
{

try
{
FileOutputStream fout = new FileOutputStream("C:\\JavaPr
og\\cdac\\Threading\\ThreadingDemo\\Names.txt",true);
PrintWriter pw = new PrintWriter(fout);
Scanner sc = new Scanner(System.in);
for(int i = 0;i<3;i++)
{
System.out.println("enter name");
String name = sc.next();
pw.println(name);
pw.flush();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
package cdac.MultiThreading;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadThread extends Thread
{
public void run()
{
try
{
FileInputStream fin = new FileInputStream("C:\\JavaProg\
\cdac\\Threading\\ThreadingDemo\\Names.txt");
Scanner sc = new Scanner(fin);
while(sc.hasNextLine())
{
String s = sc.nextLine();
int len =s.length();
System.out.println("name "+s+" "+"length is "+l
en);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
package cdac.MultiThreading;
public class ReadWrite

{
public static void main(String[] args) throws InterruptedException
{
AcceptThread accept = new AcceptThread();
ReadThread read = new ReadThread();
accept.start();
read.start();
}
}
________________________________________________________________________________
_____________
4. read the job of join() API in thread class

________________________________________________________________________________
______________
10-Dec-2016
1. Run the chat application in class on same machine and on different machines.
package cdac.Socket;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ServerMachine
{
public static void main(String[] args) throws IOException
{
ServerSocket server = new ServerSocket(14365);
System.out.println("Server is waiting for the client ...");
Socket clientSocketInfo = server.accept(); //blocking call
System.out.println("Client requested.."+clientSocketInfo);
PrintWriter pw = new PrintWriter(clientSocketInfo.getOutputStrea
m());
Scanner sc = new Scanner(System.in);
Scanner readFromSoc = new Scanner(clientSocketInfo.getInputStrea
m());
while(true)
{
System.out.println("enter ur msg");
String m = sc.nextLine();
pw.println(m);
pw.flush();
String m1 =readFromSoc.next();
System.out.println("Client said "+m1);

}
}
}
package cdac.Socket;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ClientMachine
{
public static void main(String[] args) throws UnknownHostException, IOEx
ception
{
//connect to server
Socket connectToServer = new Socket("127.0.0.1", 14365);
Scanner readFrmSoc = new Scanner(connectToServer.getInputStream(
));
PrintWriter pw = new PrintWriter(connectToServer.getOutputStream
());
Scanner readFrmKbd = new Scanner(System.in);
while(true)
{
String msg = readFrmSoc.nextLine();
System.out.println("The server said "+msg);
System.out.println("eneter ur msg");
String m = readFrmKbd.next();
pw.println(m);
pw.flush();
}
}
}
________________________________________________________________________________
______________________________
2. what would you do to connect multiple clients to the server ?
________________________________________________________________________________
_______________________________
3. Write a client server application that would send Book object from server to
client and display the object details on client.
(use ObjectOutputStream and ObjectInputStream and make
Book Serializable )
package cdac.ClientServer;
import
import
import
import
import

java.io.EOFException;
java.io.FileInputStream;
java.io.IOException;
java.io.ObjectInputStream;
java.io.PrintWriter;

import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class BookUser
{
public static void main(String[] args) throws UnknownHostException, IOEx
ception, ClassNotFoundException
{
Socket connectToServer = new Socket("127.0.0.1", 2246);
Scanner readFrmSoc = new Scanner(connectToServer.getInputStream(
));
PrintWriter pw = new PrintWriter(connectToServer.getOutputStream
());
Scanner readFrmKbd = new Scanner(System.in);
FileInputStream fin =new FileInputStream("C:\\JavaProg\\cdac\\Th
reading\\ThreadingDemo\\BookData.txt");
ObjectInputStream obj=new ObjectInputStream(fin);
while(true)
{
try
{
Object bk=obj.readObject();
System.out.println(bk);
}
catch(EOFException e)
{
System.out.println("eneter ur msg");
String m = readFrmKbd.next();
pw.println(m);
pw.flush();
break;
}
}
}
}
package cdac.ClientServer;
import
import
import
import
import
import

java.io.FileOutputStream;
java.io.IOException;
java.io.ObjectOutputStream;
java.net.ServerSocket;
java.net.Socket;
java.util.Scanner;

public class BookSender


{
public static void main(String[] args) throws IOException
{
ServerSocket server = new ServerSocket(2246);
System.out.println("Server is waiting for the client ...");
Socket clientSocketInfo = server.accept(); //blocking call
System.out.println("Client requested.."+clientSocketInfo);
Scanner readFromSoc = new Scanner(clientSocketInfo.getInputStrea
m());

Book a = new Book();


Book b=new Book(102, "Java", 450);
Book b1=new Book(103, "CPP", 400);
Book b2=new Book(104, "Os", 550);
FileOutputStream fout=new FileOutputStream("C:\\JavaProg\\cdac\\
Threading\\ThreadingDemo\\BookData.txt");
ObjectOutputStream obj=new ObjectOutputStream(fout);
obj.writeObject(b);
obj.writeObject(b1);
obj.writeObject(b2);
obj.writeObject(a);
obj.close();
fout.close();
String m1 =readFromSoc.next();
System.out.println("Client said "+m1);
}
}
________________________________________________________________________________
___________________________________________
4. Write a UDP socket application that will do as follows ---a. sender reads data from the file specified by user
b. sender sends each line in a packet to the receiver
c. receiver receives the packet and displays on console.
Once the application runs on your machine u run it on different machines.
package cdac.UDPSocket;
import
import
import
import
import
import

java.io.FileInputStream;
java.io.IOException;
java.net.DatagramPacket;
java.net.DatagramSocket;
java.net.InetAddress;
java.util.Scanner;

public class Sender


{
public static void main(String[] args) throws IOException
{
DatagramSocket sender = new DatagramSocket();
InetAddress add= InetAddress.getByName("127.0.0.1");
FileInputStream fin = new FileInputStream("C:\\JavaProg\
\cdac\\Threading\\UDPSocketDemo\\Poem.txt");
Scanner sc = new Scanner(fin);
String poem="";
while(sc.hasNextLine())
{
try
{
poem+=sc.nextLine();
}
catch(Exception e)
{
break;
}
}

byte[] msg =poem.getBytes();


DatagramPacket packet = new DatagramPacket(msg,msg.lengt
h,add,6789);
sender.send(packet);
}
}
package cdac.UDPSocket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Reciver
{
public static void main(String[] args) throws IOException
{
DatagramSocket receiver = new DatagramSocket(6789);
byte[] res= new byte[100];
DatagramPacket packet = new DatagramPacket(res, res.length);
receiver.receive(packet);
System.out.print(new String(packet.getData()));
receiver.close();
}
}
________________________________________________________________________________
_________________________
5. Write a thread program that will create 2 threads
thread1 OddThread class= print the odd numbers
use sleep method,getname
thread2 EvenThread class = print the even numbers
sleep method, getname
accept the range from user
main thread will be in the class MainClass ( start, setname )
here you give names to both the threads
and print the name every time u print the number
package cdac.Threading;
public class RunOddEven
{
public static void main(String[] args) throws InterruptedException
{
EvenDemo e = new EvenDemo();
e.setName("Even");
e.start();
System.out.println(e.getName());
OddThread o = new OddThread();
o.setName("Odd");
o.start();
System.out.println(o.getName());
}
}

package cdac.Threading;
public class EvenDemo extends Thread
{
public void run()
{
for(int i=1;i<100;i++)
{
if(i%2==0)
{
System.out.println("Even Number Is :-"+i);
}
}
}
}
package cdac.Threading;
public class OddThread extends Thread
{
public void run()
{
for(int i=1;i<100;i++)
{
if(i%2==1)
{
System.out.println("Odd Number Is :-"+i);
}
}
}
}
________________________________________________________________________________
_________________________
9-Dec-16
1. What is the Data type of "in" static field of System class.
public static final InputStream in
The "standard" input stream. This stream is already open and ready to supply inp
ut data. Typically this stream corresponds to keyboard input or another input so
urce specified by the host environment or user.
1. What is the Data type of "out" static field of System class.
public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept ou
tput data. Typically this stream corresponds to display output or another output
destination specified by the host environment or user.
2. Write a program that will read any text file and display it on console with l
inenumbers.
package cdac.IODemo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFromFile

{
public static void main(String[] args) throws FileNotFoundException
{
FileInputStream fin=new FileInputStream("C:\\JavaProg\\cdac\\IOA
pplication\\IOPrograming\\Demo.txt");
Scanner sc = new Scanner(fin);
int count=1;
while(sc.hasNext())
{
String input = sc.nextLine();
System.out.println(count+"."+input);
count++;
}
}
}
________________________________________________________________________________
__________________________
3. Write a program that will accept names from user and add them to a file stud_
names.txt.
Write another class that will read all the names from the file
and show the sorted list on console.
package cdac.IODemo;
import
import
import
import

java.io.FileOutputStream;
java.io.FileNotFoundException;
java.io.PrintWriter;
java.util.Scanner;

public class WriteToFile


{
public static void main(String[] args) throws FileNotFoundException
{
FileOutputStream fout=new FileOutputStream("C:\\JavaProg\\cdac\\
IOApplication\\IOPrograming\\Student_Name.txt");
Scanner sc = new Scanner(System.in);
PrintWriter pw=new PrintWriter(fout);
String str="";
while(!str.equalsIgnoreCase("quit"))
{
System.out.println("Enter the name of the student");
str=sc.nextLine();
if(!str.equals("quit"))
{
pw.println(str);
}
pw.flush();
}
pw.close();
}
}

package cdac.IOProgDemo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import
import
import
public
{

java.util.Iterator;
java.util.Scanner;
java.util.TreeSet;
class SortFile

public static void main(String[] args) throws FileNotFoundException


{
FileInputStream fin=new FileInputStream("C:\\JavaProg\\cdac\\IOA
pplication\\IOPrograms\\Student_Name.txt");
Scanner sc = new Scanner(fin);
TreeSet<String> ts = new TreeSet<String>();
while(sc.hasNext())
{
String input = sc.nextLine();
ts.add(input);
}
Iterator<String> it = ts.iterator();
System.out.println("Data in sorted Order..");
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
________________________________________________________________________________
_____________________________
4. Write a program to accept product details from user and store it in a binary
file.
Write a program to read the binary file and show the details of the product id e
ntered by the user.
package cdac.IOProgDemo;
import
import
import
import

java.io.DataOutputStream;
java.io.FileOutputStream;
java.io.IOException;
java.util.Scanner;

public class DataToBinary


{
public static void main(String[] args) throws IOException
{
FileOutputStream fout=new FileOutputStream("C:\\JavaProg\\cdac\\
IOApplication\\IOPrograms\\product.dat",true);
DataOutputStream dout=new DataOutputStream(fout);
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no of product u want to store");

int n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("Enter "+(i+1)+" Product Details...Pr
odId,ProName,ProDesc,Cost");
int proId=sc.nextInt();
String proNmae=sc.next();
String proDesc=sc.next();
double cost=sc.nextDouble();
dout.writeInt(proId);
dout.writeUTF(proNmae);
dout.writeUTF(proDesc);
dout.writeDouble(cost);
}
System.out.println("Data stored Successfully...");
dout.close();
fout.close();
}
}
package cdac.IOProgDemo;
import
import
import
import
import

java.io.DataInputStream;
java.io.EOFException;
java.io.FileInputStream;
java.io.IOException;
java.util.Scanner;

public class ReadDataFromBin {


public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
FileInputStream fin=new FileInputStream("C:\\JavaProg\\cdac\\IOA
pplication\\IOPrograms\\product1.dat");
DataInputStream din=new DataInputStream(fin);
System.out.println("Enter Product id u want to search");
int pid=sc.nextInt();
int proId=0;;
String proName="",proDesc="";
double cost=0.0;
while(true)
{
try
{
proId=din.readInt();
proName=din.readUTF();
proDesc=din.readUTF();
cost=din.readDouble();
if(pid==proId)
{
System.out.println("Product Details Are... "+pro
Id+" "+proName+" "+proDesc+" "+cost);
}

}
catch(EOFException e)
{
break;
}
}
}
}
________________________________________________________________________________
______________________________
5. Write a class Machine fields = name, type, make, cost, requirements,purpose cost field be transient
Write a class that will serialize a few machine objects in a file
Write another class that will deserialize and print the machine details.
package cdac.IOProgDemo;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class MachineSerialize
{
public static void main(String[] args) throws IOException
{
Machine m1=new Machine("AC", "complete", "Tata", "For Cool Air",
4500);
Machine m2=new Machine("Washing M/c", "Semi-Detatch", "Samsung",
"For wash Colths", 4500);
Machine m3=new Machine("Freez", "5lt", "LPG", "For cooling foods
", 4500);
FileOutputStream fout=new FileOutputStream("C:\\JavaProg\\cdac\\
IOApplication\\IOPrograms\\machine.txt",true);
ObjectOutputStream os=new ObjectOutputStream(fout);
os.writeObject(m1);
os.writeObject(m2);
os.writeObject(m3);
os.close();
fout.close();
}
}
package cdac.IOProgDemo;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class MachineDeser {
public static void main(String[] args) throws IOException, ClassNotFound

Exception
{
FileInputStream fout=new FileInputStream("C:\\JavaProg\\cdac\\IO
Application\\IOPrograms\\machine.txt");
ObjectInputStream os=new ObjectInputStream(fout);
while(true)
{
try
{
System.out.println(" ");
System.out.print("Machine Details:-...");
Object obj=os.readObject();
System.out.println(obj);
}
catch(Exception e)
{
System.out.println("end of file..");
break;
}
}
}
}

________________________________________________________________________________
________________________________
6. Write a program that shows a menu to the user
1. show dir content
2. delete a file
3. show permissions of a file
4. set file as readonly
5. create a new file
6. show the last modified date
package cdac.IOProgDemo;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileDemo
{
public static void main(String[] args) throws IOException
{
File fl = new File("C:\\JavaProg\\cdac\\IOApplication\\IOProgram
s\\Temp.txt");
File f2 = new File("C:\\JavaProg\\cdac\\IOApplication\\IOProgram
s\\Temp1.txt");
File f3 = new File("C:\\JavaProg\\cdac\\IOApplication\\IOProgram
s\\Temp");
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("1.Create File\n"+"2.Delete file\n"+"

3.Create Directory\n"+"4.Show Dir content\n"+"5.Show Permission of file\n"+"6.Se


t file ReadOnly\n"+"7.Show Last modified\n"+"8.Exit");
System.out.println("Enter your choice..");
int ch=sc.nextInt();
switch(ch)
{
case 1:
if(f2.createNewFile())
{System.out.println("File Created..");
System.out.println(f2.getName());}
else
System.out.println("File is not
created");
break;
case 2:
if(fl.delete())
System.out.println("File Deleted
..");
else
System.out.println("File is not
deleted");
break;
case 3:
if(f3.mkdir())
System.out.println("Directroy cr
eated..");
else
System.out.println("Dir is not C
readted");
break;
case 4:
if(f3.isDirectory())
{
String[] str=f3.list();
for(int i=0;i<str.length;i++)
System.out.println(str[i]);
}
else
{
System.out.println("Dir is not C
readted");
}
break;
case 5:
System.out.println("File Permission are:
-"+fl.canExecute()+" "+fl.canRead()+" "+fl.canWrite());
break;
case 6:
System.out.println("file set as read onl
y.."+fl.setReadOnly());
System.out.println(fl.canExecute()+" "+f
l.canRead()+" "+fl.canWrite());
break;
case 7:
System.out.println("lastmodified..."+f2.
lastModified());
case 8: break;
default:System.out.println("invalid choice..");
break;

}
}
}
}
________________________________________________________________________________
___
8-Dec-16
________________________________________________________________________________
___
1. Write a program to accept a number from user and pass it two methods
fact1 = compute factorial by non recursive method
, fact2 = compute factorial by recursion
______________________________________________________________________________
package cdac.Collection;
import java.util.Scanner;
public class FactorialDemo
{
public static void main(String[] args)
{
System.out.println("Enter the Number to find its factorial");
Scanner sc=new Scanner(System.in);
int no=sc.nextInt();
int ch;
System.out.println("1.Non-recursive Factorial\n2.Recursive Facto
rial");
ch=sc.nextInt();
FactorialDemo f1=new FactorialDemo();
if(ch==1)
{
int res=f1.fact(no);
System.out.println(no+" Factorial is "+res);
}
else if(ch==2)
{
int res=f1.Rfact(no);
System.out.println(no+" Factorial is "+res);
}
else
{
System.out.println("Invalid Choice");
}
}
int f=1;
int Rfact(int no)//by recursion
{
if(no!=0)
{
f *= no;
no--;
Rfact(no);
}
return f;
}

int fact(int no)//by non recursive


{
while(no>0)
{
f *= no;
no--;
}
return f;
}
}

______________________________________________________________________________
2. Write a program to create an ArrayList of Product class
accept the values from user
add objects , Iterate over the list and print the toString
of products.
package cdac.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class ProductArrayList
{
public static void main(String[] args)
{
ArrayList<Product> ap=new ArrayList<Product>();
Scanner sc = new Scanner(System.in);
System.out.println("enter number of Product do u want to store")
;
int len = sc.nextInt();
System.out.println("enter "+ len+" product details u want to sto
re");
for(int i =0;i<len;i++)
{
System.out.println("Enter product details proId,proName,
proDesc,cost");
int proId=sc.nextInt();
String proName=sc.next();
String proDesc=sc.next();
int cost=sc.nextInt();
System.out.println("Enter Address area,city,pin");
String area=sc.next();
String city=sc.next();
int pinCode=sc.nextInt();
Address a=new Address(area,city,pinCode);
ap.add(new Product(proId,proName,proDesc,cost,a));
}
Iterator<Product> pit=ap.iterator();
while(pit.hasNext())
{
System.out.println(pit.next());
}

}
}
______________________________________________________________________________
3. create a class Account - fields aid, balance, name, type
constr, getters. setters, toString
Write a user === create a TreeSet of accounts
that will sort the account objects w.r.t accountName
(Comparable interface )
------- @Override
public String toString() {
return "Account Ditails are:- "+accountId+" "+accName+" "+accTyp
e+" "+balance ;
}
@Override
public int compareTo(AccountSort arg0)
{
int in = this.accName.codePointAt(0);
int in1 = arg0.accName.codePointAt(0);
if (in<in1)
{
return -1;
}
else if(in>in1)
{
return 1;
}
else
{
return 0;
}
}
package cdac.Collection;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class AccUser
{
public static void main(String[] args)
{
TreeSet<AccountSort> at=new TreeSet<AccountSort>();
Scanner sc = new Scanner(System.in);
System.out.println("enter number of Account details do u want to
store");
int len = sc.nextInt();
System.out.println("enter "+ len+" Account details u want to sto
re");
for(int i =0;i<len;i++)
{
System.out.println("Enter Account details accountId, bal
ance, accName, accType");
int accountId=sc.nextInt();
String accName=sc.next();

String accType=sc.next();
double balance=sc.nextDouble();
at.add(new AccountSort(accountId, balance, accName, accT
ype));
}
Iterator<AccountSort> ait=at.iterator();
while(ait.hasNext())
{
System.out.println(ait.next());
}
}
}
______________________________________________________________________________
4. Write a java application-------show the menu
1. max
2. min
3. reverse
4. sort - asc, desc
5. shuffle
Accept a list of floating point numbers from the user
add them to the ArrayList
and depending on the choice show the result
(Collections class )
package cdac.Collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<Float> al = new ArrayList<Float>();
Scanner sc = new Scanner(System.in);
int ch;
System.out.println("enter number of element do u want to store")
;
int len = sc.nextInt();
System.out.println("enter "+ len+" floting point elements u want
to store");
for(int i =0;i<len;i++)
{
float no=sc.nextFloat();
al.add(no);
}
for(int i = 0;i<al.size();i++)
{
System.out.println(al.get(i));
}
do
{

System.out.println("1.Sort\n"+"2.Maximum\n"+"3.Minimum\n
"+"4.Reverse\n"+"5.Shuffle\n"+"6.Exit\n"+"Enter u r choice");
ch = sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter 1:Acse
nding Order\n2:Descending Order");
int no=sc.nextInt();
if(no==1)
{
Collections.sort(al);
System.out.println("sort
ed element in Acsending Order");
for(int i = 0;i<al.size(
);i++)
{
System.out.print
ln(al.get(i));
}
}
if(no==2)
{
Collections.sort(al);
System.out.println("sort
ed element in Descending Order");
for(int i = al.size()-1;
i>=0;i--)
{
System.out.print
ln(al.get(i));
}
}
else
{
System.out.println("Inva
lid choice ");
}
break;
case 2:
System.out.println("maximum elem
ent in array"+Collections.max(al));
break;
case 3:
System.out.println("minimum elem
ent in array"+Collections.min(al));
break;
case 4:
Collections.reverse(al);
System.out.println("reverse elem
ent is");
for(int i = 0;i<al.size();i++)
{
System.out.println(al.ge
t(i));
}
break;
case 5:
System.out.println("shuffled ele
ments are");

Collections.shuffle(al);
for(int i = 0;i<al.size();i++)
{
System.out.println(al.ge
t(i));
}
break;
case 6: break;
}
}while(ch!=6);
}
}
________________________________________________________________________________
___________________
5. Find the purpose of LinkedHashSet. Arrays class.
______________________________________________________________________________
6. Write a java application that will maintain a hashmap of username and passwor
d. Ask the user to enter the uname and password.
check if the uname and password match using HashMap.
if they match = grant access
otherwise = deny access
Modify such that it will display whether uname is incorrect or password is incor
rect.
______________________________________________________________________________
package cdac.Collection;
import java.util.HashMap;
import java.util.Scanner;
public class UserAuthentication {
public static void main(String[] args)
{
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("chetan","123chetan");
hm.put("jagu","jagu120");
Scanner sc = new Scanner(System.in);
System.out.println("enter User Name");
String unm = sc.next();
System.out.println("enter Password");
String pnm = sc.next();
if(hm.containsKey(unm)&&hm.containsValue(pnm))
{
if(hm.containsKey(unm))
{
if(hm.containsValue(pnm))
{
System.out.println("Welcome....Granted
Access");
}
else

System.out.println("Incorrect Pa
ssword....");
}
else
{
System.out.println("Incorrect UserName.... ");
}
}
else
{
System.out.println("Incorrect Username And password...\n
Access Deny..Please try again Later");
}
}
}
______________________________________________________________________________
7-Dec-16
______________________________________________________________________________
1. Modify the class Employee
override the setDOB method of Person in Employee class
check if DOB is at least 18 years back
if not throw TooYoungEmployeeException
Write a user class that has main
it will test the setDob method
2. Two types of exceptions --- Checked and Unchecked exceptions
_________________________________________________________________________
1) Checked: are the exceptions that are checked at compile time. If some code wi
thin a method throws a checked exception, then the method must either handle the
exception or it must specify the exception using throws keyword.
2) Unchecked are the exceptions that are not checked at compiled time. In C++, a
ll exceptions are unchecked, so it is not forced by the compiler to either handl
e or specify the exception. It is up to the programmers to be civilized, and spe
cify or catch the exceptions.
_________________________________________________________________________
3. Write a
1.
2.
3.

menu driven program as follows --Show today's date


accept a date and show the weekday
show next day = accept the
number of day or month or year after which
user wants to see the date
4. Accept a date from user and tell whether it is a
second saturday
5. quit
_________________________________________________________________________
4. Write a program that will accept command line argument as a
# separated list of numbers.
Ask the user to enter a number
check if the number is in the list.
java SomeProg 12#45#67#100

enter a num 56 ?
Output:package cdac.Tokenizer;
import java.util.Scanner;
import java.util.StringTokenizer;
public class StringTokenizerDemo
{
public static void main(String[] args)
{
System.out.println(args[0]);
String[] token = args[0].split("#");
for(String s : token)
{
System.out.println(s);
}
System.out.println("enter a number");
Scanner sc = new Scanner(System.in);
String n = sc.next();
int cnt=0;
for(int i=0;i<token.length;i++)
{
if(token[i].contains(n))
{
cnt++;
}
}
if(cnt>0)
{
System.out.println("Entered number is Present");
}
else
{
System.out.println("Entered number is not Present");
}
}
}
__________________________________________________________________________
5. Write a program that will accept a number from user
then generate the next random number
if the 2 numbers are same the user wins.
package cdac.Tokenizer;
import java.util.*;
public class RandomDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.println();
int n = sc.nextInt();
Random r = new Random();
int[] arr = new int[10];
for(int x=0;x<10;x++)
{
arr[x] = r.nextInt(n);
}
for(int i = 0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
int cnt=0;
for(int i = 0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
cnt++;
}
}
}
if(cnt>=2)
{
System.out.println("U r Winner");
}
else
{
System.out.println("U R Looser");
}
}
}
__________________________________________________________________________
6-Dec-16
_____________________________________________________________________________
1. Override the toString method in the classes written yesterday
Person, MyDate, Student, PGStudent, Employee
In the array program simply modify the last for loop such that
instead of calling display you just
sysout(arr[i]);
2. Override equals mehtod in the classes written yesterday
Person, MyDate, Student, PGStudent, Employee
Write a User that will check equals.
________________________________________________________________________________
_____
package cdac.overridingDemo;
public class MyDate

{
private int day,mon,year;
public MyDate()
{
day=1;
mon=1;
year=1970;
}
public MyDate(int dd,int mm,int yy)
{
day=dd;
mon=mm;
year=yy;
}
public void Show()
{
System.out.println(day+"-"+mon+"-"+year);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return day+"-"+mon+"-"+year;
}
@Override
public boolean equals(Object arg0) {
if(arg0 instanceof MyDate)
{
MyDate d=(MyDate)arg0;
if(this.day==d.day&&this.mon==d.mon&&this.year==d.year)
return true;
else
return false;
}
else
return false;
}
}
package cdac.overridingDemo;
public class PersonOverload {
String name;
MyDate dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PersonOverload()
{
System.out.println("Person Default..");
}
public PersonOverload(String name, MyDate dob) {
this.name = name;
this.dob = dob;
}
public void Display()
{
System.out.print("NameL:-"+name+" Date of Birth is:-");

dob.Show();
}
@Override
public String toString()
{
return "NameL:-"+name+" Date of Birth is:-"+dob;
}
@Override
public boolean equals(Object arg0) {
if(arg0 instanceof PersonOverload)
{
PersonOverload d=(PersonOverload)arg0;
if(this.name.equals(d.name)&&this.dob.equals(d.d
ob))
return true;
else
return false;
}
else
return false;
}
}
class Student extends PersonOverload
{
private int rollNo;
private String[] sub;
public Student() {
super();
System.out.println("Student Default..");
}
public Student(int rollNo,String[] sub,String name, MyDate dob)
{
super(name, dob);
this.rollNo=rollNo;
this.sub=sub;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String[] getSub() {
return sub;
}
public void setSub(String[] sub) {
this.sub = sub;
}
public void sDisplay()
{
super.Display();
System.out.println("Student Rno:- "+rollNo);
System.out.print("Sub is:-");
for(int i=0;i<sub.length;i++)
{
System.out.println(sub[i]);
}

}
@Override
public String toString()
{
return "NameL:-"+name+" Student Rno:- "+rollNo+" Subject is..."+
sub[0]+" "+sub[1]+" "+sub[2]+" Date of Birth is:-"+dob;
}
@Override
public boolean equals(Object arg0) {
if(arg0 instanceof Student)
{
Student d=(Student)arg0;
if(this.name.equals(d.name)&&this.dob.equals(d.d
ob)&&this.rollNo==d.rollNo&&this.sub.equals(d.sub))
return true;
else
return false;
}
else
return false;
}
}
class Employee extends PersonOverload
{
private int eid;
private double salary;
private String dept;
public Employee()
{
super();
System.out.println("Employee Default..");
}
public Employee(int eid, double salary, String dept,String name,
MyDate dob) {
super(name, dob);
this.eid = eid;
this.salary = salary;
this.dept = dept;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDept() {

return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public void eDisplay()
{
super.Display();
System.out.println("Employee Id:- "+eid+" Salary:-"+sala
ry+" Dept:-"+dept);
}
@Override
public String toString()
{
return "NameL:-"+name+"Student Rno:- "+"Employee Id:- "+eid+" Sa
lary:-"+salary+" Dept:-"+dept+" Date of Birth is:-"+dob+"";
}
@Override
public boolean equals(Object arg0) {
if(arg0 instanceof Employee)
{
Employee d=(Employee)arg0;
if(this.name.equals(d.name)&&this.dob.equals(d.d
ob)&&this.eid==d.eid&&this.salary==d.salary&&this.dept.equals(d.dept))
return true;
else
return false;
}
else
return false;
}
}
class PgStudent extends Student
{
private double stiped;
public PgStudent() {
super();
System.out.println("PgStudent Default..");
}
public PgStudent(double stiped,int rollNo,String[] sub,String na
me, MyDate dob) {
super(rollNo,sub,name,dob);
this.stiped = stiped;
}
public double getStiped() {
return stiped;
}
public void setStiped(double stiped)
{
this.stiped = stiped;
}
public void pgDisplay()
{

super.sDisplay();
System.out.println("Stiped:- "+stiped);
}
@Override
public String toString()
{
return "NameL:-"+name+" Stiped:- "+stiped+" Date of Birth is:-"+
dob+"";
}
@Override
public boolean equals(Object arg0) {
if(arg0 instanceof PgStudent)
{
PgStudent d=(PgStudent)arg0;
if(this.name.equals(d.name)&&this.dob.equals(d.d
ob)&&this.stiped==d.stiped)
return true;
else
return false;
}
else
return false;
}
}

package cdac.overridingDemo;
public class UserEquels
{
public static void main(String[] args)
{
MyDate d=new MyDate(12,10,1992);
MyDate d1=new MyDate(20,8,1994);
MyDate d2=new MyDate(12,10,1992);
boolean b=d.equals(d2);
System.out.println("Date is same.."+b);
String[] str=new String[3];
str[0]=new String("java");
str[1]=new String("Ds");
str[2]=new String(".Net");
System.out.println("Student Details..");
Student s2=new Student(12,str,"chetan",d);
Student s3=new Student(12,str,"chetan",d);
System.out.println(s2);
boolean b1=s2.equals(s3);
System.out.println("Students are same...."+b1);
System.out.println("Employee Details..");
Employee e1=new Employee(101,45000,"Development","Jagu",d1);
Employee e2=new Employee(101,45000,"Development","Jagu",d1);
System.out.println(e1);
boolean b2=e1.equals(e2);
System.out.println("Employee are same...."+b2);
System.out.println("PGStudent Details..");
String[] str1=new String[2];

str1[0]=new String("CDAC");
str1[1]=new String("MBA");
PgStudent pg=new PgStudent(3200,12,str1,"chetan",d);
PgStudent pg1=new PgStudent(3200,12,str1,"somu",d);
System.out.println(pg);
boolean b3=pg.equals(pg1);
System.out.println("PGStudents are equle..."+b3);
}
}
________________________________________________________________________________
_______________________________________________
3. Search the java.lang.Object class to find final methods.
***public final Class<?> getClass()
Returns the runtime class of this Object. The returned Class object is the objec
t that is locked by static synchronized methods of the represented class.
***public final void notify()
Wakes up a single thread that is waiting on this object's monitor.
If any threads are waiting on this object, one of them is chosen to be awakened
. The choice is arbitrary and occurs at the discretion of the implementation. A
thread waits on an object's monitor by calling one of the wait methods.
***public final void notifyAll()
Wakes up all threads that are waiting on this object's monitor. A thread waits o
n an object's monitor by calling one of the wait methods.
***public final void wait(long timeout)
throws InterruptedException
Causes the current thread to wait until either another thread invokes the notify
() method or the notifyAll() method for this object, or a specified amount of ti
me has elapsed.
***public final void wait(long timeout,int nanos)
throws InterruptedException
Causes the current thread to wait until another thread invokes the notify() meth
od or the notifyAll() method for this object, or some other thread interrupts th
e current thread, or a certain amount of real time has elapsed.
public final void wait()
throws InterruptedException
Causes the current thread to wait until another thread invokes the notify() meth
od or the notifyAll() method for this object. In other words, this method behave
s exactly as if it simply performs the call wait(0).
________________________________________________________________________________
_________________________
4. Write an interface Playable having a method play()
Write classes that have this feature
CD , Toy, MusicalInstrument
Write a user of Playable hierarchy

create an array of Playables


populate the array
Play everything mentioned in the array .
________________________________________________________________________________
package Interface.PlayDemo;
public interface Playable {
public String play();
}
package Interface.PlayDemo;
public class Guitar implements Playable
{
String name,type;
int cost;
public Guitar(String name, String type, int cost) {
this.name = name;
this.type = type;
this.cost = cost;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setType(String type)
{
this.type = type;
}
public String getType()
{
return type;
}
public void setCost(int cost)
{
this.cost = cost;
}
public int getCost()
{
return cost;
}
@Override
public String play()
{
return name +" "+type+" "+cost;
}

}
package Interface.PlayDemo;
public class Movie implements Playable
{
String name,type;
int cost;
public Movie(String
this.name =
this.type =
this.cost =
}

name, String type, int cost) {


name;
type;
cost;

public void setName(String name)


{
this.name = name;
}
public String getName()
{
return name;
}
public void setType(String type)
{
this.type = type;
}
public String getType()
{
return type;
}
public void setCost(int cost)
{
this.cost = cost;
}
public int getCost()
{
return cost;
}
@Override
public String play()
{
return name +" "+type+" "+cost;
}
}
package Interface.PlayDemo;
public class User
{
public static void main(String[] args)
{
Playable[] p = new Playable[4];

p[0]
p[1]
p[2]
p[3]

=
=
=
=

new
new
new
new

Guitar("Electified","Electric",25000);
Guitar("Jordan","Normal",20000);
Movie("RHTDM", "Bollywood", 10000);
Movie("Ek-Villain", "Bollywood", 10000);

for(int i=0;i<p.length;i++)
{
System.out.println("You Are Playing..."+p[i].play());
}
}
}

_____________________________________________________________________________
5-Dec-16
_____________________________________________________________________________
1. Create a hierarchy as follows
Person
Student isa Person
Employee isa Person
PGStudent isa Student
Person = fields = String name, MyDate dob
Student = fields = rollNo, array of subjects
Employee = fields = eid, salary, dept
PGStudent = fields = stipend
For each class write 2 constr, setters and getters and display
Write the user of hierarchy main
create object of each type call methods
observe which constructors are called.
____________________________________________________________________________
package cdac.assignment;
public class Person
{
String name;
MyDate dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person()
{
System.out.println("Person Default..");
}
public Person(String name, MyDate dob) {
this.name = name;
this.dob = dob;
}
public void Display()
{
System.out.print("NameL:-"+name+" Date of Birth is:-");
dob.Show();

}
}
class Student extends Person
{
private int rollNo;
private String[] sub;
public Student() {
super();
System.out.println("Student Default..");
}
public Student(int rollNo,String[] sub,String name, MyDate dob) {
super(name, dob);
this.rollNo=rollNo;
this.sub=sub;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String[] getSub() {
return sub;
}
public void setSub(String[] sub) {
this.sub = sub;
}
public void sDisplay()
{
super.Display();
System.out.println("Student Rno:- "+rollNo);
System.out.print("Sub is:-");
for(int i=0;i<sub.length;i++)
{
System.out.println(sub[i]);
}
}
}
class Employee extends Person
{
private int eid;
private double salary;
private String dept;
public Employee()
{
super();
System.out.println("Employee Default..");
}
public Employee(int eid, double salary, String dept,String name, MyDate
dob) {
super(name, dob);
this.eid = eid;
this.salary = salary;
this.dept = dept;

}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public void eDisplay()
{
super.Display();
System.out.println("Employee Id:- "+eid+" Salary:-"+salary+" Dep
t:-"+dept);
}
}
class PgStudent extends Student
{
private double stiped;
public PgStudent() {
super();
System.out.println("PgStudent Default..");
}
public PgStudent(double stiped,int rollNo,String[] sub,String name, MyDa
te dob) {
super(rollNo,sub,name,dob);
this.stiped = stiped;
}
public double getStiped() {
return stiped;
}
public void setStiped(double stiped)
{
this.stiped = stiped;
}
public void pgDisplay()
{
super.sDisplay();

System.out.println("Stiped:- "+stiped);
}
public void input()
{
}
}
package cdac.assignment;
public class PerUser
{
public static void main(String[] args)
{
MyDate d=new MyDate(12,10,1992);
MyDate d1=new MyDate(20,8,1994);
String[] str=new String[3];
str[0]=new String("java");
str[1]=new String("Ds");
str[2]=new String(".Net");
System.out.println("Student Details..");
Student s2=new Student(12,str,"chetan",d);
s2.sDisplay();
System.out.println("Employee Details..");
Employee e1=new Employee(101,45000,"Development","Jagu",d1);
e1.eDisplay();
System.out.println("PGStudent Details..");
String[] str1=new String[2];
str1[0]=new String("CDAC");
str1[1]=new String("MBA");
PgStudent pg=new PgStudent(3200,12,str1,"chetan",d);
pg.pgDisplay();
}
}
_____________________________________________________________________________
2. Write another user of the hierarchy called as U2
main
create an array of Person
ask the size to enduser
ask the enduser which person should be added
a. Person
b. Student
c. Employee
d. PGStudent
accept the details and add the student to array
show the list again till the user says quit
In the end display the details of each Person
in the array.
_____________________________________________________________________________
package cdac.assignment;
public class PersonArray

{
String name;
MyDate dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PersonArray()
{
System.out.println("Person Default..");
}
public PersonArray(String name, MyDate dob) {
this.name = name;
this.dob = dob;
}
public void Display()
{
System.out.print("Name:-"+name+" Date of Birth is:-");
dob.Show();
}
}
class StudentArray extends PersonArray
{
private int rNo;
private String clgName;
public int getrNo()
{
return rNo;
}
public void setrNo(int rNo)
{
this.rNo = rNo;
}
public String getClgName()
{
return clgName;
}
public void setClgName(String clgName)
{
this.clgName = clgName;
}
public StudentArray()
{
}
public StudentArray(int rNo, String clgName,String nm,MyDate dob)
{
super(nm,dob);
this.rNo = rNo;
this.clgName = clgName;
}
public void Display()
{
super.Display();
System.out.println("Roll Number Is :"+rNo);
System.out.println("College Name Is :"+clgName);
}

}
class EmployeeA
{
private
private
private

extends PersonArray
int eid;
double salary;
String dept;

public EmployeeA()
{
super();
System.out.println("Employee Default..");
}
public EmployeeA(int eid, double salary, String dept,String name, MyDate
dob) {
super(name, dob);
this.eid = eid;
this.salary = salary;
this.dept = dept;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public void Display()
{
super.Display();
System.out.println("Employee Id:- "+eid+" Salary:-"+salary+" Dep
t:-"+dept);
}
}
class PgStudentA extends StudentArray
{
private double stiped;
public PgStudentA() {
super();
System.out.println("PgStudent Default..");
}

public PgStudentA(double stiped,int rollNo,String clg,String name, MyDat


e dob) {
super(rollNo,clg,name,dob);
this.stiped = stiped;
}
public double getStiped() {
return stiped;
}
public void setStiped(double stiped)
{
this.stiped = stiped;
}
public void pgDisplay()
{
super.Display();
System.out.println("Stiped:- "+stiped);
}
public void input()
{
}
}

package cdac.assignment;
import java.util.Scanner;
public class UserArray
{
public static void main(String[] args)
{
Scanner SC = new Scanner(System.in);
System.out.println("Enter length Of Array");
int n = SC.nextInt();
PersonArray[] p = new PersonArray[n];
int ch,i=0;
int d,m,y;
int l=p.length;
do
{
System.out.println("1.Student");
System.out.println("2.Employee");
System.out.println("3.PG-Student");
System.out.println("4.Exit");
System.out.println("Enter U R Choice");
ch = SC.nextInt();
if(i<l)
{
switch (ch)
{
case 1:
System.out.println("Enter Student Details");
System.out.println("enter Name");
String nm = SC.next();
System.out.println("enter College Name");

String cnm = SC.next();


System.out.println("Enter Roll Number");
int rno = SC.nextInt();
System.out.println("Enter DOB");
d=SC.nextInt(); m=SC.nextInt(); y=SC.nextInt();
MyDate d1=new MyDate(d,m,y);
p[i] = new StudentArray(rno,cnm,nm,d1);
((StudentArray)p[i]).Display();
i++;
break;
case 2:
System.out.println("Enter Employee Details");
System.out.println("enter EmpId");
int eid = SC.nextInt();
System.out.println("enter Name");
String enm = SC.next();
System.out.println("Enter DOB");
d=SC.nextInt();m=SC.nextInt();y=SC.nextInt();
MyDate ed1=new MyDate(d,m,y);
System.out.println("enter Dept");
String dt = SC.next();
System.out.println("enter Salary");
double sal = SC.nextDouble();
p[i] = new EmployeeA(eid,sal,dt,enm,ed1);
((EmployeeA)p[i]).Display();
i++;
break;
case 3:
System.out.println("Enter Student Details");
System.out.println("enter Name");
String snm = SC.next();
System.out.println("enter College Name");
String scnm = SC.next();
System.out.println("Enter Roll Number");
int srno = SC.nextInt();
System.out.println("Enter DOB");
d=SC.nextInt(); m=SC.nextInt(); y=SC.nextInt();
MyDate sd1=new MyDate(d,m,y);
System.out.println("Enter Stiped");
double stp = SC.nextDouble();
p[i] = new PgStudentA(stp,srno,scnm,snm,sd1);
((PgStudentA)p[i]).Display();
i++;
break;
case 4:break;
default:System.out.println("Invalid Choice...");
break;
}
}
else
{
System.out.println("Array out of Bound");
}
}while(ch!=4);
System.out.println("Person Details...");

for(int j=0;j<l;j++)
{
p[j].Display();
}
}
}
____________________________________________________________________________
3. Write a program to accept a string from the user and display whether the str
ing is a palindrome.
_______________________________________________________________________________
package cdac.assignment;
import java.util.Scanner;
public class Palindrom {
public static void main(String[] args)
{
Scanner SC = new Scanner(System.in);
System.out.println("Enter the string");
String str=SC.next();
System.out.println("String is "+str);
int n=str.length();
System.out.println("length of string is "+n);
int j=0;
char[] rev = new char[n];
for(int i=n-1;i>=0;i--)
{
rev[j] = str.charAt(i);
j++;
}
int flag=0;
for(int i=0;i<n;i++)
{
if(rev[i]==str.charAt(i))
{
flag=1;
}
else
{
flag=0;
}
}
if(flag==1)
System.out.println(str+" is a palindrom");
else
System.out.println(str+" is not a palindrom");
}
}
output:Enter the string
radar
String is radar

length of string is 5
radar is a palindrom.
________________________________________________________________________
4. Write a program that will ask the end user to enter numbers
put all numbers in an array and pass it to a static method
mySort(int[] arr , mode=asc/desc)
sort the array
print the sorted array in main
______________________________________________________________________________
package cdac.assignment;
public class ArraySort
{
public static int[] mySort(int[] arr,int mode)
{
if(mode==0)
{
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]>=arr[j])
{
int temp;
temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
else if(mode==1)
{
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]<=arr[j])
{
int temp;
temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
return arr;
}
}

package cdac.assignment;
import cdac.assignment.ArraySort;
import java.util.Scanner;
public class User
{
public static void main(String[] args)
{
Scanner SC = new Scanner(System.in);
System.out.println("Enter legnth of array");
int n = SC.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter the"+i+"element of array");
arr[i]=SC.nextInt();
}
System.out.println("Element of array ");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
System.out.println("Enter 0:Ascending & 1:Descending");
int m = SC.nextInt();
int[] a=new int[n];
a=ArraySort.mySort(arr,m);
System.out.println("Element of array");
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
output:Enter legnth of array
5
Enter the0element of array
45
Enter the1element of array
77
Enter the2element of array
12
Enter the3element of array
88
Enter the4element of array
33
Element of array
45
77
12
88
33
Enter 0:Ascending & 1:Descending
1
Sorted decending is array
88
77

45
33
12
________________________________________________________________________
5. Try out the different variations of A,B,C,D,E hierarchy done in class.
in group.
___________________________________________________________________________
package cdac.assignment;
public class A
{
public void a1()
{
System.out.println("In The A class Function a1");
}
public void Fa()
{
System.out.println("In The A class Function Fa");
}
}
class B extends A
{
public void a1()
{
System.out.println("In
}
public void Fb()
{
System.out.println("In
}
}
class C extends B
{
/*public void c1()
{
System.out.println("In
}*/
}
class D extends B
{
public void Fd()
{
System.out.println("In
}
}
class E extends C
{
public void a1()
{
System.out.println("In
}
}
output:package cdac.assignment;

The B class Function b1");

The A class Function Fb");

The C class Function c1");

The C class Function Fd");

The C class Function c1");

public class Variations


{
public static void main(String[] args)
{
A a=new A();
a.a1();
a.Fa();
//a.Fb();
//a.Fd();
B b=new B();
b.a1();
b.Fa();
b.Fb();
//b.Fd();
C c=new C();
c.a1();
c.Fa();
c.Fb();
//c.Fd();
D d=new D();
d.a1();
d.Fa();
d.Fb();
d.Fd();
E e=new E();
e.a1();
e.Fa();
e.Fb();
//e.Fd();
}
}
___________________________________________________________________________
3-Dec-16
1. Modify the Subject class and add an array of referencebooks (string array) as
a member , modify constructor, display and add getter setter. Modify the user.
_____________________________________________________________________________
package cdac.ArrayDemo;
public class SubjectArray
{
private String subName,subFaculty;
private String[] bk;
private int subMinMarks,subMaxMarks;
public SubjectArray()
{
}
public SubjectArray(String sN,String sF, int sMin, int sMax,String[] b)
{
subName=sN; subFaculty =sF;
subMinMarks=sMin; subMaxMarks=sMax;
bk=b;
}
public void setName(String nm)
{
this.subName=nm;

}
public void setFaculty(String fnm)
{
subFaculty=fnm;
}
public void setMinMaxMarks(int mnMark,int mxMark)
{
this.subMinMarks=mnMark;
this.subMaxMarks=mxMark;
}
public void display()
{
System.out.println("Subject Name is
:-"+this.subName);
System.out.println("Subject Faculty is :-"+this.subFaculty);
System.out.println("Subject MinMarks is :-"+this.subMinMarks);
System.out.println("Subject MaxMarks is :-"+this.subMaxMarks);
System.out.print("Subject Reference is:-");
for(int i=0;i<bk.length;i++)
{
System.out.println(bk[i]);
}
}
public static void main(String[] agrs)
{
String[] str=new String[3];
str[0]=new String("Pearson");
str[1]=new String("Black Book");
str[2]=new String("Brech");
String[] str1=new String[2];
str1[0]=new String("Test ur c Skills");
str1[1]=new String("Letus C");
SubjectArray sa = new SubjectArray("Java","Prachi",40,90,str);
sa.display();
SubjectArray sa1 = new SubjectArray("C","Vinayak Sir",40,100,str
1);
sa1.display();
}
}

output:=
c:\JavaProg>javac -d . SubjectArray.java
c:\JavaProg>java cdac.ArrayDemo.SubjectArray
Subject Name is
:-Java
Subject Faculty is
:-Prachi
Subject MinMarks is
:-40
Subject MaxMarks is
:-90
Subject Reference is:-Pearson
Black Book

Brech
Subject
Subject
Subject
Subject
Subject
Letus C

Name is
:-C
Faculty is
:-Vinayak Sir
MinMarks is
:-40
MaxMarks is
:-100
Reference is:-Test ur c Skills

______________________________________________________________________________
2. Write a class Address ---- fields area,city,state,country,pin
2 constr, display, getters and setters
Modify the Product class and add a member --addressOfMfg.
modify the constr, add getter setter, display method
Write a USer that creates Product objects and displays them.
____________________________________________________________________________
package cdac.Dealer;
public class Address
{
private String area,city,state,country;
private int pinCode;
public Address()
{
}
public Address(String area,String city,String state,String country,int p
in)
{
this.area= area;
this.city=city;
this.state=state;
this.country=country;
this.pinCode=pin;
}
public void display()
{
System.out.println("Address is :-");
System.out.println(" "+area+","+city+","+state+","+country+",pin
code:"+pinCode);
}
}
package cdac.productDemo;
import cdac.Dealer.Address;
import cdac.Dealer.MyDate;
public class Product
{
private int proId,cost;
private String proName,proDesc;
private Address add;
private MyDate date;
public Product(int proId,String proName,String proDesc,int cost,Address
a,MyDate d)
{
this.proId=proId;
this.proName=proName;
this.proDesc=proDesc;

this.cost=cost;
add=a;
date=d;
}
public void Display()
{
System.out.println("Product Info:- ");
System.out.println(proId+" "+proName+" "+proDesc+" "+cost);
System.out.print("Manufacturing Date is:- ");
date.Show();
add.display();
}
public static void main(String[] s)
{
Address A = new Address("kothrud","Pune","Maharashtra","India",4
11038);
MyDate d=new MyDate(12,10,1992);
Product p=new Product(101,"PenDrive","Sandisk",150,A,d);
p.Display();
}
}
/*
output:c:\JavaProg>javac -d . Product.java
c:\JavaProg>java cdac.productDemo.Product
Product Info:101 PenDrive Sandisk 150
Manufacturing Date is:- 12-10-1992
Address is :kothrud,Pune,Maharashtra,India,pincode:411038
*/
______________________________________________________________________________
3. Write a class study.parampass.Test
main
{
x has value 70, Y has value 100
sysout ( x,y ) (o/p 70 100)
swap
sysout ( x,y ) (o/p 100 70)
}
public static void swap(? , ? )
_______________________________________________________________________________
package cdac.Swapping;
public class SwapDemo
{
public static void main(String s[])
{

Demo x=new Demo();


Demo y=new Demo();
x.value = 10;
y.value = 20;
SwapDemo sd = new SwapDemo();
System.out.println("Before Swap.... x="+x.value +"y= " +y.value)
;
sd.swap(x,y);
System.out.println("After Swap.... x="+x.value +"y= " +y.value);
}
public void swap(Demo x,Demo y)
{
Demo temp=new Demo();
temp.value = x.value ;
x.value = y.value ;
y.value =temp.value ;
}
}
class Demo
{
int value;
}
/*
output:c:\JavaProg>javac -d . SwapDemo.java
c:\JavaProg>java cdac.Swapping.SwapDemo
Before Swap.... x=10y= 20
After Swap.... x=20y= 10
*/
___________________________________________________________________
1-Dec-16
___________________________________________________________________
1. Find the minimum and maximum number that can be represented using byte, short
, int , long. Try assigning out of range value to the respective variables and o
bserve the error.
public class DataDemo
{
public static void main(String[] s)
{
System.out.println(Byte.MIN_VALUE+" " +Byte.MAX_VALUE);
System.out.println(Short.MIN_VALUE+" " +Short.MAX_VALUE);
System.out.println(Integer.MIN_VALUE+" " +Integer.MAX_VALUE);
System.out.println(Long.MIN_VALUE+" " +Long.MAX_VALUE);
}
}
c:\JavaProg>javac DataDemo.java
c:\JavaProg>java DataDemo
-128 127
-32768 32767
-2147483648 2147483647
-9223372036854775808 9223372036854775807

2. Write a class Subject . Fields = name,faculty, maxmarks,minmarks


write private fields , default and parameterized constructor
write behavior = displaySubjectDetails
= setName() , setFacultyName,
=setMaxAndMinM
arks()
Write a User class - starting point main create 3 subjects
call all the methods for each subject.
public class Subject
{
private String subName,subFaculty;
private int subMinMarks,subMaxMarks;
public Subject()
{
}
public Subject(String sN,String sF, int sMin, int sMax)
{
subName=sN; subFaculty =sF;
subMinMarks=sMin; subMaxMarks=sMax;
}
public void setName(String nm)
{
this.subName=nm;
}
public void setFaculty(String fnm)
{
subFaculty=fnm;
}
public void setMinMaxMarks(int mnMark,int mxMark)
{
this.subMinMarks=mnMark;
this.subMaxMarks=mxMark;
}
public void display()
{
System.out.println("Subject
System.out.println("Subject
System.out.println("Subject
System.out.println("Subject
}
}//SUb end

Name is
Faculty is
MinMarks is
MaxMarks is

:-"+this.subName);
:-"+this.subFaculty);
:-"+this.subMinMarks);
:-"+this.subMaxMarks);

public class College


{
public static void main(String[] s)
{
Subject s1 = new Subject("Java","Prachi Mam",40,100);
s1.display();
Subject s2 = new Subject("OS","Silbretch",45,95);
s2.display();
Subject s3 = new Subject();
s3.setName("DotNet");
s3.setFaculty("Pankaj Sir");
s3.setMinMaxMarks(30,99);

s3.display();
}
}
output:c:\JavaProg>javac College.java
c:\JavaProg>java College
Subject Name is
:-Java
Subject Faculty is
:-Prachi Mam
Subject MinMarks is
:-40
Subject MaxMarks is
:-100
Subject Name is
:-OS
Subject Faculty is
:-Silbretch
Subject MinMarks is
:-45
Subject MaxMarks is
:-95
Subject Name is
:-DotNet
Subject Faculty is
:-Pankaj Sir
Subject MinMarks is
:-30
Subject MaxMarks is
:-99

3. Modify the Subject class and add it in a package


practice.pkg1
compile this class and keep the package in current folder
Modify the User and add it to
rent folder
compile and run it

practice.users.pkg2 keep the package in cur

package cdac.iet;
public class SubjectPkg
{
private String subName,subFaculty;
private int subMinMarks,subMaxMarks;
public SubjectPkg()
{
}
public SubjectPkg(String sN,String sF, int sMin, int sMax)
{
subName=sN; subFaculty =sF;
subMinMarks=sMin; subMaxMarks=sMax;
}
public void setName(String nm)
{
this.subName=nm;
}
public void setFaculty(String fnm)
{
subFaculty=fnm;
}
public void setMinMaxMarks(int mnMark,int mxMark)
{
this.subMinMarks=mnMark;
this.subMaxMarks=mxMark;
}
public void display()

{
System.out.println("Subject
System.out.println("Subject
System.out.println("Subject
System.out.println("Subject

Name is
Faculty is
MinMarks is
MaxMarks is

:-"+this.subName);
:-"+this.subFaculty);
:-"+this.subMinMarks);
:-"+this.subMaxMarks);

}
}//SUb end
package cdac.College;
import cdac.iet.SubjectPkg;
public class CollegePkg
{
public static void main(String[] s)
{
SubjectPkg s1 = new SubjectPkg("Java","Prachi Mam",40,100);
s1.display();
SubjectPkg s2 = new SubjectPkg("OS","Silbretch",45,95);
s2.display();
SubjectPkg s3 = new SubjectPkg();
s3.setName("DotNet");
s3.setFaculty("Pankaj Sir");
s3.setMinMaxMarks(30,99);
s3.display();
}
}
output:c:\JavaProg>javac -d . Subjectpkg.java
c:\JavaProg>javac -d . Collegepkg.java
c:\JavaProg>java cdac.College.CollegePkg
Subject Name is
:-Java
Subject Faculty is
:-Prachi Mam
Subject MinMarks is
:-40
Subject MaxMarks is
:-100
Subject Name is
:-OS
Subject Faculty is
:-Silbretch
Subject MinMarks is
:-45
Subject MaxMarks is
:-95
Subject Name is
:-DotNet
Subject Faculty is
:-Pankaj Sir
Subject MinMarks is
:-30
Subject MaxMarks is
:-99
4. Write another user --- test.classpath.User2 create this user having main
create a Subject object and call its methods.
Put the package in c:\different folder
From your current folder compile and run User2
(use classpath )
//package cdac.iet;
public class SubjectPkg
{
private String subName,subFaculty;
private int subMinMarks,subMaxMarks;
public SubjectPkg()
{

}
public SubjectPkg(String sN,String sF, int sMin, int sMax)
{
subName=sN; subFaculty =sF;
subMinMarks=sMin; subMaxMarks=sMax;
}
public void setName(String nm)
{
this.subName=nm;
}
public void setFaculty(String fnm)
{
subFaculty=fnm;
}
public void setMinMaxMarks(int mnMark,int mxMark)
{
this.subMinMarks=mnMark;
this.subMaxMarks=mxMark;
}
public void display()
{
System.out.println("Subject
System.out.println("Subject
System.out.println("Subject
System.out.println("Subject
}
}//SUb end

Name is
Faculty is
MinMarks is
MaxMarks is

:-"+this.subName);
:-"+this.subFaculty);
:-"+this.subMinMarks);
:-"+this.subMaxMarks);

//package cdac.College;
//import Link.cdac.iet.SubjectPkg;
public class CollegePkg
{
public static void main(String[] s)
{
SubjectPkg s1 = new SubjectPkg("Java","Prachi Mam",40,100);
s1.display();
SubjectPkg s2 = new SubjectPkg("OS","Silbretch",45,95);
s2.display();
SubjectPkg s3 = new SubjectPkg();
s3.setName("DotNet");
s3.setFaculty("Pankaj Sir");
s3.setMinMaxMarks(30,99);
s3.display();
}
}
output:c:\JavaProg>javac -d c:\F1 SubjectPkg.java
c:\JavaProg>javac -d c:\F2 CollegePkg.java
c:\JavaProg>java CollegePkg
Subject Name is
:-Java
Subject Faculty is
:-Prachi Mam
Subject MinMarks is
:-40
Subject MaxMarks is
:-100
Subject Name is
:-OS
Subject Faculty is
:-Silbretch

Subject
Subject
Subject
Subject
Subject
Subject

MinMarks is
MaxMarks is
Name is
Faculty is
MinMarks is
MaxMarks is

:-45
:-95
:-DotNet
:-Pankaj Sir
:-30
:-99

5. Modify the PlayWithString class written in classroom


display the string vertically one char on one line ( charAt() )
display the strings in lowercase ( toLowerCase )
display the length of both the strings ( length )
display the substring from 3rd to 2nd last charachter ( substring)
package cdac.stringDemo;
public class StringDemo
{
public static void main(String[] s)
{
String str = s[0];
int n=str.length();
System.out.println("length of string= "+n);
System.out.println("string in vertical manner ");
for(int i = 0;i<n;i++)
{
System.out.println(str.charAt(i));
}
System.out.println("string in Lowercase= "+str.toLowerCase());
System.out.println("Substring = "+str.substring(2,4));
}
}
output:c:\JavaProg>javac -d . StringDemo.java
c:\JavaProg>java cdac.stringDemo.StringDemo chetan
length of string= 6
string in vertical manner
c
h
e
t
a
n
string in Lowercase= chetan
Substring = et

______________________________________________________________________________
30-Nov-16
______________________________________________________________________________
1. Check the installation of JDK on your system.
2. observe the bin and lib folders of jdk and jre.
3. Write and execute the first java program done in class.
public class Demo

{
public static void main(String[] s)
{
System.out.println("hello");
}
}
C:\Users\iet18>cd c:\JavaProg
c:\JavaProg>javac Demo.java
c:\JavaProg>java Demo
hello
4. Write a Source file River.java add 3 non-public classes to it
a. Lake b. Stream c. Ocean add starting point main to each class compile and obs
erve the .class files run each class using jvm
public class River
{
public static void main(String[] s)
{
System.out.println("River class");
}
}
class Lake
{
public static void main(String[] s)
{
System.out.println("Lake class");
}
}
class Stream
{
public static void main(String[] s)
{
System.out.println("Stream Class");
}
}
class Sea
{
public static void main(String[] s)
{
System.out.println("Sea Class");
}
}

c:\JavaProg>javac River.java
c:\JavaProg>dir
Volume in drive C has no label.
Volume Serial Number is 2C3D-8403
Directory of c:\JavaProg
11/30/2016 06:59 PM
11/30/2016 06:59 PM

<DIR>
<DIR>

.
..

11/30/2016
11/30/2016
11/30/2016
11/30/2016
11/30/2016
11/30/2016
11/30/2016
11/30/2016

06:53 PM
407 Demo.class
06:52 PM
101 Demo.java
06:56 PM
720 JavaAssighnments.txt
06:59 PM
413 Lake.class
06:59 PM
415 River.class
06:59 PM
413 River.java
06:59 PM
411 Sea.class
06:59 PM
417 Stream.class
8 File(s)
3,297 bytes
2 Dir(s) 23,093,174,272 bytes free

c:\JavaProg>java River
River class
c:\JavaProg>java Lake
Lake class
c:\JavaProg>java Stream
Stream Class
c:\JavaProg>java Sea
Sea Class

5. Write a class PrimeDemo having starting point main it should print prime num
bers from 0 to 500
public class PrimeDemo
{
public static void main(String[] s)
{
int num = 500, count;
for (int i = 1; i <= num; i++)
{
count = 0;
for (int j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
count++;
break;
}
}
if (count == 0)
{
System.out.println(i+"\t");
}
}
}
}

You might also like