JAVA
Java is
an object-oriented programming
language with its own runtime environment.Java is an object-oriented programming language developed by Sun
Microsystems and released in 1995. Java was originally developed
by James Gosling at Sun Microsystems.Java programs are platform
independent which means they can be run on any operating system with any type
of processor as long as the Java interpreter is available on that system.
Java code that runs on one platform
does not need to be recompiled to run on another platform, it’s
called write once, run anywhere. Java Virtual Machine (JVM) executes Java code, but is
written in platform specific languages such as C,C++,etc. JVM is not written in Java and hence cannot be
platform independent and Java interpreter is actually a part of JVM.
Java Applications
Web Application – Java is used to create
server-side web applications. Currently, servlet, jsp,etc. technologies are
used.
Standalone Application – It is also known as desktop
application or window-based application. An application that we need to install
on every machine or server such as media player, antivirus etc. AWT and Swing
are used in java for creating standalone applications.
Enterprise Application – An application that is
distributed in nature, such as banking applications etc. It has the advantage
of high level security, load balancing and clustering. In java, EJB is used for
creating enterprise applications.
Mobile Application – Java is used to create application
softwares for mobile devices. Currently Java ME is used for creating
applications for small devices, and also Java is programming language for
Google Android application development.Features of Java
Object Oriented – In java everything is an
Object. Java can be easily expanded since it is based on the Object model.
Platform independent – C and C++ are platform
dependency languages hence the application programs written in one Operating
system cannot run in any other Operating system, but in platform independence
language like Java application programs written in one Operating system can
able to run on any Operating system.
Simple – Java is designed to be easy
to learn. If you understand the basic concept of OOP java would be easy to
master.
Secure – With Java’s secure
feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
Portable – being architectural neutral
and having no implementation dependent aspects of the specification makes Java
portable. Compiler and Java is written in ANSI C with a clean portability
boundary which is a POSIX subset.
Robust – Java makes an effort to
eliminate error prone situations by emphasizing mainly on compile time error
checking and runtime checking.
Multi-threaded – With Java’s multi-threaded
feature it is possible to write programs that can do many tasks simultaneously.
This design feature allows developers to construct smoothly running interactive
applications.
Interpreted – Java byte code is translated
on the fly to native machine instructions and is not stored anywhere. The
development process is more rapid and analytical since the linking is an
incremental and light weight process.
High Performance – With the use of Just-In-Time
compilers Java enables high performance.
Dynamic – Java is considered to be
more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry an extensive amount of run-time
information that can be used to verify and resolve accesses to objects on
run-time.
Different Editions of Java TechnologyJava SE – Java SE or Java Standard
Edition provides tools and API’s that you can use to create server
applications, desktop applications, and even applets. These programs developed
using Java SE can be run on almost every popular operating system, including
Linux, Macintosh, Solaris, and Windows.
JEE – Based on the foundation
framework of the standard edition, Java Enterprise Edition helps in web
application service, component model and enterprise class service oriented architecture
(SOA).
JME – Java Micro Edition or JME
for short is an accumulation of Java APIs that are used for the development of
software for devices like mobile phones, PDAs, TV set-top boxes, game
programming. The platform of micro edition generally consists of an easy user
interface, a robust security model and a wide variety of built-in networks for
running Java based application.
Java Editors
To write your java programs you will
need a text editor. There are even more sophisticated IDE available in the
market. But for now, you can consider one of the following:
Notepad – On Windows machine you can
use any simple text editor like Notepad (Recommended for this tutorial),
TextPad.
Netbeans – is a Java IDE that is open source
and free.
Eclipse – is also a java IDE developed
by the eclipse open source community.
Constructor Overloading in Java
Constructor in java is a special type of method that is used to initialize the
object.A constructor can also be overloaded. Overloaded constructors are differentiated on the
basis of their type of parameters or number of parameters. Constructor overloading is not much
different than method overloading. In case of method overloading you have multiple methods
with same name but different signature,whereas in Constructor overloading you have multiple
constructor with different signature but only difference is that Constructor doesn't have return type
in Java.
Types of java constructors
There are two types of constructors:
There are two types of constructors:
1. Default constructor (no-arg constructor)
2.Parameterized constructor
Syntax:
Nameofclass()
{
//statements
}
Nameofclass(parameters)
{
//statements
}
Parentclass
{
//statements
}
Syntax:
Nameofclass()
{
//statements
}
Nameofclass(parameters)
{
//statements
}
Parentclass
{
//statements
}
20.06.17
Aim:
To implement the constructor overloading using bill.
import java.io.*;
import java.util.*;
class bill
{
int
i,n,billno,qty,price,prono;
String proname;
bill()
{
System.out.println("*****************************************************");
System.out.println("\t\t\tWelcome
To Sarojini Store");
}
bill(int billno,int prono,int
qty,int price)
{
this.billno=billno;
this.prono=prono;
this.qty=qty;
this.price=price;
}
bill(String proname)
{
this.proname=proname;
}
bill(bill b,bill b1))
{
System.out.println("*****************************************************");
System.out.println("\t\t\tSAROJINI
STORE");
System.out.println("\t\t\t3,car
street,");
System.out.println("\t\t\tSivakasi");
System.out.println("*****************************************************");
System.out.println("\t\t\t\tCash
Bill");
System.out.println("\t\t\t\t---------");
System.out.println("Billno:"+b.billno+"\t\tDate:23/02/17\t\tTime:23:11:30
PM");
System.out.println("*****************************************************");
System.out.println("\tPro_no\tPro_name\tQty\tPrice");
System.out.println("*****************************************************");
System.out.println("\n");
System.out.println("\t"+b.prono+"\t"+b1.proname+"\t\t"+b.qty+"\t"+b.price);
System.out.println("*****************************************************");
System.out.println("\t\t\t\t\t\tAmount
: Rs"+(b.qty*b.price));
System.out.println("*****************************************************");
System.out.println("\t\t\tThank
You!!Come Again!!");
} }
class consover
{
public static void
main(String args[])
{
int pno,bno,qt,pr;
String pname;
Scanner s=new
Scanner(System.in);
System.out.println("Enter
the Billno:");
bno=s.nextInt();
System.out.println("Enter
the Product Number:");
pno=s.nextInt();
System.out.println("Enter
the Quantity");
qt=s.nextInt();
System.out.println("Enter
the Price");
pr=s.nextInt();
System.out.println("Enter
your product name:");
pname=s.next();
bill b2=new bill();
bill b4=new
bill(pname);
bill b3=new bill(bno,pno,qt,pr);
bill b5=new
bill(b3,b4);
} } Output:
Nested Class
In Java, just
like methods, variables of a class too can have another class as its member.
Writing a class within another is allowed in Java. The class written within is
called the
nested class,
and the class that holds the inner class is called the outer class.
Syntax
Class outer_demo
{
Class nested_demo
{
}
}
Subclass
A
Java subclass is a class which inherits a method or methods from a Java
superclass.A Java
class may be either a subclass, a superclass, both, or neither!
Syntax
class Super
{
Number aNumber;
}
class Sub extends Super
{
Float aNumber;
}
Ex.N0:2 Nested Classes
and Subclasses
Aim
To implement the
nested classes and subclasses using students marksheet.
import java.io.*;
import java.util.*;
class outer
{
class inner
{
int dob,c,cobol,dsa,co;
float avg;
String name,gender,grade,rollno,sc1,sc2,sc3,sc4;
public void input()
{
Scanner s=new
Scanner(System.in);
System.out.println("Enter
the Rollno");
rollno=s.next();
System.out.println("Enter
the Student Name:");
name=s.next();
System.out.println("Enter
the Gender");
gender=s.next();
System.out.println("Enter
the Date_Of_Birth");
dob=s.nextInt();
System.out.println("Enter
the C Subject Code");
sc1=s.next();
System.out.println("Enter
the C mark");
c=s.nextInt();
System.out.println("Enter
the Cobol Subject Code");
sc2=s.next();
System.out.println("Enter
the Cobol mark");
cobol=s.nextInt();
System.out.println("Enter
the DSA Subject Code");
sc3=s.next();
System.out.println("Enter
the DSA mark");
dsa=s.nextInt();
System.out.println("Enter
the CO Subject Code");
sc4=s.next();
System.out.println("Enter
the CO mark");
co=s.nextInt();
}
}
class subcla extends
inner
{
int total;
public void calc()
{
total=c+cobol+dsa+co;
}
public void display()
{
System.out.println("*************************************************");
System.out.println("\t\t\t
The Student MarkList");
System.out.println("*************************************************");
System.out.println("\n");
System.out.println("Name:"+name);
System.out.println("Gender:"+gender+"\t\t\tDate_of_Birth:"+dob);
System.out.println("*************************************************");
System.out.println("\tRno\tCS
C\tCoS\tCob\tDS\tDSS\tCS\tCO");
System.out.println("\t----\t----\t---\t-----\t------\t---\t-----\t----");
System.out.println("\t"+rollno+"\t"+sc1+"\t"+c+"\t"+sc2+"\t"+cobol+"\t"+sc3+"\t"+dsa+"
\t"+sc4+"\t"+co);
System.out.println("*************************************************");
avg=total/4;
if(avg>90)
{
System.out.println("\t\t\tYour Grade
is:First class with distinction");
System.out.println("\t\t\t Congratulations!!!");
}
else if(avg>80)
{
System.out.println("\t\t\tYour Grade
is:First class");
System.out.println("\t\t\t Congratulations!!!");
}
else if(avg>60)
{
System.out.println("\t\t\tYour Grade
is:Second class");
System.out.println("\t\t\t Congratulations!!!");
}
else
{
System.out.println("\t\t\tYour Grade
is:Fail");
System.out.println("\t\t\t Try Score High!!!"); }
System.out.println("************************************************");
}
}
}
class sub
{
public static void
main(String args[])
{
subcla u=new subcla();
u.input();
u.calc();
u.display();
}
}
Output
Method overloading
If two
or more method in a class have same name but different parameters, it is known
as method overloading. Overloading always occur in the same class(unlike
method
overriding).Method overloading is one of the ways through which java
supports
polymorphism. Method overloading can be done by changing number of
arguments or
by changing the data type of arguments. If two or more method have
same name
and same parameter list but
differs in return type are not said
to
be overloaded method.
Syntax
Class class_name
{
Returntype
method()
{
……
}
Returntype
method(datatype1 variable1,datatype2 variable 2)
{
…….
}
Returntype
method(datetype2 variable 2)
{
……
}
}
Ex.No:3 Method
Overloading
Aim
To implement the
method overloading using bank details.
import java.io.*;
import java.util.*;
class bank_det
{
String anm;
int ac_no,amt;
float amount,withdraw;
String name;
public bank_det()
{
System.out.println("--------------------------------------------------");
System.out.println("\t\tWelcome
TO SBI Bank");
System.out.println("--------------------------------------------------");
}
public void bank(String
name,int ac_no,float amount)
{
this.name=name;
this.ac_no=ac_no;
this.amount=amount;
}
public void bank(float
amount,int ac_no,float interest)
{
if(amount>1000) {
this.amount=this.amount+100; } }
public void bank(float
amount,int ac_no,float withdraw)
{
if(amount>1000) {
this.amount=this.amount-this.withdraw; } }
public void disp()
{
System.out.println("\t\tSBI
Bank");
System.out.println("--------------------------------------------------");
System.out.println("Name:"+name);
System.out.println("Ac_no:"+ac_no);
System.out.println("Amount:"+amount);
System.out.println("--------------------------------------------------");
} }
class bank_details
{
public static void
main(String args[])
{
bank_det b1=new
bank_det();
Scanner s1=new
Scanner(System.in);
String nme;
float inter, with;
int ano;
float am;
System.out.println("1.Bank
Details”);
System.out.println("2.Deposit”);
System.out.println("2.Withdraw”);
System.out.println("3.Interest”);
System.out.println("Enter
your choice”);
int ch=s1.nextInt();
System.out.println("Enter
the Account Name:");
nme=s1.next();
System.out.println("Enter
the Account No:");
ano=s1.nextInt();
System.out.println("Enter
the Amount:");
am=s1.nextFloat();
System.out.println("Enter
the Interest:");
inter=s1.nextFloat();
switch(ch)
{
case 1:
b1.bank(nme,ano,am);
case 2:
b1.bank(am,ano,inter);
case 3:
b1.bank(am,ano,with);
}
b1.disp();
}
}
Output:
Array of Object
Java provides a data structure, the array, which stores a
fixed-size sequential collection of
elements of the same type. An array is used
to store a collection of data, but it is often more
useful to think of an array
as a collection of variables of the same type.
Declaring
Array Variables
To use an array in a program, you
must declare a variable to reference the array, and you
must specify the type
of array the variable can reference. Here is the syntax for declaring an
array
variable.
Syntax
Datatype[] arrayrefvar;
Or
Datatype arrayref[];
Creating Arrays
Arrayrefvar = new
datatype[arraysize];
·
It creates an array using new
dataType[arraySize].
datatype[]
arrayrefvar=new datatype[arraysize];
·
It assigns the reference of the newly created
array to the variable arrayRefVar.
datatype[] arrayref={value0,value1,….,valuek};
Ex.No:4 Array
Of Objects
Aim
To implemented the array of objects using mobile.
import java.io.*;
import java.util.*;
class mob
{
String version;
String processor;
String ram;
String size;
int rs;
mob()
{
System.out.println("----------------------------------------------------------------------------");
System.out.println("\t\t\tWelcome
To Mobile Shop");
System.out.println("----------------------------------------------------------------------------");
}
mob(int rs,String
version,String processor,String ram,String size)
{
this.version=version;
this.processor=processor;
this.ram=ram;
this.size=size;
this.rs=rs;
}
void disp()
{
System.out.println("\t\t\tMobile
Features");
System.out.println("\t\t\t****************");
System.out.println("\t\t~
Mobile OS:"+version);
System.out.println("\t\t~
Mobile Processor:"+processor);
System.out.println("\t\t~
Mobile Size:"+size);
System.out.println("\t\t~
Mobile RAM:"+ram);
System.out.println("\t\t~
Mobile Price:"+rs);
System.out.println("----------------------------------------------------------------------------");
}
void calc()
{
System.out.println("\t\tAAdi
Offer");
System.out.println("\t\t~~~~~~~~~~~~~");
if(rs>10000)
rs=(rs*50)/100;
else if(rs>12000)
rs=(rs*30)/100;
System.out.println("\t\tYour
Mobile Amount is:"+rs);
}}
class mobile
{
public static void
main(String args[])
{
int i,n;
do {
System.out.println("----------------------------------------------------------------------------");
System.out.println("\t\t\tPOORVIKA
MOBILE SHOWROOM");
System.out.println("----------------------------------------------------------------------------");
System.out.println("\tMobile
Name Here:");
System.out.println("\t\t1)
OnePlus5 6GB");
System.out.println("\t\t2)
OnePlus5 8GB");
System.out.println("\t\t3)
HTC UII");
System.out.println("\t\t4)
Redmi 4A");
System.out.println("\t\t5)
Samsung Galaxy");
System.out.println("----------------------------------------------------------------------------");
mob[] b=new mob[5];
Scanner s=new Scanner(System.in);
System.out.println("Enter
your Mobile choose");
n=s.nextInt();
switch(n)
{ case 1:
System.out.println("\t\tYour
Choosen Mobile is:OnePlus5 6GB");
b[0]=new mob();
b[0]=new
mob(50000,"Android 7.1","Octa core
2.4GHZ","6GB","5.5 inches");
b[0].disp();
b[0].calc();
break;
case 2:
System.out.println("\t\tYour
Choosen Mobile is:OnePlus5 8GB");
b[1]=new mob();
b[1]=new
mob(30000,"Android 6.8","Octa core
1.5GHZ","3GB","5 inches");
b[1].disp();
b[1].calc();
break;
case 3:
System.out.println("\t\tYour
Choosen Mobile is:HTC UII");
b[2]=new mob();
b[2]=new
mob(10000,"Android 4.0","Quad core
1.5GHZ","2GB","4 inches");
b[2].disp();
b[2].calc();
break;
case 4:
System.out.println("\t\tYour
Choosen Mobile is:Redmi 4A");
b[3]=new mob();
b[3]=new
mob(8000,"Android 3.0","Quad core
1.5GHZ","3.5GB","3.8 inches");
b[3].disp();
b[3].calc();
break;
case 5:
System.out.println("\t\tYour
Choosen Mobile is:Samsung Galaxy");
b[4]=new mob();
b[4]=new
mob(9000,"Android 4.0","Octa core
1.5GHZ","7GB","4.5 inches");
b[4].disp();
b[4].calc();
break;}
System.out.println("----------------------------------------------------------------------------");
System.out.println("\tDo
You Want to Continue(0 or 1):");
i=s.nextInt();
}while(i==1);
System.out.println("----------------------------------------------------------------------------");
System.out.println("\t\t\tThank
You!!!Come Again");
System.out.println("----------------------------------------------------------------------------");
}}
Output
String class
It is a predefined class in java.lang package can be
used to handle the
String.String
class is immutable that
means whose content can not be changed at the
time
of execution of program.
String
The class object is
immutable that means when we create an object of String
class it never changes in the existing object.
length()
This method is used to get the number of character of any
string.
charAt()
This method is used to get the character at a given index
value.
toLowerCase()
This method is used to convert lower case string into upper
case.
concat()
This method is used to combined two string.
equals()
This method is used to compare two strings, It return true if
strings are same otherwise
return false. It is case sensitive method.
equalsIgnoreCase()
This
method is case insensitive method, It return true if the contents of both
strings are same otherwise false.
startsWith()
This method return true if string is start with given another
string, otherwise it returns
false.
endsWith()
This method return true if string is end with given another
string, otherwise it returns
false.
indexOf()
This method is used find the index value of given string. It
always gives starting
index value of first occurrence of string.
lastIndexOf()
This method used to return the starting index value of last
occurence of the given
string.
trim()
This method remove space which are available before starting
of string and after
ending of string.
replace()
This method is used to return a duplicate string by replacing
old character with new
character.
Ex.No:5 String
Class Methods
Aim
To
implement the string class methods.
import java.io.*;
import java.util.*;
class stri
{
public static void
main(String args[])
{
int i;
String msg,msg1,msg2;
msg=" java
Programa ";
int ch;
Scanner s=new
Scanner(System.in);
String s1=new
String(msg);
System.out.println("\t\tSTRING
METHOD");
System.out.println("--------------------------------------------------------------");
System.out.println("\t1.Constructor");
System.out.println("\t2.Byte
and Range");
System.out.println("\t3.Length");
System.out.println("\t4.Concatenation");
System.out.println("\t5.Charat");
System.out.println("\t6.string
comparison");
System.out.println("\t7.Startswith,endswith");
System.out.println("\t8.Indexof");
System.out.println("\t9.Case");
System.out.println("\t10.Trim");
System.out.println("\t11.Replace");
System.out.println("-------------------------------------------------------------");
System.out.println("The
String is:"+msg);
System.out.println("-------------------------------------------------------------");
do{
System.out.println("Enter
your Choice:");
ch=s.nextInt();
switch(ch)
{
case 1:
System.out.println("The
string is:"+s1);
break;
case 2:
byte
b[]={65,66,67,68,69};
String
s2=new String(b,2,3);
System.out.println("The
byte and range os string is:"+s2);
break;
case 3:
int
l=s1.length();
System.out.println("The
string:"+s1+"\tString length:"+l);
break;
case 4:
System.out.println("The
string is:"+s1);
String
jo=s1.concat(" Tutorials");
System.out.println("The
string concatenation is:"+jo);
break;
case 5:
char
x=s1.charAt(10);
System.out.println("the
particular string:"+x);
break;
case 6:
msg1="java
Programa";
msg2="Java
Programa";
System.out.println("Msg1:"+msg1+"Msg2:"+msg2);
System.out.println("Msg
equals Msg1:"+msg.equals(msg1));
System.out.println("Msg1
equals Msg2:"+msg1.equals(msg2)+"\tMsg2
equals Msg1:"+msg2.equalsIgnoreCase(msg1));
break;
case 7:
System.out.println("Startswith:"+s1.startsWith("ja"));
System.out.println("Endswith:"+s1.endsWith("grams"));
break;
case 8:
System.out.println("indexof:"+s1.indexOf('a'));
System.out.println("indexof:"+s1.indexOf("gra"));
break;
case 9:
System.out.println("uppercase:"+s1.toUpperCase());
System.out.println("Lowercase:"+s1.toLowerCase());
break;
case 10:
System.out.println("Replace:"+s1.replace('a','i'));
break;
case 11:
System.out.println("Trim:"+s1.trim());
break;
}
System.out.println("-------------------------------------------------------------");
System.out.println("Do
you want to continue press:(0 or 1):");
i=s.nextInt();
}while(i==1);
}
}
Output
D:\15us01>java stri
STRING METHOD
--------------------------------------------------------------
1.Constructor
2.Byte and Range
3.Length
4.Concatenation
5.Charat
6.string comparison
7.Startswith,endswith
8.Indexof
9.Case
10.Trim
11.Replace
-------------------------------------------------------------
The String is: java
Programa
Enter your Choice:1
The string is: java
Programa
-------------------------------------------------------------
Enter your Choice:2
The byte and range os
string is:CDE
-------------------------------------------------------------
Enter your Choice:3
The string: java
Programa String length:15
-------------------------------------------------------------
Enter your Choice:4
The string is: java
Programa
The string
concatenation is: java Programa
Tutorials
-------------------------------------------------------------
Enter your Choice:5
the particular string:r
-------------------------------------------------------------
Enter your Choice:6
Msg1:java
ProgramaMsg2:Java Programa
Msg equals Msg1:false
Msg1 equals
Msg2:false Msg2 equals Msg1:true
-------------------------------------------------------------
Enter your Choice:7
Startswith:false
Endswith:false
-------------------------------------------------------------
Enter your Choice:8
indexof:2
indexof:9
-------------------------------------------------------------
Enter your Choice:9
uppercase: JAVA
PROGRAMA
Lowercase: java
programa
-------------------------------------------------------------
Enter your Choice:10
Replace: jivi Progrimi
-------------------------------------------------------------
Enter your Choice:11
Trim:java Programa
-------------------------------------------------------------
StringBuffer Methods
It is a predefined
class in java.lang package can be used to handle the String,
whose object is mutable that means content can be modify. StringBuffer class is working with thread safe mechanism that means multiple thread are not allowed simultaneously to perform operation of StringBuffer.
StringBuffer class object is mutable that means when we create an object of
StringBulder
class it can be change
reverse()
This
method is used to reverse the given string and also the new value is replaced
by the old string.
insert()
This
method is used to insert either string or character or integer or real constant
or boolean value at a specific index value of given string.
append()
This
method is used to add the new string at the end of original string.
replace()
This method is used to
replace any old string with new string based on index value.
deleteCharAt()
This
method is used to delete a character at given index value.
delete()
This method is used to delete string form given string based
on index value.
capacity()
This method
returns the current capacity. The capacity is the amount of storage
available for newly inserted characters, beyond which an allocation will occur.
lastInd
exOf()
This method
returns the index within this string of the rightmost occurrence of
the specified substring.
length()
This method
returns the length (character count) of the sequence of characters currently
represented by this object.
setCharAt()
This method sets the
character at the specified index.
This sequence is altered to
represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index.
setLength()
This method
sets the length of the character sequence. The sequence is changed to a
new character sequence whose length is specified by the argument.
Ex.No:6 StringBuffer Class
and its Methods
Aim
To implement the
stringbuffer class and its methods.
import java.io.*;
import java.util.*;
class strbff
{
public static void
main(String args[])
{
int i;
String msg;
msg="java
Programa";
int ch;
Scanner s=new
Scanner(System.in);
StringBuffer s1=new StringBuffer(msg);
System.out.println("\t\tSTRINGBUFFER
CLASS METHOD");
System.out.println("--------------------------------------------------------------");
System.out.println("\t1.Length");
System.out.println("\t2.Capacity");
System.out.println("\t3.setlength");
System.out.println("\t4.Append");
System.out.println("\t5.charat");
System.out.println("\t6.setcharat");
System.out.println("\t7.ReverseInsert");
System.out.println("\t8.Deletecharat");
System.out.println("\t9.Replace");
System.out.println("\t10.Indexof");
System.out.println("-------------------------------------------------------------");
System.out.println("The
String is:"+msg);
System.out.println("-------------------------------------------------------------");
do{
System.out.println("Enter
your Choice:");
ch=s.nextInt();
switch(ch)
{
case 1:
int
l=s1.length();
System.out.println("The
string is:"+s1+"\tThe string length is:"+l);
break;
case 2:
int
cap=s1.capacity();
System.out.println("The
string is:"+s1+"\tThe string capacity is:"+cap);
break;
case 3:
System.out.println("Before
string is:"+s1);
System.out.println("\n");
s1.setLength(4);
System.out.println("After
the string set length is:"+s1);
break;
case 4:
System.out.println("Before
string is:"+s1);
System.out.println("\n");
s1.append("
tutorialv");
System.out.println("After
the string append is:"+s1);
break;
case 5:
System.out.println("Before
string is:"+s1);
System.out.println("\n");
s1.setCharAt(12,'s');
System.out.println("After
the string set char:"+s1);
break;
case 6:
System.out.println("Before
string is:"+s1);
System.out.println("\n");
s1.insert(4,"2point");
System.out.println("After
the inserted string is:"+s1);
break;
case 7:
System.out.println("Before
string is:"+s1);
System.out.println("\n");
s1.reverse();
System.out.println("After
the reverse string is:"+s1);
break;
case 8:
System.out.println("Before
string is:"+s1);
System.out.println("\n");
s1.deleteCharAt(12);
System.out.println("After
the deleted string is:"+s1);
break;
case 9:
System.out.println("Before
string is:"+s1);
System.out.println("\n");
s1.replace(12,17,"mmingsimplified");
System.out.println("After
the replaced string is:"+s1);
break;
case 10:
String msg1="one
by one";
StringBuffer s2=new
StringBuffer(msg1);
System.out.println("The
string is:"+msg1);
System.out.println("the
index string is:"+s2.indexOf("one"));
System.out.println("the
last index string is:"+s2.lastIndexOf("one"));
break;
}
System.out.println("-------------------------------------------------------------");
System.out.println("Do
you want to continue press:(0 or 1):");
i=s.nextInt();
}while(i==1);
} }
Output
D:\15us01>java
strbff
STRINGBUFFER CLASS METHOD
--------------------------------------------------------------
1.Length
2.Capacity
3.setlength
4.Append
5.charat
6.setcharat
7.ReverseInsert
8.Deletecharat
9.Replace
10.Indexof
-------------------------------------------------------------
The String is:java
Programa
-------------------------------------------------------------
Enter your Choice:1
The string is:java
Programa The string length is:13
-------------------------------------------------------------
Do you want to continue
press:(0 or 1):1
Enter your Choice:2
The string is:java
Programa The string capacity is:29
-------------------------------------------------------------
Enter your Choice:3
Before string is:java
Programa
After the string set
length is:java
-------------------------------------------------------------
Enter your Choice:4
Before string is:java
After the string append
is:java tutorialv
-------------------------------------------------------------
Enter your Choice:5
Before string is:java
tutorialv
After the string set
char:java tutoriasv
-------------------------------------------------------------
Enter your Choice:6
Before string is:java
tutoriasv
After the inserted
string is:java2point tutoriasv
-------------------------------------------------------------
Enter your Choice:7
Before string
is:java2point tutoriasv
After the reverse
string is:vsairotut tniop2avaj
-------------------------------------------------------------
Enter your Choice:8
Before string
is:vsairotut tniop2avaj
After the deleted
string is:vsairotut tnop2avaj
-------------------------------------------------------------
Enter your Choice:9
Before string
is:vsairotut tnop2avaj
After the replaced
string is:vsairotut tnmmingsimplifiedaj
-------------------------------------------------------------
Enter your Choice:10
The string is:one by
one
the index string is:0
the last index string
is:7
-------------------------------------------------------------
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Inheritance
Inheritance can
be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit the
properties of a class. Following is the
syntax of extends keyword.
Syntax
Class super
{
…..
}
Class
sub extends super
{
…..
}
Method
Overriding
If a class
inherits a method from its superclass, then there is a chance to override
method provided that it is not marked final.The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.In object-oriented terms, overriding means to override the functionality of an existing method.
Ex.No:7 Implement Inheritance and demonstrate
Method Overriding
Aim
To implement the inheritance
and demonstrate method overriding using EB bill.
import java.io.*;
import java.util.*;
class iover
{
public void caldisp()
{
System.out.println("-----------------------------------------------------------");
System.out.println("\t\tWelcome
to pay the EB BILL amount");
System.out.println("-----------------------------------------------------------");
}
}
class iover1 extends
iover
{
String name;
String dates;
int cur_read,pre_read;
double
unit,sur_charge,net_amt;
Scanner s=new
Scanner(System.in);
public void caldisp(){
System.out.println("Enter
the Name:");
name=s.next();
System.out.println("Enter
the date:");
dates=s.next();
System.out.println("Enter
the current reading:");
cur_read=s.nextInt();
System.out.println("Enter
the previous reading:");
pre_read=s.nextInt();
System.out.println("------------------------------------------------------------");
System.out.println("\t\t\tEB
BILL");
System.out.println("\t\t\t*********");
System.out.println("Name:"+name+"\t\t\tDate:"+dates);
System.out.println("------------------------------------------------------------");
System.out.println("Current
reading:"+cur_read+"\t\t"+"previous
reading:"+pre_read);
System.out.println("\n");
unit=cur_read-pre_read;
System.out.println("\t\tThe
unit is:"+unit);
if(unit>100)
{
sur_charge=25+(unit-30)*0.25;
net_amt=unit+sur_charge;
}
if(unit>400)
{
sur_charge=25+(unit-30)*0.25;
net_amt=unit+sur_charge;
}
if(unit>800)
{
sur_charge=50+(unit-55)*0.50;
net_amt=unit+sur_charge;
}
else
{
sur_charge=25+(unit-80)*0.75;
net_amt=unit+sur_charge; }
System.out.println("------------------------------------------------------------");
System.out.println("\tThe
Net Amount for the Eb bill is:"+"Rs."+net_amt);
System.out.println("------------------------------------------------------------");
System.out.println("\t\tHave
A Nice Day!!!!");
}
}
class inover
{
public static void
main(String args[])
{
iover i=new iover();
iover1 i1=new iover1();
i.caldisp();
i1.caldisp();
}
}
Output
Multilevel
Inheritance
When a class extends a class, which extends anther class then
this is called multilevel
inheritance. For example class C extends class B and class B extends class
A then this type of inheritance is known as multilevel inheritance.
Classs A
{
….
}
Class B extends A
{
…..
}
Class C extends B
{
…..
}
Ex.No:8 Implement
the concepts of multilevel inheritance
Aim
To implement the concepts
of multilevel inheritance using mobile netpack.
import java.io.*;
import java.util.*;
class npack
{
public int p_num;
public String m_name;
public double pays;
public String pack;
public double tax;
String week;
npack()
{
System.out.println("---------------------------------------------------------------------------");
System.out.println("\t\t\tWelcome
To Mobile Netpack shop");
System.out.println("---------------------------------------------------------------------------");
}
}
class npack1 extends
npack
{
Scanner s1=new
Scanner(System.in);
npack1(double
pay,double taxs,String packs,String weeks)
{
pays=pay;
tax=taxs;
pack=packs;
week=weeks;
System.out.println("Your
choosen netpack is:"+pack);
}
public void details()
{
System.out.println("Enter
your Mobile number:");
p_num=s1.nextInt();
System.out.println("Enter
your Mobile name:");
m_name=s1.next();
}
double calc()
{
System.out.println("pays:"+this.pays);
System.out.println("tax:"+this.tax);
System.out.println("Week:"+this.week);
return pays+tax; }}
class npack2 extends
npack1
{
npack2(double
pay,double taxs,String packs,String weeks)
{
super(pay,taxs,packs,weeks);
}
void disp()
{
System.out.println("-------------------------------------------------------------------------");
System.out.println("\t\t\tUnlimited
Netpack Shop");
System.out.println("-------------------------------------------------------------------------");
System.out.println("Mobile
number:"+p_num+"\t\tSim Name:"+m_name);
System.out.println("\n");
System.out.println("Day:"+week+"\t\tNetpack:"+pack+"\ttax:"+tax);
System.out.println("\n");
}}
class netpack
{
public static void
main(String args[])
{
int i;
int ch;
double paid;
Scanner c=new Scanner(System.in);
do
{
npack n=new npack();
System.out.println("\tAvailable
pack is:");
System.out.println("\t\t\t1)
2G");
System.out.println("\t\t\t2)
3G");
System.out.println("\t\t\t3)
4G");
System.out.println("--------------------------------------------------------------------------");
Scanner s=new
Scanner(System.in);
System.out.println("Please
choose the netpack types:");
ch=s.nextInt();
switch(ch)
{
case 1:
npack2 n1=new
npack2(250,5.5,"2G","3 week");
n1.details();
paid=n1.calc();
n1.disp();
System.out.println("\t\tNet
Amount is:Rs."+paid); break;
case 2:
npack2 n2=new
npack2(650,8.5,"2G","1 Month");
n2.details();
paid=n2.calc();
n2.disp();
System.out.println("\t\tNet
Amount is:Rs."+paid); break;
case 3:
npack2 n3=new
npack2(300,2.5,"4G","3 Month");
n3.details();
paid=n3.calc();
n3.disp();
System.out.println("\t\tNet
Amount is:Rs."+paid); break; }
System.out.println("-------------------------------------------------------------------------");
System.out.println("\t\tEnjoy
your unlimited internet pack!!!");
System.out.println("-------------------------------------------------------------------------");
System.out.println("Do
you want to continue:(0 or 1):");
i=c.nextInt();
}while(i==1);
}
}
Output
Interface
Interface
is a pure abstract class.They are syntactically similar to classes, but you
cannot create instance of an Interface and their methods are declared without any body. Interface is used to achieve complete abstraction in Java. When you create an interface it defines what a class can do without saying anything about how the class will do it.
Syntax
interface interface_name
{
//methods
declaration
}
Rules for using Interface
·
Methods inside Interface must not be
static, final, native or strictfp.
·
All variables declared inside interface
are implicitly public static final
variables(constants).
·
All methods declared inside Java
Interfaces are implicitly public and abstract, even if
you don't use public or abstract keyword.
·
Interface can extend one or more other
interface.
·
Interface cannot implement a class.
·
Interface can be nested inside another
interface.
extends
interface
Syntax
interface interface_name
{
//methods declaration
}
Interface
extends interface_name
{
//methods declaration
}
Ex.No:9 Implementing the Interface
and extending the Interface
Aim
To implement the interface
and extending the interface using notebook store.
import java.io.*;
import java.util.*;
interface sample
{
void title();
}
interface sam1 extends
sample
{
void det();
}
class sample1
implements sample,sam1
{
int n1;
int n2;
int n3;
sample1()
{
n1=30;
n2=50;
n3=60;
}
Scanner a=new Scanner(System.in);
int no,ch;
int q,amt;
public void title()
{
System.out.println("----------------------------------------------------------------------------");
System.out.println("\t\t\t\tStationary
Items");
System.out.println("----------------------------------------------------------------------------");
System.out.println("\t\tThe
list is:");
System.out.println("\t\t\t
1.Note Books");
System.out.println("\t\t\t
2.Pen");
System.out.println("\t\t\t
3.Paper");
System.out.println("\t\t\t
4.Pencil");
System.out.println("\t\t\t
5.Box");
System.out.println("----------------------------------------------------------------------------");
}
public void det()
{
System.out.println("Enter
your coice:");
ch=a.nextInt();
switch(ch)
{
case 1:
System.out.println("No.of
pages");
System.out.println("\t
120");
System.out.println("\t
160");
System.out.println("\t
180");
System.out.println("----------------------------------------------------------------------------");
System.out.println("Enter
your quantity:");
q=a.nextInt();
System.out.println("What
do you want note(No.of pages)?:");
no=a.nextInt();
switch(no)
{
case 120:
amt=n1*q;
break;
case 160:
amt=n2*1;
break;
case 180:
amt=n3*q;
System.out.println("---------------------------------------------------------------------");
System.out.println("Item
name:NoteBooks");
break;
}
case 2:
System.out.println("Pen");
System.out.println("\t
1)Ball point");
System.out.println("\t
2)Boomar");
System.out.println("----------------------------------------------------------------------------");
System.out.println("Enter
your quantity:");
q=a.nextInt();
System.out.println("What
do you want the pen type?:");
no=a.nextInt();
switch(no)
{
case 1:
amt=n1*q;
break;
case 2:
amt=n2*q;
break;
}
System.out.println("----------------------------------------------------------------------------");
System.out.println("Item
name:Pen"); break; }
System.out.println("\n");
System.out.println("\tQty\tNo.of
pages\tAmt");
System.out.println("\t****\t**************\t****");
System.out.println("\t"+q+"\t"
+no+"\t\t"+amt);
System.out.println("----------------------------------------------------------------------------");
System.out.println("\t\t\tYour
Amount is:Rs."+amt);
}
}
class inter1
{
public static void
main(String args[])
{
sample l=new sample1();
sample1 s=new
sample1();
s.title();
sam1 s1=new sample1();
s1.det();
System.out.println("----------------------------------------------------------------------------");
System.out.println("\t\t\tThank
You!! Come Again!!!");
System.out.println("----------------------------------------------------------------------------");
}
}
Output
Package
Package are used in Java, in-order to avoid name conflicts
and to control access of
class, interface and enumeration etc. A package can be defined as a group of similar types of classes, interface, enumeration and sub-package. Using package it becomes easier to locate the related classes.
Package are
categorized into two forms
·
Built-in Package:-Existing Java package
for example
java.lang , java.util etc.
·
User-defined-package:- Java package
created by user to categorized classes and
interface
Creating a
package
Creating a package in
java is quite easy. Simply include a package command followed by
name of the package as the first statement in java source file.
Syntax
Package mypack;
public
class employee
{
…statement;
}
import keyword
import keyword is used to import built-in and
user-defined packages into your
java source file so that your class can refer to a class that is in another package by directly using its name.
Syntax
import
pack_name.*;
Ex.No:10 User
defined package Creation
Aim
To implement the user
defined package creation using students marksheet.
Sample.java
package p1;
import java.util.*;
public class sample
{
Scanner s=new
Scanner(System.in);
public String name,rollno,dob,date,community;
public int
ta,en,ma,ph,ch,cs;
public sample() {
System.out.println("Enter
your name");
name=s.next();
System.out.println("Enter
your Rollno");
rollno=s.next();
System.out.println("Enter
your dob");
dob=s.next();
System.out.println("Enter
the year");
date=s.next();
System.out.println("Enter
your community");
community=s.next();
}
}
Sample1.java
package p1;
public class sample1
extends sample
{
public int tot;
public sample1()
{
System.out.println("Enter
your tamil");
ta=s.nextInt();
System.out.println("Enter
your english");
en=s.nextInt();
System.out.println("Enter
your maths");
ma=s.nextInt();
System.out.println("Enter
your physics");
ph=s.nextInt();
System.out.println("Enter
your chemistry");
ch=s.nextInt();
System.out.println("Enter
your cs");
cs=s.nextInt();
}
}
Sample3.java
package p1;
public class sample3
extends sample1
{
public int ch;
public float
cut_off,av;
public void calc()
{
tot=ta+en+ma+ph+ch+cs;
System.out.println("Total:"+tot);
av=tot/6;
cut_off=(ph/4)+(ch/4)+(ma/4)+(cs/4);
}
public void disp()
{
System.out.println("----------------------------------------------------------------------------");
System.out.println("\t\tStudent
Mark Details");
System.out.println("----------------------------------------------------------------------------");
System.out.println("\tName:"+name+"\t\t\tRollno:"+rollno);
System.out.println("\tDOB:"+dob+"\t\t\tCommunity:"+community);
System.out.println("----------------------------------------------------------------------------");
System.out.println("Tamil\tEnglish\t\tMaths\tPhy\tche\tcs");
System.out.println("******\t********\t******\t*****\t****\t***");
System.out.println(ta+"\t"+en+"\t\t"+ma+"\t"+ph+"\t"+ch+"\t"+cs);
System.out.println("----------------------------------------------------------------------------");
System.out.println("\t\tAverage
is:"+av);
System.out.println("----------------------------------------------------------------------------");
System.out.println("Do
you have extra curricular activity in the school?:(1 or 0)");
ch=s.nextInt();
System.out.println("----------------------------------------------------------------------------");
switch(ch)
{
case 1:
cut_off=cut_off+3;
System.out.println("Extra
curricular activity with cut_off mark:"+cut_off);
break;
}
if(cut_off>90)
{
System.out.println("Medical
course you are eligible");
}
if(cut_off>70)
{
System.out.println("Engineering
course you are eligible");
}
else
{
System.out.println("Arts
and science course you are eligible");
}
System.out.println("-----------------------------------------------------------------------------");
System.out.println("\t\t\tCongrats!!!");
System.out.println("----------------------------------------------------------------------------");
}
}
Mainpack.java
import p1.sample;
import p1.sample1;
import p1.sample3;
class mf
{
public static void
main(String args[])
{
sample3 s3=new
sample3();
s3.calc();
s3.disp();
}
}
Output
Multithreading
`A program can be divided into a number of small processes.
Each small process can
be addressed as a single thread (a lightweight process). You can think of a lightweight process as a virtual CPU that executes code or system calls. You usually do not need to concern yourself with lightweight processes to program with threads. Multithreaded programs contain two or more threads that can run concurrently and each thread defines a separate path of execution. This means that a single program can perform two or more tasks simultaneously.
The main thread
When
we run any java program, the program begins to execute its code starting
from the main method. Therefore, the JVM creates a thread to start executing the code present in main method. This thread is called as main thread. Although the main thread is automatically created, you can control it by obtaining a reference to it by calling currentThread() method.
Life cycle of a Thread
1. New : A
thread begins its life cycle in the new state. It remains in this state until
the
start() method is called on it.
2. Runnable
: After
invocation of start() method on new thread, the thread becomes
runnable.
3. Running
: A
thread is in running state if the thread scheduler has selected it.
4. Waiting : A
thread is in waiting state if it waits for another thread to perform a task.
In this stage the thread is still alive.
5. Terminated : A
thread enter the terminated state when it complete its task.
Thread
Priorities
Every
thread has a priority that helps the operating system determine the order in
which threads are scheduled for execution. In java thread priority ranges between 1 to 10,
·
MIN-PRIORITY (a constant of 1)
·
MAX-PRIORITY (a constant of 10)
By default every thread
is given a NORM-PRIORITY(5). The main thread always
have NORM-PRIORITY.
Ex.No:11 Implement multithreading
using runnable Interface.
Aim
To implement multithreading using runnable interface.
//Extends thread
class newthread extends
Thread
{
int n;
int a=-1,i;
int b=1;
int c=0;
String name;
Thread t;
newthread(String
threadname)
{
name=threadname;
t=new
Thread(this,name);
System.out.println("New
thread"+t);
t.start();
}
public void run()
{
try
{
for(i=0;i<5;i++)
{
c=a+b;
a=b;
b=c;
System.out.println("Child
thread "+name+"is:"+c);
Thread.sleep(1000);
}
}
catch(InterruptedException
e)
{
System.out.println("Exception
is"+e);
}
System.out.println("Childthread"+name+"is
existing");
}
}
class extendthread
{
public static void
main(String args[])
{
newthread s=new
newthread("one");
try
{
for(int i=5;i>0;i--)
{
System.out.println("Mainthread
is:"+i);
Thread.sleep(500);
}
}
catch(InterruptedException
e)
{
System.out.println(e);
}
System.out.println("Mainthread
Existing");
}
}
Output
class newthread
implements Runnable
{
int n;
int a=-1,i;
int b=1;
int c=0;
String name;
Thread t;
newthread(String
threadname)
{
name=threadname;
t=new
Thread(this,name);
System.out.println("New
thread"+t);
t.start(); }
public void run()
{
try
{
for(i=0;i<5;i++)
{
c=a+b;
a=b;
b=c;
System.out.println("Child
thread "+name+"is:"+c);
Thread.sleep(1000);
}
}
catch(InterruptedException
e)
{
System.out.println("Exception
is"+e);
}
System.out.println("Childthread"+name+"is
existing");
}
}
class multithreaddemo
{
public static void
main(String args[])
{
newthread s=new
newthread("one");
newthread s1=new
newthread("two");
try
{
for(int i=5;i>0;i--)
{
System.out.println("Mainthread
is:"+i);
Thread.sleep(500);
}
}
catch(InterruptedException
e)
{
System.out.println(e);
}
System.out.println("Mainthread
Existing");
}
}
Output
Interthread Communication
Java provide benefits of avoiding thread pooling using
inter-thread
communication. The wait(), notify(), and notifyAll() methods of Object class are used for this purpose. These method are implemented asfinal methods in Object, so that all classes have them. All the three method can be called only from within a synchronized context.
·
wait() tells calling thread to give
up monitor and go to sleep until some other thread
enters the same monitor and call notify.
·
notify() wakes up a thread that called
wait() on same object.
·
notifyAll() wakes up all the thread that
called wait() on same object.
Synchronization
At
times when more than one thread try to access a shared resource, we need to
ensure
that resource will be used by only one thread at a time. The process by which this is achieved is calledsynchronization. The synchronization keyword in java creates a block of code referred to as critical section.
Using
Synchronized Methods
Using Synchronized
methods is a way to accomplish synchronization. But lets first see what
happens when we do not use synchronization in our program.
Synchronized
Keyword
To
synchronize above program, we must synchronize access to the shared display()
method, making it available to only one thread at a time. This is done by using keyword synchronized with display() method.
Syntax
Synchronized
void display(String msg)
Ex.No:12 Interthread communication
using Synchronization
Aim
To implement the
interthread communication using synchronization.
import java.io.*;
class customer
{
int amt=10000;
synchronized void
withdraw(int amt)
{
System.out.println("\t\tGoing
to withdraw");
if(this.amt<amt)
{
System.out.println("\tLess
balancing waiting for deposit");
System.out.println();
System.out.println("\t\t************");
System.out.println();
Try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
}
this.amt-=amt;
System.out.println("\tAfter
withdraw,Your current amount is:"+this.amt);
System.out.println("\t\tWithdraw
completed!!!!!");
System.out.println("----------------------------------------------------------------");
}
synchronized void
deposit(int amt)
{
System.out.println("\t\tGoing
to deposit");
this.amt+=amt;
System.out.println("\tYour
deposited amount is:"+this.amt);
System.out.println("\t\tDeposit
completed!!!!");
System.out.println();
System.out.println("\t\t************");
System.out.println();
notify();
}
}
class syninter
{
public static void
main(String args[])
{
System.out.println("\t\tBank
Amount Details");
final customer c=new
customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}
Output
Exception
A
Java Exception is an object that describes the exception that occurs in a
program.
When an exceptional events occurs in java, an exception is said to be thrown. The code that's responsible for doing something about the exception is called an exception handler.A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception.
Syntax
try
{
//protected code
}
Catch(Exception e)
{
//catch block
}
Built-in
Exceptions
Ex.No:13 Exception Handling - Built-in exceptions
Aim
To implement the exception
handling-Built-in exception..
class sampexc
{
public static void
main(String a[])
{
int v=0;
int n,c=0;
for(int
i=0;i<a.length;i++)
{
try
{
n=Integer.parseInt(a[i]);
}
catch(Exception e)
{
System.out.println(e);
System.out.println("Caught
an invalid no");
c=c+1;
v=v+1;
}
System.out.println("Valid:"+c);
System.out.println("Invalid:"+c);
}
}
}
Output
D:\15us01>java
sampexc 1.1
java.lang.NumberFormatException:
For input string: "1.1"
Caught an invalid no
Valid:1
Invalid:1
class sampexc
{
public static void
main(String args[])
{
int a=10;
int b=0;
try
{
int c=a/b;
System.out.println(c);
}
catch(Exception e)
{
System.out.println(e);
int d=a*b;
System.out.println(d);
}
}
}
Output
D:\15us01>java
sampexc
java.lang.ArithmeticException:
/ by zero
0
class nestry
{
public static void
main(String args[])
{
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a
= " + a);
try
{
if(a==1) a = a/(a-a);
// division by zero
if(a==2)
{
int c[] = { 1 };
c[42] = 99;
}
}
catch(ArrayIndexOutOfBoundsException
e)
{
System.out.println("Array
index out-of-bounds: " + e); }
}
catch(ArithmeticException e)
{
System.out.println("Divide
by 0: " + e);
}
}
}
Output
D:\15us01>java
nestry 12 23
a value 2
Array index
out-of-bounds: java.lang.ArrayIndexOutOfBoundsException: 42
class nestry
{
static void demoproc()
{
try
{
throw new
NullPointerException("Demo");
}
catch(NullPointerException
e)
{
System.out.println("Caught
inside demoproc");
throw e;
}
}
public static void
main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException
e)
{
System.out.println(e);
}
}
}
Output
D:\15us01>java
nestry
Caught inside demoproc
java.lang.NullPointerException:
Demo
class nestry
{
static void demoproc()
throws NullPointerException
{
System.out.println("Inside
demoproc");
try
{
throw new
NullPointerException("Demo");
}
catch(NullPointerException
e)
{
System.out.println("Caught
inside demoproc");
throw e;
}
}
public static void
main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException
e)
{
System.out.println(e);
}
}
}
Output
D:\15us01>java
nestry
Inside demoproc
Caught inside demoproc
java.lang.NullPointerException:
Demo
User Defined Exception
·
All exceptions must be a child of Throwable.
·
If you want to write a checked exception that
is automatically enforced by
the Handle or Declare Rule, you need to extend the Exception class.
·
If you want to write a runtime exception, you
need to extend the RuntimeException
class.
Syntax
class MyException extends Exception
{
……
}
Ex.No:14 Exception
Handling - User defined exception
Aim
To implement the exception
handling-user defined package using adharcard
number.
import java.util.*;
class
AdharNumberException extends Exception
{
String msg;
public
AdharNumberException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
public class
myexception
{
public static void
main(String a[])
{
String
name,address,dob;
String
caste,father_name;
int phno;
int adhar_no;
Scanner s=new
Scanner(System.in);
System.out.println("Enter
Your Name");
name=s.next();
System.out.println("Enter
Your Address");
address=s.next();
System.out.println("Enter
Your Dob");
dob=s.next();
System.out.println("Enter
Your Caste");
caste=s.next();
System.out.println("Enter
Your FatherName");
father_name=s.next();
System.out.println("Enter
Your phno");
phno=s.nextInt();
System.out.println("Enter
Your AdharNo");
adhar_no=s.nextInt();
System.out.println("_____________________________________________________");
System.out.println("Name\tFatherName\tCaste\t\tAddress\t\tDob\t\tphno");
System.out.println("*******\t**************\t******\t\t**********\t****\t******");
System.out.println(name+"\t"+father_name+"\t"+caste+"\t"+address+"\t"+dob+"\t"+phn);
System.out.println("____________________________________________________");
try
{
if(adhar_no<0)
{
throw new
AdharNumberException("The Adhar Number Is Not Allowed Negative ");
}
else
{
System.out.println("Your
phno and adhar_no is positive");
System.out.println("_____________________________________________________");
}
}
catch(AdharNumberException
e)
{
System.out.println("Exception
is:"+e);
System.out.println("_____________________________________________________");
}
}
}
Output
File
FileOutputStream
Class
Java FileOutputStream is an
output stream used for writing data to a file.If you
have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutStream.
Ex.No:16 Create a File and Check Attributes
Aim
To create a file and check attributes.
//Write a file
import java.io.*;
public class fos1
{
public static void
main(String a[])
{
try
{
FileOutputStream
fo=new FileOutputStream("D:\\sample1.txt");
fo.write(65);
fo.close();
System.out.println("Success");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output
D:\java>java fos1
Success..
//Read a file
import java.io.*;
public class fin1
{
public static void
main(String a[])
{
try
{
FileInputStream
fin=new FileInputStream("D:\\sample.txt");
int
i=fin.read();
System.out.println((char)i);
fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output
D:\java>java fin1
A
Copy the File
ByteArrayOutputStream
·
Java
ByteArrayOutputStream class is used to write common data into multiple
files.
In this stream, the data is written into a byte array which can be written to multiple streams later.
·
The
ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.
·
The buffer of
ByteArrayOutputStream automatically grows according to data.
Ex.No:16 Copy contents of one file to
another file
Aim
To copy the contents of one file to another files.
import java.io.*;
class copyfile
{
public static void
main(String args[]) throws IOException
{
FileOutputStream
fout1=new FileOutputStream("D:\\Copy1.txt");
FileOutputStream
fout2=new FileOutputStream("D:\\Copy2.txt");
ByteArrayOutputStream
bout=new ByteArrayOutputStream();
String
s="Welcome To Anjac";
byte
b[]=s.getBytes();
bout.write(b);
bout.writeTo(fout1);
bout.writeTo(fout2);
bout.flush();
fout1.close();
fout2.close();
System.out.println("Success..");
}
}
D:\>java copyfile
Output:
Success..
Copy1.txt
Welcome To Anjac
Copy2.txt
Welcome To Anjac
BufferedStream and ByteArrayStream
BufferedOutputStream Class
Java
BufferedOutputStream class is used for buffering an output stream. It
internally
uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.
Syntax
OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));
BufferedInputStream Class
Java BufferedInputStream
class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
The important points about
BufferedInputStream are:
|
Changing the state of an object
is known as an event. For example, click on button, dragging mouse etc. The
java.awt.event package provides many event classes and Listener interfaces
for event handling.
|
Java Event classes and Listener interfaces
Event
Classes
|
Listener
Interfaces
|
ActionEvent
|
ActionListener
|
MouseEvent
|
MouseListener
and MouseMotionListener
|
MouseWheelEvent
|
MouseWheelListener
|
KeyEvent
|
KeyListener
|
ItemEvent
|
ItemListener
|
TextEvent
|
TextListener
|
AdjustmentEvent
|
AdjustmentListener
|
WindowEvent
|
WindowListener
|
ComponentEvent
|
ComponentListener
|
ContainerEvent
|
ContainerListener
|
FocusEvent
|
FocusListener
|
Source of Events:
·
Button
- public void addActionListener(ActionListener a){}
- MenuItem
- public void addActionListener(ActionListener a){}
- TextField
- public void addActionListener(ActionListener a){}
- public void addTextListener(TextListener a){}
- TextArea
- public void addTextListener(TextListener a){}
- Checkbox
- public void addItemListener(ItemListener a){}
- Choice
- public void addItemListener(ItemListener a){}
- List
- public void addActionListener(ActionListener a){}
- public void addItemListener(ItemListener a){}
Event
classes:
- ActionEvent
- AdjustmentEvent
- ComponentEvent
- ContainerEvent
- FocusEvent
- InputEvent
- ItemEvent
- KeyEvent
- MouseEvent
- PaintEvent
- TextEvent
- WindowEvent
KeyEvent
The Java KeyListener is notified whenever you change the state of key.
It is notified against KeyEvent. The KeyListener interface is found in
java.awt.event package. It has three methods.
3 methods found in KeyListener interface
·
public abstract void keyPressed(KeyEvent e);
·
public abstract void keyReleased(KeyEvent e);
·
public abstract void keyTyped(KeyEvent e);
MouseEvent
·
The
Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent. The MouseListener interface is found in
java.awt.event package.
·
It has
five methods.
Ø public abstract void mouseClicked(MouseEvent e);
Ø public abstract void mouseEntered(MouseEvent e);
Ø public abstract void mouseExited(MouseEvent e);
Ø public abstract void mousePressed(MouseEvent e);
Ø public abstract void mouseReleased(MouseEvent e);
Ex.No:21 Implementing Key Events
Aim
To implementing key events.
import java.awt.*;
import
java.awt.event.*;
import java.applet.*;
/*
<applet
code="keyboard" width=500 height=500>
</applet>
*/
public class keyboard
extends Applet implements KeyListener
{
int X=0,Y=20;
String
msg="";
public void init()
{
addKeyListener(this);
}
public void
keyPressed(KeyEvent ke)
{
showStatus("Key
Down");
}
public void
keyReleased(KeyEvent ke)
{
showStatus("Key
up");
}
public void
keyTyped(KeyEvent ke)
{
msg+=ke.getKeyChar();
repaint();
}
public void
paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Output
Menu
and MenuItems
Menus
Java are a number of pull-down combo boxes (In Java called as Choice) placed at
single place for easy selection by the user.
To
create menus, the java.awt package comes with mainly four classes – MenuBar,
Menu, MenuItem and CheckboxMenuItem. All these four classes are not AWT
components as they are not subclasses of java.awt.Component class. Infact, they
are subclasses of java.awt.MenuComponent which is is no way connected in the
hierarchy with Component class.
MenuBar
MenuBar
holds the menus. MenuBar is added to frame with setMenuBar() method.
Implicitly, the menu bar is added to the north (top) of the frame. MenuBar
cannot be added to other sides like south and west etc.
Menu
Menu
holds the menu items. Menu is added to frame with add() method. A sub-menu can be added to
Menu.
MenuItem
MenuItem
displays the actual option user can select. Menu items are added to menu with
method addMenuItem(). A dull-colored line can be added in
between menu items with addSeparator() method.
The dull-colored line groups (or separates from other) menu items with similar
functionality like cut, copy and paste.
CheckboxMenuItem
It
differs from MenuItem in that it appears along with a checkbox. The selection
can be done with checkbox selected.
Ex.No:22 Creating Menu and Menu Items using Frame.
Aim
To creating menu and menu items using frame.
// Illustrate menus.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MenuDemo.class" width=250
height=250>
</applet>
*/
// Create a subclass of Frame.
class MenuFrame extends Frame
{
String msg = "";
CheckboxMenuItem debu
g, test;
MenuFrame(String title)
{
super(title);
// create menu bar and add it to frame
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
// create the menu items
Menu file = new Menu("File");
MenuItem item1, item2, item3, item4, item5;
file.add(item1 = new MenuItem("New..."));
file.add(item2 = new MenuItem("Open..."));
file.add(item3 = new MenuItem("Close"));
file.add(item4 = new MenuItem("-"));
file.add(item5 = new MenuItem("Quit..."));
mbar.add(file);
Menu edit = new Menu("Edit");
MenuItem item6, item7, item8, item9;
edit.add(item6 = new MenuItem("Cut"));
edit.add(item7 = new MenuItem("Copy"));
edit.add(item8 = new MenuItem("Paste"));
edit.add(item9 = new MenuItem("-"));
Menu sub = new Menu("Special");
MenuItem item10, item11, item12;
sub.add(item10 = new MenuItem("First"));
sub.add(item11 = new MenuItem("Second"));
sub.add(item12 = new MenuItem("Third"));
edit.add(sub);
// these are checkable menu items
debug = new CheckboxMenuItem("Debug");
edit.add(debug);
test = new CheckboxMenuItem("Testing");
edit.add(test);
mbar.add(edit);
// create an object to handle action and item events
MyMenuHandler handler = new MyMenuHandler(this);
// register it to receive those events
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
item11.addActionListener(handler);
item12.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g)
{
g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);
if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10, 240);
}
}
class MyWindowAdapter extends WindowAdapter
{
MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame)
{
this.menuFrame = menuFrame;
}
public void windowClosing(WindowEvent we)
{
menuFrame.setVisible(false);
}
}
class MyMenuHandler implements ActionListener,
ItemListener
{
MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame)
{
this.menuFrame = menuFrame;
}
// Handle action events.
public void actionPerformed(ActionEvent ae)
{
String msg = "You selected ";
String arg = ae.getActionCommand();
if(arg.equals("New..."))
msg += "New.";
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}
// Handle item events.
public void itemStateChanged(ItemEvent ie)
{
menuFrame.repaint();
}
}
// Create frame window.
public class MenuDemo extends Applet
{
Frame f;
public void init()
{
f = new MenuFrame("Menu Demo");
int width =
Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
setSize(new Dimension(width, height));
f.setSize(width, height);
f.setVisible(true);
}
public void start()
{
f.setVisible(true);
}
public void stop()
{
f.setVisible(false);
}
}
Output
Ex.No:23 Demonstrate
Mouse Event
Aim
To demonstrate the mouse events.
import java.awt.*;
import
java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse"
width=500 height=500>
</applet>
*/
public class Mouse
extends Applet implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String
msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void
mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse
Entered");
repaint();
}
public void
mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse
Exited");
repaint();
}
public void
mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="NEC";
setBackground(Color.green);
repaint();
}
public void
mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent
m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse
Moved");
repaint(); }
public void
mouseDragged(MouseEvent m)
{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse
Moved"+m.getX()+" "+m.getY());
repaint();
}
public void
mouseClicked(MouseEvent m)
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse
Clicked");
repaint();
}
public void
paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Output
Ex.No:23 Implementing an
Animation by using Applet
Aim
To create an animation.
import java.applet.*;
import java.awt.*;
public class ani extends Applet
{
public void paint(Graphics g)
{
int a=150,b=150,c=10,d=10;
g.setColor(Color.red);
for(int i=0;i<15;i++)
{
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
g.drawOval(a,b,c,d);
a-=10;
b-=10;
c+=8;
d+=10;
}
}
}
/*<applet code="ani" height=800
width=700>
</applet> */
Output
AWT
Compoenents
Container
The
Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.
Panel
The
Panel is the container that doesn't contain title bar and menu bars. It can
have other components like button, textfield etc.
Frame
The
Frame is the container that contain title bar and can have menu bars. It can
have other components like button, textfield etc.
Button
public void
addActionListener(ActionListener a)
{
}
TextField
public void
addTextListener(TextListener a)
{
}
Choice
public void
addItemListener(ItemListener a)
{
}
Java ActionListener Interface
The Java
ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent. The ActionListener interface is found in
java.awt.event package. It has only one method: actionPerformed().
public void actionPerformed(ActionEvent e);
Ex.No:24 Create a Calculator to
perform Arithmetic operations
Aim
To
create a calculator to perform arithmetic operations.
import java.awt.*;
import java.awt.event.*;
/*
<applet code="calculator" width=500 height=500>
</applet>
*/
public class calculator implements ActionListener
{
int c,n;
String s1,s2,s3,s4,s5;
Frame f;
Button
b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17;
Panel p;
TextField tf;
GridLayout g;
public calculator()
{
f = new Frame("My calculator");
p = new Panel();
f.setLayout(new FlowLayout());
b1 = new Button("0");
b1.addActionListener(this);
b2 = new Button("1");
b2.addActionListener(this);
b3 = new Button("2");
b3.addActionListener(this);
b4 = new Button("3");
b4.addActionListener(this);
b5 = new Button("4");
b5.addActionListener(this);
b6 = new Button("5");
b6.addActionListener(this);
b7 = new Button("6");
b7.addActionListener(this);
b8 = new Button("7");
b8.addActionListener(this);
b9 = new Button("8");
b9.addActionListener(this);
b10 = new Button("9");
b10.addActionListener(this);
b11 = new Button("+");
b11.addActionListener(this);
b12 = new Button("-");
b12.addActionListener(this);
b13 = new Button("*");
b13.addActionListener(this);
b14 = new Button("/");
b14.addActionListener(this);
b15 = new Button("%");
b15.addActionListener(this);
b16 = new Button("=");
b16.addActionListener(this);
b17 = new Button("C");
b17.addActionListener(this);
tf = new TextField(20);
f.add(tf);
g = new GridLayout(4,4,10,20);
p.setLayout(g);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(b10);
p.add(b11);
p.add(b12);
p.add(b13);
p.add(b14);
p.add(b15);
p.add(b16);
p.add(b17);
f.add(p);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
s3 =
tf.getText();
s4 = "0";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b2)
{
s3 =
tf.getText();
s4 = "1";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b3)
{
s3 =
tf.getText();
s4 = "2";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b4)
{
s3 =
tf.getText();
s4 = "3";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b5)
{
s3 =
tf.getText();
s4 = "4";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b6)
{
s3 =
tf.getText();
s4 = "5";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b7)
{
s3 =
tf.getText();
s4 = "6";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b8)
{
s3 =
tf.getText();
s4 = "7";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b9)
{
s3 =
tf.getText();
s4 = "8";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b10)
{
s3 =
tf.getText();
s4 = "9";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b11)
{
s1 =
tf.getText();
tf.setText("");
c=1;
}
if(e.getSource()==b12)
{
s1 =
tf.getText();
tf.setText("");
c=2;
}
if(e.getSource()==b13)
{
s1 =
tf.getText();
tf.setText("");
c=3;
}
if(e.getSource()==b14)
{
s1 =
tf.getText();
tf.setText("");
c=4;
}
if(e.getSource()==b15)
{
s1 =
tf.getText();
tf.setText("");
c=5;
}
if(e.getSource()==b16)
{
s2 = tf.getText();
if(c==1)
{
n = Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else if(c==2)
{
n = Integer.parseInt(s1)-Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==3)
{
n = Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
if(c==4)
{
try
{
int p=Integer.parseInt(s2);
if(p!=0)
{
n =
Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
tf.setText("infinite");
}
catch(Exception i)
{
}
}
if(c==5)
{
n =
Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
}
if(e.getSource()==b17)
{
tf.setText("");
}
}
public static void main(String[] abc)
{
calculator
v = new calculator();
}
}
Output
Ex.No:25 Bar
Chart using Applets
Aim
To create a Barchart using Applet.
import java.awt.*;
import java.applet.*;
public class
BarChart extends Applet
{
int n=0;
String
label[];
int value[];
public void
init()
{
setBackground(Color.pink);
try
{
int n =
Integer.parseInt(getParameter("Columns"));
label = new String[n];
value = new int[n];
label[0] =
getParameter("label1");
label[1] =
getParameter("label2");
label[2] =
getParameter("label3");
label[3] = getParameter("label4");
value[0] = Integer.parseInt(getParameter("c1"));
value[1] =
Integer.parseInt(getParameter("c2"));
value[2] =
Integer.parseInt(getParameter("c3"));
value[3] =
Integer.parseInt(getParameter("c4"));
}
catch(NumberFormatException e)
{
}
}
public void
paint(Graphics g)
{
for(int
i=0;i<4;i++)
{
g.setColor(Color.black);
g.drawString(label[i],20,i*50+30);
g.setColor(Color.red);
g.fillRect(50,i*50+10,value[i],40);
}
}
}
/* <applet code=BarChart width=400
height=400>
<param
name=c1 value=110> <param
name=c2 value=150>
<param name=c3
value=100>
<param name=c4 value=170>
<param
name=label1 value=1991>
<param name=label2 value=1992>
<param
name=label3 value=1993>
<param name=label4 value=1994>
<param
name=Columns value=4>
</applet>
*/
Output
Layout Manager
Layout means
the arrangement of components within the container. In other way we can say
that placing the components at a particular position within the container. The
task of layouting the controls is done automatically by the Layout Manager.
Java provide us
with various layout manager to position the controls. The properties like
size,shape and arrangement varies from one layout manager to other layout
manager. When the size of the applet or the application window changes the
size, shape and arrangement of the components also changes in response i.e. the
layout managers adapt to the dimensions of appletviewer or the application
window.
BorderLayout
The borderlayout arranges the
components to fit in the five regions: east, west, north, south and center.
|
CardLayout
The CardLayout object treats
each component in the container as a card. Only one card is visible at a
time.
CardLayout(int hgap, int
vgap): creates a card layout with the given horizontal and vertical gap.
|
FlowLayout
The
FlowLayout is the default layout.It layouts the components in a directional
flow.
|
GridLayOut
The GridLayout manages the components in
form of a rectangular grid.
|
GridLayout(): creates a grid layout with one
column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
GridLayout(int
rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.
Ex.No:26 Different Types of Layouts
Aim
To implement the different types of layouts.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MyBorderLayout" width=500
height=500>
</applet>
*/
public class MyBorderLayout extends Frame
{
Frame f;
Button b1,b2,b3,b4,b5;
public MyBorderLayout()
{
f=new Frame();
b1=new Button("NORTH");
b2=new Button("SOUTH");
b3=new Button("CENTER");
b4=new Button("WEST");
b5=new Button("EAST");
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.CENTER);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.EAST);
//setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting
grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyBorderLayout();
}
}
Output
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MyCardLayout" width=500
height=500>
</applet>
*/
public class MyCardLayout extends Frame implements
ActionListener
{
CardLayout
c;
public MyCardLayout()
{
c = new CardLayout();
Button b1=new Button("hi");
Button b2=new Button("hello");
Button b3=new Button("bye");
Button b4=new Button("take care");
setLayout(c);
add(b1,"card1");
add(b2,"card2");
add(b3,"card3");
add(b4,"card4");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
setSize(300,300);
setVisible(true);
setTitle("CardLayout Manager");
}
public void actionPerformed(ActionEvent ae)
{
c.first(this);
c.last(this);
c.next(this);
//c.previous(this);
c.show(this,"card2");
}
public static void main(String[] args)
{
new MyCardLayout();
}
}
Output
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MyFlowLayout" width=500
height=500>
</applet>
*/
public class MyFlowLayout extends Frame
{
Button b1,b2 ;
public MyFlowLayout(){
b1=new Button("1");
b2=new
Button("2");
Button b3=new Button("3");
Button
b4=new Button("4");
Button b5=new Button("5");
Button
b6=new Button("6");
Button b7=new Button("7");
Button
b8=new Button("8");
Button b9=new Button("9");
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
setLayout(new
FlowLayout(FlowLayout.LEFT));
setSize(300,300);
setVisible(true);
}
public static void main(String[] args)
{
new MyFlowLayout();
}
}
Output
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MyGridLayout" width=500
height=500>
</applet>
*/
public class MyGridLayout extends Frame implements
ActionListener
{
Button b1,b2,b3,b4,b5,b6,b7,b8;
TextField t1;
public MyGridLayout(){
b1=new Button("1");
b2=new
Button("2");
b3=new Button("3");
b4=new
Button("4");
b5=new Button("5");
b6=new
Button("6");
b7=new Button("7");
b8=new
Button("8");
t1 =new TextField();
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(t1);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
GridLayout gl = new GridLayout(3,3,20,20);
setLayout(gl);
//setting
grid layout of 3 rows and 3 columns
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
t1.setText(b1.getLabel());
}
if(ae.getSource()==b2)
{
t1.setText(b2.getLabel());
}
if(ae.getSource()==b3)
{
t1.setText(b3.getLabel());
}
if(ae.getSource()==b4)
{
t1.setText(b4.getLabel());
}
if(ae.getSource()==b5)
{
t1.setText(b5.getLabel());
}
if(ae.getSource()==b6)
{
t1.setText(b6.getLabel());
}
if(ae.getSource()==b6)
{
t1.setText(b6.getLabel());
}
if(ae.getSource()==b7)
{ t1.setText(b7.getLabel()); }
if(ae.getSource()==b8)
{ t1.setText(b8.getLabel());
}
}
public
static void main(String[] args)
{
new
MyGridLayout();
}
}
Output
Server Client Application
Socket-Java Socket programming is used for communication
between the applicationsrunning on different JRE.
·
Java Socket programming can be
connection-oriented or connection-less.
·
Socket and ServerSocket classes are used for
connection-oriented socket programming and DatagramSocket and DatagramPacket
classes are used for connection-less socket programming.
The client in socket
programming must know two information:
1.
IP
Address of Server, and
2.
Port
number.
Socket class:A socket is simply an endpoint
for communications between the machines. The Socket class can be used to create
a socket.
Important methods
Method
|
Description
|
1)
public InputStream getInputStream()
|
returns
the InputStream attached with this socket.
|
2)
public OutputStream getOutputStream()
|
returns
the OutputStream attached with this socket.
|
3)
public synchronized void close()
|
closes
this socket
|
ServerSocket class-The ServerSocket class can be
used to create a server socket. This object is used to establish communication
with the clients.Important methods
Method
|
Description
|
1)
public Socket accept()
|
returns
the socket and establish a connection between server and client.
|
2)
public synchronized void close()
|
closes
the server socket.
|
Ex.No:27 Creating Client-Server
Application
Aim
To
creating a client-sever application
//server
import java.net.*;
import java.io.*;
class MyServer
{
public static void main(String args[]) throws
Exception
{
ServerSocket
ss=new ServerSocket(3333);
Socket
s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader
br=new BufferedReader(new InputStreamReader(System.in));
String msg=" ";
String msg1=" ";
while(!msg.equals("stop"))
{
msg=din.readUTF();
System.out.println("Client says="+msg);
msg1=br.readLine();
dout.writeUTF(msg1);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
//Client
import java.net.*;
import java.io.*;
class MyClient
{
public static void main(String args[]) throws
Exception
{
Socket
s=new Socket("Localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
BufferedReader
br=new BufferedReader(new InputStreamReader(System.in));
String msg=" ";
String msg1=" ";
while(!msg.equals("stop"))
{
msg=br.readLine();
dout.writeUTF(msg);
dout.flush();
msg1=din.readUTF();
System.out.println("Server says="+msg1);
}
dout.close();
s.close();
}
}
Output
Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is fantastic, let alone the content!
ReplyDeleteMobile app development in Coimbatore
Android app development in Coimbatore
I really liked your blog article. Great.
ReplyDeletejava online training
java training