Вы находитесь на странице: 1из 67

INTERNET CONCEPTS

&
JAVA PROGRAMMING
LAB MANUAL
2011 2012

PREPARED BY

V.USHA CHAITANYA
Assistant Professor
Department Of IT

Dept. of IT

Internet concepts & Java Programming

INDEX
Serial No.

Content

Page number

1.

INTRODUCTION TO OOP

2.

BENEFITS OF OBJECT ORIENTED

PROGRAMMING
3.

BASIC C++ KNOWLEDGE

4.

BASIC CONCEPTS OF OBJECT

ORIENTED PROGRAMMING
5.

ABOUT JAVA

6.

SYSTEM REQUIREMENTS

10

7.

JAVA DOCUMENTATION COMMENTS

11

8.

MODULE-1 BASIC PROGRAMMING

13

9.

MODULE-2 GRAPHICAL USER

42

INTERFACE COMPONENTS
10.

63

APPENDIX

OBJECT ORIENTED PROGRAMMING


The object oriented paradigm is built on the foundation laid by the structured
programming concepts. The fundamental change in OOP is that a program is designed
Dept. of IT

Internet concepts & Java Programming

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.

Benefits of object oriented programming:


Inheritance eliminates redundant code and extends the properties of existing
classes.
Data hiding builds secure programs that cannot be invaded by code in other parts
of the program.
User defined data types can be easily constructed.
Builds programs from the standard working modules rather than writing the code
from scratch, which leads to saving of development time and resulting in higher
productivity.
Large complexity in the software development can be easily managed.

Basic C++ Knowledge:


C++ began its life in Bell Labs, where Bjarne Stroustrup developed the language in the
early 1980s. C++ is a powerful and flexible programming language. Thus, with minor
exceptions, C++ is a superset of the C Programming language. The principal
enhancement being the object oriented concept of a class. A Class is a user defined type
that encapsulates many important mechanisms. Classes enable programmers to break an
application up into small, manageable pieces, or objects.

Basic concepts of Object Oriented Programming:


Object: Objects are the basic run time entities in an object-oriented system They
may represent a person, a place, a bank account, a table of data or any item that the
program has to handle.
Dept. of IT

Internet concepts & Java 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

Internet concepts & Java Programming

The process of making an operator to exhibit different behaviors in different


instances is known as operator overloading.
The process of making a method to exhibit different behaviors in different
instances is known as method overloading.

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

Portability: Java programs contain no implementation-dependent aspects, so


the result of executing a series of Java bytecodes should always be the same no
matter on what system they are executed.
High Performance: A just-in-time(JIT) compiler is an interpreter that
remembers the machine code sequences it executes corresponding to the input
bytecodes. Just-in-time compilation may make interpretation of Java bytecodes
almost as efficient as native execution of machine-language code.
Multithreaded: Multithreaded applications allow you to complete more tasks
in a given time and to use a systems resources more efficiently. Java includes
support for multithreaded applications as part of its basic library.
Dynamic: Javas program units, classes, are loaded dynamically (when
needed) by the Java run-time system. Loaded classes are then dynamically
linked with existing classes to form an integrated unit.

Java Virtual Machine(JVM):


One of the key characteristics of Java is platform independence, usually referred
to as write once run anywhere. This is accomplished by the JVM that runs on the
Dept. of IT

Internet concepts & Java Programming

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

More about runtime data areas


Mechanism to hold all kinds of data items such as instructions, object data, local
variable data, return values & intermediate results.
Organization of runtime data areas
How runtime data are stored in the runtime data areas depends on the implementation
of the JVM. Some implementation may enjoy the availability of memory and some
others may not. The abstract nature of runtime data area specification allows the
implementation of JVM in different machines easier.
Some runtime data areas are shared among all the threads in the application, while
some others are too specific to an active thread.
Runtime data areas shared among all threads:
Method area: Holds the details of each class loaded by the class loader
subsystem.
Dept. of IT

Internet concepts & Java Programming

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

Internet concepts & Java Programming

Software Requirements:

Minimum: JDK Kit. Recommended: jdk1.5.0 or jdk1.6.0

Using Javas Documentation Comments:


Java supports three types of comments. The first two are the // and the /* */. The third
type is called a documentation comment. It begins with the character sequence /**. It
ends with */. Documentation comments allow you to embed information about your
program into the program itself. You can then use the javadoc utility program to
extract the information and put it into an HTML file. Documentation comments make
it convenient to document your programs.
Dept. of IT

Internet concepts & Java Programming

10

The javadoc Tags:


The javadoc utility recognizes the following tags:
Tag
@author
@exception

Meaning
Identifies the author of a class.
Identifies an exception thrown by a method.

@param

Documents a methods parameter.

@return

Documents a methods return value.

@throws

Same as @exception.

{@value}

Displays the value of a constant, which must be a


static field.

You can use documentation comments to document classes, interfaces, fields,


constructors, and methods. In all cases, the documentation comment must
immediately precede the item being documented.
What javadoc Outputs
The javadoc program takes as input your Java programs source file and outputs
several HTML files that contain the programs documentation. Information about each
class will be in its own HTML file. javadoc will also output an index and a hierarchy
tree.

An Example that Uses Documentation Comments:


Following is a sample program that uses documentation comments. Notice the way
each comment immediately precedes the item that it describes. After being processed
by javadoc, the documentation about the SquareNum class will be found in
SquareNum.html.
import java.io.*;
/**
* This class demonstrates documentation comments.
* @author Sample
*/
public class SquareNum {
/**
* This method returns the square of num.
* This is a multiline description. You can use
* as many lines as you like.
* @param num The value to be squared.
Dept. of IT

Internet concepts & Java Programming

11

* @return num squared.


*/
public double square(double num) {
return num * num;
}
/**
* This method inputs a number from the user.
* @return The value input as a double.
* @exception IOException On input error.
* @see IOException
*/
public double getNumber() throws IOException {
// create a BufferedReader using System.in
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader inData = new BufferedReader(isr);
String str;
str = inData.readLine();
return (new Double(str)).doubleValue();
}
/**
* This method demonstrates square().
* @param args Unused.
* @return Nothing.
* @exception IOException On input error.
* @see IOException
*/
public static void main(String args[])
throws IOException
{
SquareNum ob = new SquareNum();
double val;
System.out.println("Enter value to be squared: ");
val = ob.getNumber();
val = ob.square(val);
System.out.println("Squared value is " + val);
}
}
Module 1: This module deals with the basic Application programs

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Program Statement: b) The Fibonacci sequence is defined by the following rule.


The first 2 values in the sequence are 1, 1. Every subsequent value is the sum of the 2
values preceding it. Write a Java program that uses both recursive and non-recursive
functions to print the nth value of the Fibonacci sequence.
Program :
/*Non Recursive Solution*/
import java.util.Scanner;
class Fibonacci
{
public static void main(String[] input)
{
int x,y;
x=Integer.parseInt(input[0]);
Dept. of IT

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

the line that was skipped

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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:

name - the system-dependent file name.

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

Internet concepts & Java Programming

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:

he current line number.

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

30

Stack b=new Stack();


System.out.println("Enter input string");
s=br.readLine();
System.out.println("Input String:"+s);
System.out.println("Output String:");
b.postfix(s);
}
}
Classes used:
a. Class BufferedReader
java.lang.Object
java.io.Reader
java.io.BufferedReader
Methods used:
BufferedReader(Reader in)
Creates a buffering character-input stream that uses a default-sized input
buffer.
Parameters: in - A Reader
readLine() Reads a line of text. A line is considered to be terminated by any one of a
line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a
linefeed.
Returns: A String containing the contents of the line, not including any linetermination characters, or null if the end of the stream has been reached.

Dept. of IT

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

34

public void run() {


for ( ;; )
{
try{
sleep(3000);
}
catch(InterruptedException e){}
System.out.println("Welcome");
}
}
}
class MyThread
{
public static void main(String args[ ])
{
Thread t = new Thread();
One obj1=new One();
Two obj2=new Two();
Three obj3=new Three();
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
Thread t3=new Thread(obj3);
t1.start();
try{
t.sleep(1000);
}
catch(InterruptedException e){}
t2.start();
try{
t.sleep(2000);
}
catch(InterruptedException e){}
t3.start();
try{
t.sleep(3000);
}
catch(InterruptedException e){}
}
}
// Using Runnable interface
class One implements Runnable {
One( )
{
new Thread(this, "One").start();
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
public void run() {
Dept. of IT

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

39

javac ShapeDemo.java

Interpretation:
java ShapeDemo
Output:
Trapezoidal has four sides
Triangle has three sides
Hexagon has six sides

Dept. of IT

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

50

/*<applet code=linegraphs width=400 height=400>


</applet>
*/
public class linegraphs extends Applet
{
public void paint(Graphics g)
{
int x[]={0,60,120,180,240,300,360,400};
int y[]={400,280,220,140,160,160,100,420};
int n=x.length;
g.drawPolygon(x,y,n);
}
}
Compilation:
javac linegraphs.java
Interpretation:
appletviewer linegraphs.java

Program Statement : d) Write a program to draw Barcharts


Dept. of IT

Internet concepts & Java Programming

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

Internet concepts & Java Programming

52

Week 12: GUI using SWING Components


Program Statement : Write a program that creates a user interface to perform
integer divisions. The user enters two numbers in the textfields, Num1 and Num2. The
division of Num1 and Num2 is displayed in the Result field when the Divide button is
clicked. If Num1 or Num2 were not an integer, the program would throw a
NumberFormatException. If Num2 were Zero, the program would throw an
ArithmeticException Display the exception in a message dialog box.
Program :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Division extends JFrame implements ActionListener
{
Container c;
JButton btn;
JLabel lbl1,lbl2,lbl3;
JTextField tf1,tf2,tf3;
JPanel p;
Division()
{
Dept. of IT

Internet concepts & Java Programming

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

Internet concepts & Java Programming

54

{
Division b=new Division();
b.setSize(300,300);
b.setVisible(true);
}
}
Compilation:
javac Division.java
Interpretation:
java Division

Dept. of IT

Internet concepts & Java Programming

55

Program Statement : Create a GUI application to convert Fahrenheit to Celsius and


vice versa using swing components
Program :
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class temp extends JFrame implements ActionListener
{
Container c;
JButton btn1,btn2,btn3,btn4;
JLabel lb1,lb2;
JTextField tf1,tf2;
JPanel p,p1;
public temp()
{
super("Temperature Conversions");
c=getContentPane();
c.setBackground(Color.cyan);
btn1=new JButton("CONVERT TO FAHRENHEIT");
btn1.addActionListener(this);
btn2=new JButton("CONVERT TO CELSIUS");
btn2.addActionListener(this);
btn3=new JButton("CANCEL");
btn3.addActionListener(this);
btn4=new JButton("CLEAR");
btn4.addActionListener(this);
tf1=new JTextField(5);
tf2=new JTextField(5);
lb1=new JLabel("CELSIUS");
lb2=new JLabel("FAHRENHEIT");
p=new JPanel();
p1=new JPanel();
p.setLayout(new GridLayout(3,2));
p.add(lb1);p.add(tf1);
p.add(lb2) ;p.add(tf2);
p1.add(btn1);p1.add(btn2);p1.add(btn3);p1.add(btn4);
p1.setLayout(new FlowLayout());
Dept. of IT

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

58

Socket s=new Socket("localhost",2000);


BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
String rad;
System.out.println("Enter radius of the circle ");
rad=br.readLine();
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(rad);
BufferedReader fs=new BufferedReader (newInputStreamReader
(s.getInputStream()));
String result=fs.readLine();
System.out.println("From Server : "+result);
br.close();
fs.close();
ps.close();
s.close();
}
}

a. Class ServerSocket
Dept. of IT

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

62

Why inheritance is important?


Reusability is achieved through inheritance
Can we achieve multiple inheritances in Java?
Multiple inheritance in JAVA is achieved through interfaces.
What is interface?
Interface is collection of final variables and abstract methods
(We need not give final and abstract keywords and By default they are public
methods)
What is the difference between class and interface?
Class contains implemented methods, but interface contains only method declarations
but not their implementations.
What is polymorphism?
Existence of an entity in multiple forms is called polymorphism. Poly(= many)
Morphism(=forms)
Can we achieve run time polymorphism in Java?
Yes, also called as dynamic polymorphism. Possible by dynamic method dispatch
What is dynamic method dispatch?
When you assign object of sub class for the super class instance, similar methods of
super class are hidden
What is overloading?
Same method name can be used with different type and number of arguments (in same
class)
What is overriding?
Same method name, similar arguments and same number of arguments can be
defined in super class and sub class. Sub class methods override the super class
methods.
What is the difference between overloading and overriding?
Overloading related to same class and overriding related sub-super class
Compile time polymorphism achieved through overloading, run time polymorphism
achieved through overriding
What is keyword?
Java reserved word which should is not used as variable/class-name (e.g.: break, for,
if, while etc)
What is final keyword?
Used before variables for declaring constants
Used before methods for preventing from overriding
Used before class-name for preventing from inheritance
What is static keyword?
Used before variable for defining shared variables
Dept. of IT

Internet concepts & Java Programming

63

Used before method for defining class-level methods, these methods


can be called without creating objects (e.g.: parseInt method of Integer class)
What is abstract keyword?
Used for creating abstract class, class which doesn't have any instance
What is this keyword?
To call current class variables and current class methods we can use this key word
What is this( )?
Used for calling another constructor of current class
What is super keyword?
To call super class variables and super class methods we can use super key word
What is super( )?
Used for calling of super class constructor and it should be first executable statement
in sub class constructor
What is CLASSPATH?
It is an environment variable which is used for defining the location of class files
What is jar?
Jar stands for Java archive files, compressed set of class files and can be used in
CLASSPATH
What is the meaning of import java.awt.*;?
Import all the classes and interfaces in the java.awt.package.
Is it necessary to give import java.awt.event.*;, when already import java.awt.*
given?
Yes, import java.awt.* doesn't imports event package defined in java.awt. package.
What is the difference between throw and throws keywords?
throw keyword is used for invoking an exception (For raising)
throws keyword lists exception names which can be ignored from the method
execution
What is the difference between final and finally?
final is used for defining constants
finally is used for executing code after completion of exception handler
What happen is we not handle sub class exception first?
Generates compile time error saying that unreachable code is defined in the program
What is a process?
Program under execution is called process
Can you name any methods of Thread class?
currentThread( ), setName( ), getName( ), setPriority( ), getPriority( ), join( ), isAlive(
)
Dept. of IT

Internet concepts & Java Programming

64

What is join( ) method of Thread?


Combines two or more threads running process and wait till their execution is
completed
What is an applet?
Applet is a java program which runs via java-enabled browser
Is graphics possible only in applets?
No, stand alone program frames can also display graphics
What is the relation between java and Internet?
With the help of java applets, we can write programming for Internet
Which package is required to write GUI (Graphical User Interface) programs?
Java.awt
Which package is required to write Applets?
Java.applet
What is event handling?
A procedure which gives functionality for the events
How to implement event handling?
By using interfaces like ActionListener, MouseListener
What is the method available in ActionListener Interface?
public void action performed(ActionEvent e)
How to pass parameters to Applets?
By using PARAM tag.
What are different types of inner classes?
Nested top-level classes, Member classes, Local classes, Anonymous classes
What are Checked and UnChecked Exception?
Making an exception checked forces client programmers
to deal with the possibility that the exception will be thrown. eg, IOException
thrown by java.io.FileInputStreams read() method
With an unchecked exception, however, the compiler doesnt force client
programmers either to catch the exception or declare it in a throws clause. In
fact, client programmers may not even know that the exception could be
thrown. eg, StringIndexOutOfBoundsException thrown by Strings charAt()
method
Can I import same package/class twice? Will the JVM load the package twice at
runtime?

Dept. of IT

Internet concepts & Java Programming

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

Internet concepts & Java Programming

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

Internet concepts & Java Programming

67

Вам также может понравиться