You are on page 1of 45

EXPERIMENT NO -1

AIM: Write HTML/Java scripts to display your CV in navigator, your


Institute website, Department Website and Tutorial website for specific
subject.

Code/Method:

<html>
<head>
<title>RESUME |</title>
</head>
<body>
<!-- BEGIN DIV FOR OVERALL BOX -->
<div id="resume">
<!-- THIS DIV CENTERS OUR HEADING -->
<h1>Harshit Pratap Rao</h1>
<h2>Flat Number-405, Tower-2 </h2>
<h2>Panchsheel Primrose Apartment, Ghaziabad-201013</h2>
<br />
<!-- END CENTERING DIV -->
</div>
<h2>Profile</h2>
<p> Seeking a challenging position in the area of teaching that
takes best out of me and helps me in enhancing my creativity
in the field of Education and for the growth of the Institution
and Students.
</p>
<br />
<h2>Educational Qualifications</h2>
<h3>B Tech, Dr.A.P.J. Abdul Kalam Technical University,Lucknow
</h3>
<h3>Research Project</h3>
<ul>
<li>Sussesfully submitted AKTU Funded Project. </li></ul>
<! -- THIS DIV CENTERS OUR LINKS --><div id="bottom"><p>
<a href="index.html">RESUME HOME</a> | <a href="#">SIMPLE RESUME</a> | <a
href="resume.html">COMPLEX RESUME</a> | <a href="code.html" target="_blank">SEE
HTML</a> | <a href="resume.css" target="_blank">SEE CSS</a></p></div><!-- END
CENTERING LINKS --><!-- END DIV FOR OVERALL BOX --></div></body>
</html>
Output:

Harshit Pratap Rao


B-Tech
Dr.
A.P.J.
Abdul
Kalam

Technical University, Lucknow


EXPERIMENT NO -2

AIM-Write an HTML program to design an entry form of student details


and send it to store at database server like SQL, Oracle or MS Access..

Code/Method:
<html>
<head>
<script type="text/javascript" src="validate.js" ></script>
</head>
<body bgcolor="aqua" bolder="5">
<form action="register.jsp" name="StudentRegistration" method=”post”>
<table cellpadding="2" width="50%" border="10" align="center"cellspacing="2">
<tr><td colspan=2><center><font
size=4><b> Student Registration Form
</b></font></center></td>
</tr><tr><td>Name</td><td>
<input type=text name=textnames id="textname" size="30"></td>
</tr>
<tr><td>Father Name</td><td><input type="text" name="fathername" id="fathername"
size="30"></td></tr>
<tr><td>Postal Address</td><td><input type="text" name="paddress" id="paddress"
size="30"></td></tr>
<tr><td>Personal Address</td><td><input type="text" name="personaladdress"
id="personaladdress" size="30"></td></tr>
<tr><td>Sex</td><td><input type="radio" name="sex" value="male" size="10">Male
<input type="radio" name="sex" value="Female" size="10">Female</td></tr>
<tr><td>City</td><td><select name="City"><option value="-1"
selected>select..</option><option value="New Delhi">NEW DELHI</option><option
value="Mumbai">MUMBAI</option><option value="Goa">GOA</option><option
value="Patna">PATNA</option></select></td></tr>
<tr><td>Course</td><td><select name="Course"><option value="-1"
selected>select..</option><option value="B.Tech">B.TECH</option><option
value="MCA">MCA</option>
<option value="MBA">MBA</option><option
value="BCA">BCA</option></select></td></tr><tr><td>District</td><td><select
name="District"><option value="-1" selected>select..</option><option
value="Nalanda">NALANDA</option><option value="UP">UP</option><option
value="Goa">GOA</option><option
value="Patna">PATNA</option></select></td></tr><tr><td>State</td><td><select
Name="State"><option value="-1" selected>select..</option><option value="New Delhi">NEW
DELHI</option><option value="Mumbai">MUMBAI</option><option
value="Goa">GOA</option><option
value="Bihar">BIHAR</option></select></td></tr><tr><td>PinCode</td><td><input type="text"
name="pincode" id="pincode" size="30"></td></tr><tr><td>EmailId</td><td><input type="text"
name="emailid" id="emailid" size="30"></td></tr><tr><td>DOB</td><td><input type="text"
name="dob" id="dob" size="30"></td></tr><tr><td>MobileNo</td><td><input type="text"
name="mobileno" id="mobileno" size="30"></td></tr>
<tr><td><input type="reset"></td><td colspan="2"><input type="submit"
value="Submit Form" /></td></tr></table></form><br><br><h1><a
href="MainPage.html">Back</a></h1></body></html>

Output:
EXPERIMENT NO -3

AIM-Write programs using Java script for Web Page to display browsers
information.

Code/Method:
<script>
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
document.writeln("<br/>navigator.language: "+navigator.language);
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
document.writeln("<br/>navigator.platform: "+navigator.platform);
document.writeln("<br/>navigator.onLine: "+navigator.onLine);
</script>

JavaScript Screen Object

<script>
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
document.writeln("<br/>screen.availWidth: "+screen.availWidth);
document.writeln("<br/>screen.availHeight: "+screen.availHeight);
document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
</script>

<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name); }
</script>

<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>

<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number); }
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>

<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);}
</script>
<form>

Male:<input type="radio" name="gender" value="male">


Female:<input type="radio" name="gender" value="female"> <input type="button" onclick="totalelements()"
value="Total Genders">
</form>

Output:

appCodeName Returns the code name of the browser


appName Returns the name of the browser
appVersion Returns the version information of the browser
cookieEnabled Determines whether cookies are enabled in the browser
geolocation Returns a Geo location object that can be used to locate
the
EXPERIMENT NO -4

AIM-Write a Java applet to display the Application Program screen i.e.


calculator and other.

Code/Method:
/*Java Program to Demonstrate a Basic Calculator using Applet*/
import java.awt.*;
import java.applet.*;
import
java.awt.event.*;
public class Calculator extends Applet implements ActionListener
{
TextField inp;
//Function to add features to the frame
public void init()
{
setBackground(Color.white);
setLayout(null);
int i;
inp = new TextField();
inp.setBounds(150,100,270,50);
his.add(inp);
Button button[] = new Button[10];
for(i=0;i<10;i++)
{
button[i] = new Button(String.valueOf(9-i));
button[i].setBounds(150+((i%3)*50),150+((i/3)*50),50,50);
this.add(button[i]);
button[i].addActionListener(this);
}
Button dec=new Button(".");
dec.setBounds(200,300,50,50);
this.add(dec);
dec.addActionListener(this);

Button clr=new Button("C");


clr.setBounds(250,300,50,50);
this.add(clr);
clr.addActionListener(this);

Button operator[] = new Button[5]; operator[0]=new Button("/");


operator[1]=new Button("*"); operator[2]=new Button("-");

operator[3]=new Button("+");
operator[4]=new Button("=");
for(i=0;i<4;i++)
{
operator[i].setBounds(300,150+(i*50),50,50);
this.add(operator[i]);
operator[i].addActionListener(this);
}
operator[4].setBounds(350,300,70,50);
this.add(operator[4]);
operator[4].addActionListener(this);
}
String num1="";
String op="";
String num2="";
//Function to calculate the expression
public void actionPerformed(ActionEvent e)
{
String button = e.getActionCommand();
char ch = button.charAt(0);
if(ch>='0' && ch<='9'|| ch=='.')
{
if (!op.equals(""))
num2 = num2 + button;
else
num1 = num1 + button;
inp.setText(num1+op+num2);
}
else if(ch=='C')
{
num1 = op = num2 = "";
inp.setText("");
}
else if (ch =='=')
{
if(!num1.equals("") && !num2.equals(""))
{
double temp;
double n1=Double.parseDouble(num1);
double n2=Double.parseDouble(num2);
if(n2==0 && op.equals("/"))
{
inp.setText(num1+op+num2+" = Zero Division Error");
num1 = op = num2 = "";
}
else
{
if (op.equals("+"))
temp = n1 + n2;
else if (op.equals("-"))
temp = n1 - n2;
else if (op.equals("/"))
temp = n1/n2;
else
temp = n1*n2;

inp.setText(num1+op+num2+" = "+temp); num1 = Double.toString(temp);


}
op = num2 = "";
}
enum1 = op = num2 = "";
linp.setText("");
s }
e }
{ else
{
if (op.equals("") ||
num2.equals("")) op = button;
else
{
if (op.equals("") ||
num2.equals("")) op = button;
else
{
double
double
n2=Double
op.equals
{
inp.
op
}
else
{
if

else if

else if

else

num1
button
num2
}
}
inp.setText
}
}
}
/*
<applet code = Calculator.class width=600
</applet>
*/

Output:

<applet code = Calculator.class width=600 height=600>


</applet>
*/
Appletviewer display
EXPERIMENT NO -5

AIM-Writing program in XML for creation of DTD, which specifies set of


rules. Create a style sheet in CSS/ XSL & display the document in internet
explorer.

Code :
employee
{
background-color:
pink; 4. }
firstname,lastname,e
mail 6. {
font-size:25px;
display:block;
color: blue;
margin-left: 50px;
}
create the DTD file.

employee.dtd

<!ELEMENT employee (firstname,lastname,email)>


<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT email (#PCDATA)>

employee.xml

<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="cssemployee.css"?>
<!DOCTYPE employee SYSTEM "employee.dtd">
<employee>
<firstname>vimal</firstname>
<lastname>jaiswal</lastname>
<email>vimal@javatpoint.com</email>
</employee>
EXPERIMENT NO -6

AIM-Program to illustrate JDBC connectivity. Program for maintaining


database by sending queries. Design and implement a simple servlet book
query with the help of JDBC & SQL. Create MS Access Database, Create
on ODBC link, Compile & execute JAVA JDVC Socket.

Code/Method:

import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object Connection con=DriverManager.getConnection(


"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object Statement stmt=con.createStatement();

while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object con.close();

}catch(Exception e){ System.out.println(e);}

}
}

Java Database Connectivity with MySQL

import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
19. }
20. }

Output:
Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.

Connection URL: The connection URL for the mysql database is


jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on
which mysql is running
EXPERIMENT NO -7

AIM-Install TOMCAT web server and APACHE. Access the above


developed static web pages for books web site, using these servers by
putting the web pages developed.

Procedure:
Set the JAVA_HOME Variable
You must set the JAVA_HOME environment variable to tell Tomcat where to find Java.
Failing to properly set this variable prevents Tomcat from handling JSP pages. This variable
should list the base JDK installation directory, not the bin subdirectory.
On Windows XP, you could also go to the Start menu, select Control Panel, chooseSystem,
click on the Advanced tab, press the Environment Variables button at the bottom, and enter
the JAVA_HOME variable and value directly as:
Name: JAVA_HOME
Value: C:\jdk
Set the CLASSPATH
Since servlets and JSP are not part of the Java 2 platform, standard edition, youhave to
identify the servlet classes to the compiler. The server already knows about theservlet classes,
but the compiler (i.e., javac ) you use for development probably doesn't.So, if you don't set
your CLASSPATH, attempts to compile servlets, tag libraries, or other classes that use the
servlet and JSP APIs will fail with error messages about unknownclasses.
Name: JAVA_HOME
Value: install_dir/common/lib/servlet-api.jar
Turn on Servlet Reloading
The next step is to tell Tomcat to check the modification dates of the class files of requested
servlets and reload ones that have changed since they were loaded into theserver's memory.
This slightly degrades performance in deployment situations, so isturned off by default.
However, if you fail to turn it on for your development server,you'll have to restart the server
every time you recompile a servlet that has already beenloaded into the server's memory.
To turn on servlet reloading, edit install_dir/conf/server.xml and add a
DefaultContextsubelement to the main Host element and supply true for the reloadable
attribute. For example, in Tomcat 5.0.27, search for this entry:
<Host name="localhost" debug="0" appBase="webapps" ...> and then insert the following
immediately below it: <DefaultContext reloadable="true"/>

Code/Method:
AIM: Install TOMCAT web server and APACHE. While installation, we assign port number
8080 to APACHE. Make sure that these ports are available i.e., no other process is
using this port.
DESCRIPTION: Set the JAVA_HOME Variable You must set the JAVA_HOME environment variable to
tell Tomcat where to find Java. Failing to properly set this variable prevents Tomcat
from handling JSP pages. This variable should list the base JDK installation directory,
not the bin subdirectory. On Windows XP, you could also go to the Start menu, select Control Panel,
choose System, click on the Advanced tab, press the Environment Variables button at the bottom,
and enter the JAVA_HOME variable and value directly as:
Name: JAVA_HOME Value: C:\jdk Set the CLASSPATH Since servlets and JSP are not part of the Java
2 platform, standard edition, you have to identify the servlet classes to the compiler. The server
already knows about the servlet classes, but the compiler (i.e., javac) you use for development
probably doesn't. So, if you don't set your CLASSPATH, attempts to compile servlets, tag libraries, or
other classes that use the servlet and JSP APIs will fail with error messages about unknown classes.

Name: JAVA_HOME Value: install_dir/common/lib/servlet-api.jar Turn on Servlet Reloading The


next step is to tell Tomcat to check the modification dates of the class files of requested servlets and
reload ones that have changed since they were loaded into the server's memory. This slightly
degrades performance in deployment situations, so is turned off by default. However, if you fail to
turn it on for your development server, you'll have to restart the server every time you recompile a
servlet that has already been loaded into the server's memory.

To turn on servlet reloading, edit install_dir/conf/server.xml and add a DefaultContext subelement


to the main Host element and supply true for the reloadable attribute.

For example, in Tomcat 5.0.27, search for this entry: and then insert the following immediately
below it: Be sure to make a backup copy of server.xml before making the above change.

Enable the Invoker Servlet The invoker servlet lets you run servlets without first making changes to
your Web application's deployment descriptor.

Instead, you just drop your servlet into WEB-INF/classes and use the URL
http://host/servlet/ServletName. The invoker servlet is extremely convenient when you are learning
and even when you are doing your initial development.

invoker org.apache.catalina.servlets.InvokerServlet........invoker /servlet/*

To enable the invoker servlet, uncomment the following servlet and servlet-mapping elements in
install_dir/conf/web.xml. Finally, remember to make a backup copy of the original version of this file
before you make the changes. invoker org.apache.catalina.servlets.InvokerServlet............invoker
/servlet/*
EXPERIMENT NO -8

AIM-Assume four users user1, user2, user3 and user4 having the
passwords pwd1, pwd2, pwd3 and pwd4 respectively. Write a servlet for
doing the following. Create a Cookie and add these four user id’s and
passwords to this Cookie. 2. Read the user id and passwords entered in the
Login form and authenticate with the values available in the cookies.

Code/Method:

PROGRAM:
cologin.html:
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>
<label> Password </label>
<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>

cologin1.html
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin1">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>
<label> Password </label>
<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>
</body>
</html>

Addcook.java:
import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Addcook extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
Cookie c1=new
Cookie("usr1","suni"); Cookie
p1=new Cookie("pwd1","ani");
Cookie c2=new
Cookie("usr2","abc"); Cookie
p2=new Cookie("pwd2","123");
Cookie c3=new
Cookie("usr3","def"); Cookie
p3=new Cookie("pwd3","456");
Cookie c4=new
Cookie("usr4","mno"); Cookie
p4=new Cookie("pwd4","789");
res.addCookie(c1);
res.addCookie(p1);
res.addCookie(c2);
res.addCookie(p2);
res.addCookie(c3);
res.addCookie(p3);
res.addCookie(c4);
res.addCookie(p4);
out.println("COOKIE ADDED");
}
}
Clogin.java:
import javax.servlet.* ; import
javax.servlet.http.*; import
java.io.*;
public class Clogin extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
user=req.getParameter("usr");
pas=req.getParameter("pwd");
Cookie[] c=req.getCookies();
for(int i=0;i<c.length;i++)
{
if((c[i].getName().equals("usr1")&&c[i+1].getName().equals("pwd1"))|| c[i].getName().equals("usr2") &&c[i+1].getName().equals("pwd2"))||
(c[i].getName().equals("usr3")&& c[i+1].getName().equals("pwd3"))||(c[i].getName().equals("usr4")&& c[i+1].getName().equals("pwd4") ))
{
if((user.equals(c[i].getValue()) && pas.equals(c[i+1].getValue())) )
{
//RequestDispatcher rd=req.getRequestDispatcher("/cart.html");
rd.forward(req,res);
}
else
{
out.println("YOU ARE NOT AUTHORISED USER ");
//res.sendRedirect("/cookdemo/cologin.html");
}
}
}
}
}

Web.xml:
<web-app>
<servlet>
<servlet-name>him</servlet-name><servlet-class>Clogin</servlet-class></servlet>
<servlet>
<servlet-name>him1</servlet-name>
<servlet-class>Addcook</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>him</servlet-name>
<url-pattern>/clogin</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>him1</servlet-name>
<url-pattern>/clogin1</url-pattern>
</servlet-mapping>
</web-app>
Output:
EXPERIMENT NO -9

AIM- Write a JSP which insert the details of the 3 or 4 users who register
with the web site by using registration form. Authenticate the user when he
submits the login form using the user name and password from the
database.

Code/Method:
Login.html:
<!--Home.html-->
<html><body>
<center><h1>XYZ Company Ltd.</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td valign="top" align="center"><br/>
<form action="auth.jsp"><table>
<tr>
<td colspan="2" align="center"><b>Login Page</b></td>
</tr>
<tr>
<td colspan="2" align="center"><b>&nbsp;</td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td>&nbsp;</td>

<td colspan="2" align="center"><input type="submit" value="LogIN"/></td>


<td>&nbsp;</td></tr><tr>

</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
Auth.jsp:
<%@page import="java.sql.*;"%>
<html>
<head>
<title>
This is simple data base example in JSP</title>
</title>
</head>
<body bgcolor="yellow">
<%!Stringuname,pwd;%>
<%
uname=request.getParameter("user");
pwd=request.getParameter("pwd");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.101.158:1521
:CCLAB","scott","tiger");
Statement st=con.createStatement();
ResultSetrs=st.executeQuery("select name,password from personal where name='"+uname+"'
and password='"+pwd+"'");
if(rs.next())
{
out.println("Authorized person");
}
else
{
out.println("UnAuthorized person");
}
con.close();}

catch(Exception e){out.println(""+e);}
%></body></html>
Output
EXPERIMENT NO -10

LOGIN PAGE: Login page must contain Login field, Password field, Submit
and reset buttons.

Code :

login.html
<html>
<head>
<title>Login page</title>
</head>
<body>
<center>
<font face="Arial Black" size="4"><u><b>LOGIN FORM</b></u></font>
<br><br>
<form name="f1" action="" method="post">
<table frame="box" cellspacing="10">
<tr>
<td>Login</td>
<td><input type="text" size="25"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" size="25"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="SUBMIT">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="RESET"></td>
</tr>
</table>
</form>
</center>
</body>
</html>

OUTPUT
EXPERIMENT NO -11

AIM- Write a java program that will concatenate 2 strings and return the
result. The result should be in lowercase. Note: If the concatenation creates
a double- char, then one of the characters need to be omitted.

Code/Method:
packagecom.cse;
public class JumpString {

public String conCat(String st1, String st2)


{
if (st1.length() != 0 && st2.length() != 0
&&st1.charAt(st1.length() - 1) == st2.charAt(0))
return st1 + st2.substring(1);
return st1 + st2;
}

public static void main (String[] args)


{
JumpString m= new JumpString();
String str1 = "food";
String str2 = "door";
System.out.println("The given strings are: "+str1+" and "+str2);
System.out.println("The string after concatination are: "+m.conCat(str1,str2));
}
}

Output:
The given strings are: food and door
EXPERIMENT NO -12

AIM- Given a string, return a new string made of 'n' copies of the first 2
chars of the original string where 'n' is the length of the string.

Code/Method:
packagecom.cse;
public class JumpString {
public static void main(String[] args) {
String str = "CSE";
int n = str.length();
String repeater = "";
if (n < 2)
repeater = str;
else
repeater = str.substring(0, 2);
String output = "";
for (int i = 0; i < n; i++) {
output += repeater;
}

System.out.println(output);
}
}

Output:
CSCSCS
EXPERIMENT NO -13

AIM- Write a Java program that will return the first half of the string, if
the length of the string is even. It should return null for odd length string.

Code:

Input a String.
Calculate length of String.
if(length%2==0) 4. {
5. System.out.println(str.substring(0, length-(length/2))); 6. }
else
System.out.println(str.substring((length/2), length));

Start
packagecom.cse;

public class JumpString {


public static void main(String[] args) {

String str="imseccse";
int length=str.length();
if(length%2==0)
{
System.out.println(str.substring(0, length-(length/2)));
}
else
System.out.println(str.substring((length/2), length));
}
}
Output:
imse
EXPERIMENT NO -14

AIM- Write a program that accepts a string and returns a new string
without the first and last character of the input string.

Code/Method:
packagecom.cse;
public class JumpString {
public static String removeFirstandLast(String str)
{

// Removing first and last character


// of a string using substring() method
str = str.substring(1, str.length() - 1);

// Return the modified


string returnstr;
}

public static void main(String args[])


{
// Given String str
String str =
"imsec";

// Print the modified


string System.out.print(
removeFirstandLast(str));
}
}

Output:

Mse
EXPERIMENT NO -15

AIM- Given 2 strings, a and b, return a string of the form short-long-short


with the shorter string on the outside and the longer string on the inside.
The strings will not be the same length, but they may be empty (length 0).

Code/Method:
packagecom.cse;
public class JumpString {
public static void main (String[] args)
{
String a = "hi";
String b = "hello";
if(a.length() >b.length())
System.out.println(b+a+b);
else
System.out.println(a+b+a);
}
}
Output:
hihellohi
EXPERIMENT NO -16

AIM-Given a string, if the first or last chars are 'x', return the string
without those 'x' chars,otherwise return the string unchanged.

Code/Method:
packagecom.cse;
public class MergeString {
public String excludeT(String stng)
{
if (stng.length() == 0)
returnstng;
if (stng.length() == 1)
{
if (stng.charAt(0) == 'x')
return "";
else
returnstng;
}
if (stng.charAt(0) == 'x')
stng = stng.substring(1,stng.length());
if (stng.charAt(stng.length()-1) == 'x')
stng = stng.substring(0,stng.length()-1);
returnstng;
}
public static void main (String[] args)
{
MergeString m= new MergeString();
String str1 = "xestcrickex";
System.out.println("The given strings is: "+str1);
System.out.println("The new string is: "+m.excludeT(str1));
}
}

Output :
The given strings is: xestcrickex
The new string is: estcricke
EXPERIMENT NO -17

AIM-Given two strings, a and b, print a new string which is made of the
following combination-first character of a, the first character of b, second
character of a, second character of b and so on. Any characters left, will go
to the end of the result.

Code/Method:
packagecom.cse;
public class MergeString {
// Function for alternatively merging two strings
public static String merge(String s1, String s2)
{
// To store the final string
StringBuilder result = new
StringBuilder();

// For every index in the strings


for (int i = 0; i < s1.length() || i < s2.length(); i++) {

// First choose the ith character of the


// first string if it
exists if (i < s1.length())
result.append(s1.charAt(i));

// Then choose the ith character of the


// second string if it
exists if (i < s2.length())
result.append(s2.charAt(i));
}

returnresult.toString();
}

// Driver code
public static void main(String[] args)
{
String s1 = "cse";
String s2 =
"ims";
System.out.println(merge(s1, s2));
}

}
Output:
cismes

You might also like