Академический Документы
Профессиональный Документы
Культура Документы
&
JAVA PROGRAMMING
LAB MANUAL
2011 2012
PREPARED BY
V.USHA CHAITANYA
Assistant Professor
Department Of IT
Dept. of IT
INDEX
Serial No.
Content
Page number
1.
INTRODUCTION TO OOP
2.
PROGRAMMING
3.
4.
ORIENTED PROGRAMMING
5.
ABOUT JAVA
6.
SYSTEM REQUIREMENTS
10
7.
11
8.
13
9.
42
INTERFACE COMPONENTS
10.
63
APPENDIX
around the data being operated upon rather upon the operations themselves. Data and its
functions are encapsulated into a single entity. OOP facilitates creating reusable code that
can eventually save a lot of work. A feature called polymorphism permits to create
multiple definitions for operators and functions. Another feature called inheritance
permits to derive new classes from old ones. OOP introduces many new ideas and
involves a different approach to programming than the procedural programming.
Class: The entire set of data and code of an object can be made of a user defined data
type with the help of a class. One fact, Objects are variables of the type class. Once a
class has been defined, we can create any number of objects belonging to that class.
A class an also be defined as a user defined Data type and Object as an instance of
that class.
A class is thus a collection of objects of similar type.
ex: 1) mango, apple, and orange are members of the class fruit.
2)fruit mango;will create an object mango belonging to the class fruit.
Data Abstraction and Encapsulation: The wrapping up of data and functions in to
a single unit is known as encapsulation. Data encapsulation is the most striking
feature of a class. The data is not accessible to the outside world, and only those
functions which are wrapped in the class can access. This insulation of the data from
direct access by the program is called data hiding.
Abstraction: Abstraction refers to the act of representing essential features without
including the background details or explanations. Since the classes use the concept of
data abstraction, they are known as abstract data type (ADT).
Inheritance: Inheritance is the process by which objects of one class acquire the
properties of objects of another class. Inheritance supports the concept of hierarchical
classification.
For example:
The
bird
'Robin ' is a part of the class 'Flying Birds' which is again a part of the class
'Bird'. The concept of inheritance provides the idea of reusability.
Polymorphism:Polymorphism means the ability to exist in more than one form.
An operation may exhibit different instances.
Dept. of IT
Java History
Java is a general-purpose; object oriented programming language developed by Sun
Microsystems of USA in 1991. Originally called as Oak, by James Gosling one of
the inventors of the language. In 1995 this was renamed as Java. This goal had a
Dept. of IT
strong impact on the development team to make the language simple, portable, highly
reliable and powerful language.
Java also adds some new features. While C++ is a superset of C. Java is neither a
superset nor a subset of C or C++.
FEATURES OF JAVA
Simple: Java is
simple because of its
resemblance in
syntax with C and C++.
Java is simple
because the complex
topics of C and C++ like pointers are eliminated in Java.
Object Oriented: Object-oriented languages allow the programmer to organize
a program so that it closely models the real world in structure and in the
interactions among its components.
Distributed: Java includes pre built-in components or libraries that greatly
facilitate developing of internet applications.
Interpreted: This means that Javas executable files are composed of so-called
bytecodes that are instructions that are executed using Java Runtime
Environment
Robust: Java contains the features that make the task of writing robust
software easier. Then they added features that allow the developer to discover
errors early.
Secure: Java has a multitude ways for dealing with evildoers who would try to
compromise your system using a Java program by providing limitations that
are designed to reduce the chance that simply viewing someones page might
result in harm to your system or data.
Architecture Neutral: Javas bytecodes are designed to be read and
interpretedin exactly the same manneron any computer hardware or
operating system that supports a Java run-time. No translation or conversion is
necessary.
Dept. of IT
local machine, interprets the Java bytecode, and converts it into platform-specific
machine code.
JVM Architecture
Major subsystems
Class loader subsystem: Responsible for loading classes and interfaces
Execution engine: Responsible for the execution of the instructions
specified in the classes.
Other components: 1.Runtime data areas
2. Native interface; interacts with the native libraries
Heap: Holds every object being created by the threads during execution
Program counter register: Points to the next instruction to be executed.
Java stack: Hold the state of each method (java method, not a native method)
invocations for the thread such as the local variables, method arguments, return
values, intermediate results. Each entry in the Java stack is called stack
frames. Whenever a method is invoked a new stack frame is added to the
stack and corresponding frame is removed when its execution is completed. In
JVM there are no registers to store the intermediate values. They are stored in
the java stack itself.
Native method stack: Holds the state of each native method call in an
implementation dependent way.
System Requirements:
Hardware Requirements:
Processor: 2.6GHZ or faster processor
RAM: 512MB RAM and above
Hard Disk: 40 GB free disk space.
Dept. of IT
Software Requirements:
10
Meaning
Identifies the author of a class.
Identifies an exception thrown by a method.
@param
@return
@throws
Same as @exception.
{@value}
11
Week 1:
Program Statement : a)Write a Java program that prints all real solutions to the
quadratic equation ax2+bx+c = 0. Read in a, b, c and use the quadratic formula. If the
discriminant b2-4ac is negative, display a message stating that there are no real
solutions.
Program :
Dept. of IT
12
import java.util.Scanner;
class Quadratic
{
public static void main(String[] args)
{
int a,b,c;
double x,y;
Scanner s=new Scanner(System.in);
System.out.println(Enter the values of a, b, and c:);
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
int k=(b*b)-4*a*c;
if(k<0)
{
System.out.println(No real roots);
}
else if(k>0)
{
double l=Math.sqrt(k);
x=(-b-l)/2*a;
y=(-b+l)/2*a;
System.out.println(Roots of given equation:+x+ +y);
}
else
{
System.out.println(Roots are real and equal);
x=y=(-b)/(2*a);
System.out.println(Roots are+x+,+y);
}
}
}
Compilation:
javac Quadratic.java
Interpretation:
java Quadratic
Classes used:
a. Class Scanner
java.lang.Object
java.util.Scanner
Methods used:
Scanner(InputStream source)
Dept. of IT
13
Constructs a new Scanner, that produces values scanned from the specified input
stream. Bytes from the stream are converted into characters using the underlying
platform's default charset.
Parameters: source - An input stream to be scanned
nextInt()
Scans the next token of the input as an int
Parameters: No parameters
Returns: the integer value scanned from the input
b. Class Math
java.lang.Object
java.lang.Math
Methods used:
sqrt(double a)
Returns the correctly rounded positive square root.
Parameters: a-a value
Returns: the positive square root of a
14
y=Integer.parseInt(input[1]);
Scanner s=new Scanner(System.in);
System.out.println(Enter the value of n:);
int n=s.nextInt();
int z[]=new int[n];
z[0]=x;
z[1]=y;
for(int i=2;i<n;i++)
{
z[i]=z[i-1]+z[i-2];
}
for(int i=0;i<n;i++)
System.out.println(z[i]);
}
}
Compilation:
javac Fibonacci.java
Interpretation:
java Fibonacci 1 1
Classes used:
a. Class Integer
java.lang.Object
java.lang.Number
java.lang.Integer
Methods used:
parseInt(String s)
Parses the string argument as a signed decimal integer. The characters in the string
must all be decimal digits, except that the first character may be an ASCII minus sign
'-' ('\u002D') to indicate a negative value.
Parameters: s-String containing the int representation to be parsed
Returns: the integer value represented by the argument in decimal.
/* Recursive Solution*/
Dept. of IT
15
import java.util.Scanner;
class Fibonacci
{
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println(Enter the value of n:);
int n=s.nextInt();
fiboni f1=new fiboni();
System.out.println(f1.fibon(n));
}
}
class fiboni
{
public int fibon(int a)
{
if(a==0 || a==1)
return 1;
else
return fibon(a-1)+fibon(a-2);
}
}
Compilation: javac Fibonacii.java
Interpretation: java Fibonacii
Week 2:
Program Statement : a)Write a Java program that prompts the user for an integer and
then prints out all prime numbers upto that integer
Program:
import java.util.Scanner;
class prime
{
public static void main(String[] args)
{
int n,p;
Scanner s=new Scanner(System.in);
System.out.println(Enter upto which number prime numbers are
needed);
n=s.nextInt();
Dept. of IT
16
for(int i=1;i<n;i++)
{
p=0;
for(int j=2;j<(i/2);j++)
{
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}
Program Statement: b) Write a Java Program to multiply two matrices
Program :
import java.util.Scanner;
class matmul
{
public static void main(String args[])
{
int a[ ][ ]=new int[3][3];
int b[ ][ ]=new int[3][3];
int c[ ][ ]=new int[3][3];
System.out.println("Enter the first matrix:");
Scanner input=new Scanner(System.in);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j]=input.nextInt();
System.out.println("Enter the second matrix:");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
b[i][j]=input.nextInt();
System.out.println("Matrix multiplication is as follows:");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
for(int i=0;i<3;i++)
{
Dept. of IT
17
for(int j=0;j<3;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println("\n");
}
System.out.println("\n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(b[i][j]+"\t");
}
System.out.println("\n");
}
System.out.println("\n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println("\n");
}
}
}
Program Statement: c) Write a Java program that reads a line of integers and
displays each integer and sum of all integers using StringTokenizer class
Program :
import java.util.StringTokenizer;
import java.util.Scanner;
class tokens
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String sentence=input.nextLine();
String temp;
int k,total=0;
StringTokenizer s1=new StringTokenizer(sentence);
System.out.println("Total Number of tokens:"+s1.countTokens());
while(s1.hasMoreTokens())
{
temp=s1.nextToken();
Dept. of IT
18
k=Integer.parseInt(temp);
total+=k;
System.out.print(k+"\t");
}
System.out.println("Sum of tokens :"+total);
}
}
Classes used:
a. Class StringTokenizer
java.lang.Object
java.util.StringTokenizer
Methods used:
hasMoreTokens()
Tests if there are more tokens available from this tokenizer's string. If this
method returns true, then a subsequent call to nextToken with no argument will
successfully return a token. Returns: true if and only if there is at least one token in
the string after the current position; false otherwise
nextToken()
Returns: the next token from this string tokenizer.
nextLine()
Advances this scanner past the current line and returns the input that was
skipped. This method returns the rest of the current line, excluding any line separator
at the end. The position is set to the beginning of the next line. Since this method
continues to search through the input looking for a line separator, it may buffer all of
the input searching for the line to skip if no line separators are present.
Returns:
Dept. of IT
19
Week 3:
Program Statement :
a) Write a Java program that checks whether a given string is a palindrome or not. Ex:
MADAM is a palindrome.
Program :
import java.io.*;
class Palindrome
{
public static void main(String args[ ])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the string to check for palindrome:");
String s1=br.readLine();
StringBuffer sb=new StringBuffer();
sb.append(s1);
sb.reverse();
String s2=sb.toString();
Dept. of IT
20
if(s1.equals(s2))
System.out.println("palindrome");
else
System.out.println("not palindrome"); }
}
}
Program Statement : b) Write a Java program for sorting a given list of names in
ascending order.
Program :
import java.io.*;
class Test
{
int len,i,j;
String arr[ ];
Test(int n)
{
len=n;
arr=new String[n];
}
String[ ] getArray()throws IOException
{
BufferedReader br=new BufferedReader (new
InputStreamReader(System.in));
System.out.println ("Enter the strings U want to sort----");
for (int i=0;i<len;i++)
arr[i]=br.readLine();
return arr; }
String[ ] check()throws ArrayIndexOutOfBoundsException
{
for (i=0;i<len-1;i++)
{
for(int j=i+1;j<len;j++)
{
if ((arr[i].compareTo(arr[j]))>0)
{
String s1=arr[i];
arr[i]=arr[j];
arr[j]=s1;
}
}
}
return arr;
}
void display()throws ArrayIndexOutOfBoundsException
{
System.out.println ("Sorted list is---");
for (i=0;i<len;i++)
System.out.println(arr[i]);
Dept. of IT
21
}
}
class Ascend
{
public static void main(String args[ ])throws IOException
{
Test obj1=new Test(4);
obj1.getArray();
obj1.check();
obj1.display();
}
}
Program Statement: c) Write a Java program to make frequency count of words in a
given text.
Program :
import java.io.*;
import java.util.*;
class Test
{
public static void main(String a[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the text:");
String s=br.readLine();
int count=0;
StringTokenizer st=new StringTokenizer(s);
System.out.println("Number of tokens:"+st.countTokens());
System.out.println("Enter the word to find its frequency:");
String s1=br.readLine();
while(st.hasMoreTokens())
{
String temp=st.nextToken();
if(temp.equals(s1))
{
count++;
}
}
System.out.println("frequency of the given word "+s1+" is "+count);
}
}
Dept. of IT
22
Week 4:
Program Statement: a) Write a Java program that reads on file name from the user
then displays information about whether the file exists, whether the file is readable,
whether the file is writable ,the type of the file and the length of the file in bytes
Program :
import java.util.Scanner;
import java.io.File;
class FileDemo
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String s=input.nextLine();
File f1=new File(s);
System.out.println("File Name:"+f1.getName());
System.out.println("Path:"+f1.getPath());
System.out.println("Abs Path:"+f1.getAbsolutePath());
System.out.println("Parent:"+f1.getParent());
System.out.println("This file "+(f1.exists()?"Exists": "Does not
exists"));
System.out.println("Is file:"+f1.isFile());
System.out.println("Is Directory:"+f1.isDirectory());
System.out.println("Is Readable:"+f1.canRead());
System.out.println("IS Writable:"+f1.canWrite());
System.out.println("Is Absolute:"+f1.isAbsolute());
System.out.println("File Last Modified:"+f1.lastModified());
System.out.println("File Size:"+f1.length()+"bytes");
System.out.println("Is Hidden:"+f1.isHidden());
}
}
Program Statement : b)Write a Java program that reads a file and displays a file and
displays the file on the screen, with a line number before each line.
Program :
import java.io.*;
class linenum
{
public static void main(String[] args)throws IOException
{
FileInputStream fil;
LineNumberInputStream line;
int i;
try
{
fil=new FileInputStream(args[0]);
line=new LineNumberInputStream(fil);
}
Dept. of IT
23
catch(FileNotFoundException e)
{
System.out.println("No such file found");
return;
}
do
{
i=line.read();
if(i=='\n')
{
System.out.println();
System.out.print(line.getLineNumber()+" ");
}
else
System.out.print((char)i);
}while(i!=-1);
fil.close();
line.close();
}
}
Classes used:
a. Class FileInputStream
java.lang.Object
java.io.InputStream
java.io.FileInputStream
Methods used:
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the
file named by the path name name in the file system.
Parameters:
close()
Closes this file input stream and releases any system resources
associated with the stream.
b. Class LineNumberInputStream
java.lang.Object
java.io.InputStream
Dept. of IT
24
java.io.FilterInputStream
java.io.LineNumberInputStream
Methods used:
LineNumberInputStream(InputStream in)
Constructs a newline number input stream that reads its input from the
specified input stream.
Parameters: in - the underlying input stream.
getLineNumber()
Returns:
read(): Reads the next byte of data from this input stream. The value byte is
returned as an int in the range 0 to 255. If no byte is available because the end
of the stream has been reached, the value -1 is returned. This method blocks
until input data is available, the end of the stream is detected, or an exception is
thrown.
Returns: the next byte of data, or -1 if the end of this stream is reached.
Program Statement : c) Write a Java program that displays the number of
characters, lines and words in a given text file
Program :
import java.io.*;
class wordcount
{
public static int words=0;
public static int lines=0;
public static int chars=0;
public static void wc(InputStreamReader isr)throws IOException
{
int c=0;
boolean lastwhite=true;
while((c=isr.read())!=-1)
{
chars++;
if(c=='\n')
lines++;
if(c=='\t' || c==' ' || c=='\n')
++words;
if(chars!=0)
++chars;
}
}
public static void main(String[] args)
Dept. of IT
25
{
FileReader fr;
try
{
if(args.length==0)
{
wc(new InputStreamReader(System.in));
}
else
{
for(int i=0;i<args.length;i++)
{
fr=new FileReader(args[i]);
wc(fr);
}
}
}
catch(IOException ie){ return; }
System.out.println(lines+" "+words+" "+chars);
}
}
Classes used:
a. Class InputStreamReader
java.lang.Object
java.io.Reader
java.io.InputStreamReader
Methods used:
InputStreamReader(InputStream in)
Creates an InputStreamReader that uses the default charset.
Parameters: in - An InputStream
read()
Reads a single character.
Returns: The character read, or -1 if the end of the stream has been reached
b. Class FileReader
java.lang.Object
java.io.Reader
java.io.InputStreamReader
Dept. of IT
26
java.io.FileReader
Methods used:
FileReader(String fileName)
Creates a new FileReader, given the name of the file to read from.
Parameters: fileName - the name of the file to read from
Week 5:
Program Statement: a) Write a Java program that implements stack ADT
Program :
import java.io.*;
class stack
{
int stck[]=new int[10];
int top;
String res;
stack()
{
top=-1;
}
void push(int item)
{
if(top==9)
System.out.println("stack is full");
else
stck[++top]=item;
}
int pop()
{
if(top<0)
{
System.out.println("stack is underflow");
return 0;
}
else
Dept. of IT
27
return stck[top--];
}
void display()
{
if(top==-1)
System.out.println("Stack is empty");
else
{
System.out.println("Elements in the Stack are:");
for(int i=0;i<=top;i++)
System.out.println(stck[i]);
}
}
}
public class StackADT
{
public static void main(String args[])throws Exception
{
int ch;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
stack s1=new stack();
//System.out.println("Menu\n1.Push\n2.Pop\n3.Display\n");
do
{
System.out.println("Menu is as follows:");
System.out.println("1.Push\n2.Pop\n3.Display\n4.Exit");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1: System.out.println("Enter element to push:");
int p=Integer.parseInt(br.readLine());
s1.push(p);
break;
case 2: int item=s1.pop();
System.out.println("Popped item:"+item);
break;
case 3: s1.display();
break;
default: System.exit(0);
}
}while(ch<4);
}
}
Dept. of IT
28
Program Statement : b)Write a Java program that converts infix expression into
postfix form
Program :
import java.io.*;
class Stack
{
char stack1[]=new char[20];
int top;
void push(char ch)
{
top++;
stack1[top]=ch;
}
char pop()
{
char ch;
ch=stack1[top];
top--;
return ch;
}
int pre(char ch)
{
switch(ch)
{
case '-':return 1;
case '+':return 1;
case '*':return 2;
case '/':return 2;
}
return 0;
}
boolean operator(char ch)
{
if(ch=='/'||ch=='*'||ch=='+'||ch=='-')
return true;
else
return false;
}
boolean isAlpha(char ch)
{
if(ch>='a'&&ch<='z'||ch>='0'&&ch=='9')
return true;
else
return false;
}
void postfix(String str)
{
char output[]=new char[str.length()];
Dept. of IT
29
char ch;
int p=0,i;
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
if(ch=='(')
{
push(ch);
}
else if(isAlpha(ch))
{
output[p++]=ch;
}
else if(operator(ch))
{
if(stack1[top]==0||(pre(ch)>pre(stack1[top]))||
stack1[top]=='(')
{
push(ch);
}
}
else if(pre(ch)<=pre(stack1[top]))
{
output[p++]=pop();
push(ch);
}
else if(ch=='(')
{
while((ch=pop())!='(')
{
output[p++]=ch;
}
}
}
while(top!=0)
{
output[p++]=pop();
}
for(int j=0;j<str.length();j++)
{
System.out.print(output[j]);
}
}
}
class Intopost
{
public static void main(String[] args)throws Exception
{
String s;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Dept. of IT
30
Dept. of IT
31
Week 6:
Program Statement: Write a program to create an interface to display the student
details
Program :
interface student
{
void getdata();
void putdata();
}
class demo implements student
{
int m1,m2,m3,avg,tot;
DataInputStream dis=new DataInputStream(System.in);
public void getdata()
{
try{
System.out.println("Enter Marks of subject1:");
m1=Integer.parseInt(dis.readLine());
System.out.println("Enter Marks of subject2:");
m2=Integer.parseInt(dis.readLine());
System.out.println("Enter Marks of subject3:");
m3=Integer.parseInt(dis.readLine());
avg=(m1+m2+m3)/3;
tot=m1+m2+m3;
}
catch(Exception e)
{
System.out.println("error");
Dept. of IT
32
}
}
public void putdata()
{
System.out.println("Marks of subject 1:"+m1);
System.out.println( "Marks of subject 2:"+m2);
System.out.println( "Marks of subject 3:"+m3);
System.out.println( "Average of three subjects:"+avg);
System.out.println("Total Marks:"+tot);
}
}
class interface1
{
public static void main(String a[])
{
student s;
demo d=new demo();
s=d;
s.getdata();
s.putdata();
}
}
Output:
Dept. of IT
33
Week 7:
Program Statement : a) Write a Java program that creates three threads. First thread
displays Good Morning every one second, the second thread displays Hello every
two seconds and the third thread displays Welcome every three seconds.
Program :
// Using Thread class
class One extends Thread
{
public void run() {
for ( ;; )
{
try{
sleep(1000);
}
catch(InterruptedException e){}
System.out.println("Good Morning");
}
}
}
class Two extends Thread
{
public void run() {
for ( ;; )
{
try{
sleep(2000);
}
catch(InterruptedException e){}
System.out.println("Hello");
}
}
}
class Three extends Thread
{
Dept. of IT
34
35
for ( ;; )
{
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
System.out.println("Good Morning");
}
}
}
class Two implements Runnable
{
Two( )
{
new Thread(this, "Two").start();
try{
Thread.sleep(2000);
}
catch(InterruptedException e){}
}
public void run()
{
for ( ;; )
{
try{
Thread.sleep(2000);
}
catch(InterruptedException e){}
System.out.println("Hello");
}
}
}
class Three implements Runnable
{
Three( )
{
new Thread(this, "Three").start();
try{
Thread.sleep(3000);
}
catch(InterruptedException e){}
}
public void run(){
for ( ;; )
{
try{
Thread.sleep(3000);
}
catch(InterruptedException e){}
System.out.println("Welcome");
}
Dept. of IT
36
}
}
class MyThread
{
public static void main(String args[ ])
{
One obj1=new One();
Two obj2=new Two();
Three obj3=new Three();
}
}
Program Statement : b)Write a Java program that correctly implements producer
consumer problem using the concept of inter thread communication
Program :
class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
Dept. of IT
37
System.out.println("Put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-c to stop");
}
}
Dept. of IT
38
Week 8:
Program Statement : a) Write a Java Program to create an abstract class named
Shape, that contains an empty method named numberOfSides(). Provide three classes
named Trapezoid, Triangle and Hexagon, such that each one of the classes contains
only the method numberOfSides(), that contains the number of sides in the given
geometrical figure.
Program :
abstract class Shape
{
abstract void numberOfSides();
}
class Trapezoid extends Shape{
void numberOfSides()
{
System.out.println(" Trapezoidal has four sides");
}
}
class Triangle extends Shape {
void numberOfSides()
{
System.out.println("Triangle has three sides");
}
}
class Hexagon extends Shape {
void numberOfSides()
{
System.out.println("Hexagon has six sides");
}
}
class ShapeDemo
{
public static void main(String args[ ]) {
Trapezoid t=new Trapezoid();
Triangle r=new Triangle();
Hexagon h=new Hexagon();
Shape s;
s=t; s.numberOfSides();
s=r; s.numberOfSides();
s=h; s.numberOfSides();
}
}
Compilation:
Dept. of IT
39
javac ShapeDemo.java
Interpretation:
java ShapeDemo
Output:
Trapezoidal has four sides
Triangle has three sides
Hexagon has six sides
Dept. of IT
40
Module 2: This module deals with AWT components, Swings, Applets and
Networking.
Week 9:
Program Statement : a) Write an applet that displays a simple message
Program :
import java.awt.*;
import java.applet.*;
/* <applet code="Sim" width=300 height=300> </applet> */
public class Sim extends Applet
{
String msg=" ";
public void init()
{
msg+="Hello";
setBackground(Color.orange);
}
public void start()
{
msg+="Welcome To..";
setForeground(Color.blue);
}
public void paint(Graphics g)
{
msg+="Applet Programming";
g.drawString(msg,200,50);
}}
Dept. of IT
41
Classes used:
a. Class Applet
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
Methods used:
init(): Called by the browser or applet viewer to inform this applet that it has
been loaded into the system.
start(): Called by the browser or applet viewer to inform this applet that it
should start its execution. It is called after the init method and each time the
applet is revisited in a Web page
paint(Graphics g): Paints the container. This forwards the paint to any
lightweight components that are children of this container. If this method is
reimplemented, super.paint(g) should be called so that lightweight components
are properly rendered. If a child component is entirely clipped by the current
clipping setting in g, paint() will not be forwarded to that child.
Parameters: g - the specified Graphics window
setBackground(Color c):Sets the background color of this component.
The background color affects each component differently
and the parts of the component that are affected by the background color may
differ between operating systems.
Parameters: c - the color to become this component's color; if this
parameter is null, then this component will inherit the background color of its
parent
setForeground(Color c):Sets the foreground color of this component.
Parameters: c - the color to become this component's foreground
color; if this parameter is null then this component will inherit the foreground
color of its parent
b. Class Graphics
java.lang.Object
Dept. of IT
42
java.awt.Graphics
Methods used:
drawString(String str, int x, int y):Draws the text given by the specified
string, using this graphics context's current font and color. The baseline of the
leftmost character is at position (x, y) in this graphics context's coordinate
system.
Parameters: str - the string to be drawn. x - the x coordinate.
y - the y coordinate.
Program Statement : b) Develop an applet that receives an integer in one text field,
and computes its factorial Value and returns it in another text field, when the button
named Compute is clicked.
Program :
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=Compute width=300 height=300></applet>*/
public class Compute extends Applet implements ActionListener
{
Button btn,clearbtn;
Label lbl1,lbl2;
TextField tf1,tf2;
public void init()
{
btn=new Button("COMPUTE");
btn.addActionListener(this);
clearbtn=new Button("CLEAR");
clearbtn.addActionListener(this);
tf1=new TextField(30);
tf2=new TextField(30);
lbl1=new Label("NUMBER");
lbl2=new Label("RESULT");
setLayout(new GridLayout(3,2));
add(lbl1); add(tf1);
add(lbl2); add(tf2);
Dept. of IT
43
add(btn); add(clearbtn);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btn)
{
int a=Integer.parseInt(tf1.getText());
int fact=1;
for(int i=1;i<=a;i++)
fact*=i;
tf2.setText(""+fact);
}
else
{
tf1.setText("");
tf2.setText("");
}
}
}
Compilation:
javac Compute.java
Interpretation:
appletviewer Compute.java
Week 10:
Dept. of IT
44
Program Statement : Write a Java program that works as a simple calculator. Use a
grid layout to arrange buttons for the digits and for the + - * % operations.
Add a text field to display the result.
Program :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="Cal" width=300 height=300></applet>*/
public class Cal extends Applet implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
Dept. of IT
45
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
Dept. of IT
46
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}
Compilation:
Interpretation:
javac Cal.java
appletviewer Cal.java
Week 11:
Program Statement : a) Write a Java program for handling mouse events
Program :
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);
Dept. of IT
47
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";
Dept. of IT
48
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Program
Statement :
program to handle
Keyboard events
Write a
Program :
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=keyevents width=400 height=400>
</applet>
*/
public class keyevents extends Applet implements KeyListener
{
String msg=" ";
int X=50,Y=50;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent e)
{
Dept. of IT
49
showStatus("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
showStatus("Key Released");
}
public void keyTyped(KeyEvent e)
{
showStatus("Key Typed");
msg+=e.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString(msg,X,Y);
}
}
Compilation:
javac keyevents.java
Interpretation:
appletviewer keyevents.java
Program Statement : c) Write a program to draw line graphs using the method
drawPolygon()
Program :
import java.applet.*;
import java.awt.*;
Dept. of IT
50
51
Program :
import java.applet.*;
import java.awt.*;
/*<applet code=bargraphs width=400 height=400>
</applet>
*/
public class bargraphs extends Applet
{
public void paint(Graphics g)
{
g.fillRect(180,180,20,20);
g.fillRect(220,140,20,60);
g.fillRect(260,100,20,100);
g.fillRect(300,50,20,150);
g.drawLine(165,200,340,200);
g.drawString("2000",180,216);
g.drawString("2001",220,216);
g.drawString("2002",260,216);
g.drawString("2003",300,216);
}
}
Compilation:
javac bargraphs.java
Interpretation:
appletviewer bargraphs.java
Dept. of IT
52
53
super("Exception Handler");
c=getContentPane();
c.setBackground(Color.red);
btn=new JButton("DIVIDE");
btn.addActionListener(this);
tf1=new JTextField(30);
tf2=new JTextField(30);
tf3=new JTextField(30);
lbl1=new JLabel("NUM 1");
lbl2=new JLabel("NUM 2");
lbl3=new JLabel("RESULT");
p=new JPanel();
p.setLayout(new GridLayout(3,2));
p.add(lbl1); p.add(tf1);
p.add(lbl2); p.add(tf2);
p.add(lbl3); p.add(tf3);
c.add(new JLabel("Division"),"North");
c.add(p,"Center");
c.add(btn,"South");
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btn)
{
try
{
int a=Integer.parseInt(tf1.getText());
int b=Integer.parseInt(tf2.getText());
int c=a/b;
tf3.setText(""+c);
}
catch(NumberFormatException ex)
{
tf3.setText("--");
JOptionPane.showMessageDialog(this,"Only Integer Division");
}
catch(ArithmeticException ex)
{
tf3.setText("--");
JOptionPane.showMessageDialog(this,"Division by zero");
}
catch(Exception ex)
{
tf3.setText("--");
JOptionPane.showMessageDialog(this,"Other Err "+ex.getMessage());
}
}
}
public static void main(String args[])
Dept. of IT
54
{
Division b=new Division();
b.setSize(300,300);
b.setVisible(true);
}
}
Compilation:
javac Division.java
Interpretation:
java Division
Dept. of IT
55
56
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.add(p,BorderLayout.CENTER);
c.add(p1,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btn2)
{
float f=Float.parseFloat(tf2.getText());
float c=(f-32)/1.8f;
tf1.setText(" "+c);
}
if(e.getSource()==btn1)
{
float c=Float.parseFloat(tf1.getText());
float f=(c*1.8f)+32.0f;
tf2.setText(" "+f);
}
if(e.getSource()==btn3)
{
System.exit(0);
}
if(e.getSource()==btn4)
{
tf1.setText(" ");
tf2.setText(" ");
}
}
public static void main(String[] args)
{
temp p=new temp();
p.setSize(400,400);
p.setVisible(true);
}
}
Compilation:
javac temp.java
Interpretation:
java temp
Dept. of IT
57
Week 13:
Program Statement : Write a Java program that finds the area of a circle using
Client-Server network
Program :
import java.net.*;
import java.io.*;
public class server
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket s=ss.accept();
BufferedReader br=new BufferedReader(newInputStreamReader
(s.getInputStream()));
double rad,area;
String result;
rad=Double.parseDouble(br.readLine());
System.out.println("From Client : "+rad);
area=Math.PI*rad*rad;
result="Area is "+area;
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(result);
br.close();
ps.close();
s.close();
ss.close();
}
}
public class client
{
public static void main(String args[]) throws Exception{
Dept. of IT
58
a. Class ServerSocket
Dept. of IT
59
java.lang.Object
java.net.ServerSocket
Week 14:
Program Statement : Write a Java program that allows the user to draw lines,
rectangles and ovals
Program :
import java.awt.*;
import java.applet.*;
/* <applet code="Sam" width=200 height=200>
</applet> */
public class Sam extends Applet
{
public void paint(Graphics g)
{
for(int i=0;i<=250;i++)
{
Color c1=new Color(35-i,55-i,110-i);
g.setColor(c1);
g.drawRect(250+i,250+i,100+i,100+i);
g.drawOval(100+i,100+i,50+i,50+i);
g.drawLine(50+i,20+i,10+i,10+i);
}
}
}
Dept. of IT
60
Reference Books:
Thinking in Java Bruce Eckel
Beginning Java 2-Ivbor horton
Just Java 1.2 -Peter van der linder
Big Java 2 -Cay Horstmann
Introduction to java programming -Y.Daniel Liang
WEB References:
Sun Microsystems, javadoc. The Java API Document Generator.
www.java.com
www.roseindia.net
www.javasoft.com
www.javabeat.net
http://www.acm.org/crossroads/columns/ovp/august2000.html
http://java.sun.com/docs/books/tutorial/java/concepts/
List of Packages:
java.io: Provides for system input and output through data streams,
serialization and the file system.
java.util: Contains the collections framework, legacy collection classes, event
model, date and time facilities, internationalization, and miscellaneous utility
classes (a string tokenizer, a random-number generator, and a bit array).
java.applet: Provides the classes necessary to create an applet and the classes
an applet uses to communicate with its applet context.
Dept. of IT
61
java.awt : Contains all of the classes for creating user interfaces and for
painting graphics and images.
java.awt.event : Provides interfaces and classes for dealing with different
types of events fired by AWT components.
java.net : Provides the classes for implementing networking applications.
javax.swing: Provides a set of "lightweight" (all-Java language) components
that, to the maximum degree possible, work the same on all platforms.
java.sql: Provides classes for dealing with Database operations.
VIVA- QUESTIONS
What is Java?
Java is an object oriented programming language
Is Java invented for Internet?
No, it was developed for programming towards tiny devices
What are java buzzwords?
Java buzzwords explain the important features of java. They are Simple,
Secured, Portable, architecture neutral, high performance, dynamic, robust,
interpreted etc.
Is byte code is similar to .obj file in C?
Yes, both are machine understandable codes
No, .obj file directly understood by machine, byte code requires JVM
What is new feature in control statements comparing with C/C++?
Labeled break and labeled continue are new
What are new features in basic features comparing with C/C++?
Data types: All data types on all machines have fixed size;
Constants: final is used to declare constant
Boolean Type: boolean is new data type in Java which can store true/false
There are no structures/unions/pointers
Is String data type?
No, Strings are classes in Java (Arrays are classes)
What are length and length( ) in Java?
Both gives number of char/elements, length is variable defined in Array class,
length( ) is method defined in String class
What is inheritance?
Extracting the features of a class by another class is called inheritance.
Dept. of IT
62
63
64
Dept. of IT
65
The JVM will internally load the class only once no matter how many times you
import the same class.
Can I have multiple main methods in the same class?
No the program fails to compile. The compiler says that the main method is already
defined in the class.
Can an application have multiple classes having main method?
Yes it is possible. While starting the application we mention the class name to be run.
The JVM will look for the Main method only in the class whose name you have
mentioned. Hence there is not conflict amongst the multiple classes having main
method
What environment variables do I need to set on my machine in order to be able
to run Java programs?
CLASSPATH and PATH are the two variables
How can one prove that the array is not null but empty?
Print args.length. It will print 0. That means it is empty. But if it would have been null
then it would have thrown a NullPointerException on attempting to print args.length.
What is the first argument of the String array in main method?
The String array is empty. It does not have any element.
What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error NoSuchMethodError.
What if I write static public void instead of public static void?
Program compiles without any error.
What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error NoSuchMethodError.
What if the main method is declared as private?
The program compiles properly but at runtime it will give Main method not public.
message.
What is a compilation unit?
A compilation unit is a Java source code
file.
What is the purpose of garbage collection?
Dept. of IT
66
The purpose of garbage collection is to identify and discard objects that are no longer
needed by a program so that their resources may be reclaimed and reused.
Dept. of IT
67