You are on page 1of 84

ADVANCE TECHNOLOGIES LAB PRACTICALS

SUBMITTED TO: MR. GAURAV GAMBHIR

SUBMITTED BY: Gourav Meet

INTAKE NO.: 8614127

LEVEL: 2

BRANCH: CSE(G1)

1
INDEX
CSE-311: Advance Technologies (Pr.)
S. AIM DATE SIGNATURE
No.

1 Learn the basics of Java and its Development Tools. 29/07/2016

2. Write a JAVA program to print Hello World. 29/07/2016

3. Write a Java program to show addition, subtraction, multiplication 29/07/2016


and division of two numbers [num1=90, num2=10].

4. Using if statement write a program to check whether one number 29/07/2016


is greater than, less than or equal to another number.

5. Using for loop write counting from 1 to 100 in ascending order. 05/08/2016

6. Write a program to calculate area and perimeter (circumference) of 05/08/2016


circle with radius 12.

7. Write a program to print default value for each primitive data type. 05/08/2016

8. Using command line argument, write a program to take input from 12/8/2016
user for example his/her name and print Hello <his/her name>.

9. Using arrays write a program to store number of days in each 12/8/2016


month, then print April has 30 days.

10. Write a program to show average of 10 floating point numbers. 12/8/2016

11. Using 2D array write a program to show desired output. 19/08/2016

12. Using ternary operator write a program to show the absolute value 19/08/2016
of -10.

13. Write a program to show which months fall in winter season, 19/08/2016
spring season, summer season, and autumn season.

14. Using loop write a program to print 1 to 10, in English words. [i.e 26/08/2016
One , Two Ten]

15. Using for loop write a program to show desired output. 26/08/2016

2
16. Write a Java class to create a box having width, height and depth, 26/08/2016
using java objects create two boxes of different dimensions and
calculate their volume.

17. Use constructors to create two boxes and calculate their volume. 02/09/2016

18. Give an example of a. Method overloading in java b. Constructor 02/09/2016


overloading in java

19. Write an example to show use of this keyword 02/09/2016

a. With variables b. With methods c. With constructors

20. Write a program to demonstrate 09/09/2016

a. Call by value b. Call by reference

21. Using recursion write a program to show factorial of a number. 09/09/2016

22. Write a program to show the difference between various access 09/09/2016
modifiers i.e public, private, protected and default.

23. Write a program to show: a. Difference between static variable 30/09/2016


and not static variable. b. Difference between static method and
not static method. c. Significance of static block.

24. Create three arrays of different dimensions and write a program to 30/09/2016
display their size.

25. Can we define a class inside a class in java, if yes show with an 30/09/2016
example.

26. Write a program to store your name twice in two strings i.e one in 30/09/2016
upper case and another in lower case, check weather both strings
are equal, find the length of string and character at index 3.

27. Give an example of inheritance in Java show 30/09/2016

a. Method inheritance b. Variable inheritance.

28. Write an example to show use of super keyword 07/10/2016

a. with variables b. with methods c. with constructors

29. Give an example of a. Method overloading in java 07/10/2016

b. Can we do Constructor overloading in java c. Method


Overriding in java.

3
30. Demonstrate use of final a. With variables b. With methods in 07/10/2016
Java.

31. Can we declare a method without body in Java, if yes how? What 07/10/2016
are abstract classes.

32. How we create package in java and how do we import them, give 14/10/2016
an example.

33. Give an example to show difference between abstract class and 14/10/2016
interface.

34. Write a program to take two input numbers from user using 21/10/2016
scanner class and display their modulus.

35. Generate an editor screen containing menus, dialog boxes etc using 21/10/2016
Java.

36. Create an applet with a text field and three buttons. When you 21/10/2016
press each button, make some different text appear in the text field.

37. Create an applet with a button and a text field. Write a 28/10/2016
handleEvent( ) so that if the button has the focus, characters typed
into it will appear in the text field.

38. Java Networking Java Sockets and RMI. 28/10/2016

39. Using JAVA develop a front end for a contact management 28/10/2016
program using a flat file database. DB needs to be distributed or
centralized.

4
EXPERIMENT NO : 1

AIM : Learn the basics of Java and its Development Tools.

INTRODUCTION

Java is a general-purpose computer programming language that is concurrent, class-


based, object-oriented, and specifically designed to have as few implementation dependencies as
possible.

It is intended to let application developers "write once, run anywhere" (WORA),] meaning
that compiled Java code can run on all platforms that support Java without the need for
recompilation.
Java applications are typically compiled to bytecode that can run on any Java virtual
machine (JVM) regardless ofcomputer architecture. As of 2015, Java is one of the most popular
programming languages in use, particularly for client-server web applications, with a reported 9
million developers.

Java was originally developed by James Gosling at Sun Microsystems (which has since
been acquired by Oracle Corporation) and released in 1995 as a core component of Sun
Microsystems' Java platform. The language derives much of its syntax from C and C++, but it
has fewer low-level facilities than either of them.

5
HISTORY

YEAR NAME
1991 Oak
1995 Java

James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. Java was originally designed for interactive television, but it was too advanced for the
digital cable television industry at the time. The language was initially called Oak after
an oak tree that stood outside Gosling's office.
Later the project went by the name Green and was finally renamed Java, from Java
coffee. Gosling designed Java with a C/C++-style syntax that system and application
programmers would find familiar.
Sun Microsystems released the first public implementation as Java 1.0 in 1995. It promised
"Write Once, Run Anywhere" (WORA), providing no-cost run-times on popular platforms.
Fairly secure and featuring configurable security, it allowed network- and file-access
restrictions. Major web browsers soon incorporated the ability to run Java applets within web
pages, and Java quickly became popular.

The Java 1.0 compiler was re-written in Java by Arthur van Hoff to comply strictly with the
Java 1.0 language specification. With the advent of Java 2 (released initially as J2SE 1.2 in
December 1998 1999), new versions had multiple configurations built for different types of
platforms. J2EE included technologies and APIs for enterprise applications typically run in
server environments, while J2ME featured APIs optimized for mobile applications.

The desktop version was renamed J2SE. In 2006, for marketing purposes, Sun renamed
new J2 versions as
Java EE
Java ME, and
Java SE, respectively.

On November 13, 2006, Sun released much of Java as free and open-source software, (FOSS),
under the terms of the GNU General Public License (GPL).
On May 8, 2007, Sun finished the process, making all of Java's core code available under free
software/open-source distribution terms, aside from a small portion of code to which Sun did not
hold the copyright.

6
Features of Java

1. Simple
2. Object-Oriented
3. Platform Independent
4. Secured
5. Robust
6. Architecture Neutral
7. Portable
8. High Performance
9. Distributed
10.Multi-threaded

Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection
in java.

Object-oriented
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent

7
A platform is the hardware or software environment in which a program runs. There are two
types of platforms software-based and hardware-based. Java provides software-based
platform. The Java platform differs from most other platforms in the sense that it's a
software-based platform that runs on top of other hardware-based platforms.
It has two components:
1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS etc.


Java code is compiled by the compiler and converted into bytecode.This bytecode is a
platform independent code because it can be run on multiple platforms i.e. Write Once and
Run Anywhere(WORA).

Secured
Java is secured because:
No explicit pointer
Programs run inside virtual machine sandbox.

8
Classloader- adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate access
right to objects.
Security Manager- determines what resources a class can access such as reading and
writing to the local disk.
These security are provided by java language. Some security can also be provided by
application developer through SSL,JAAS,cryptography etc.

Robust
Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java. There is
exception handling and type checking mechanism in java. All these points makes java
robust.

Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.

Portable
We may carry the java bytecode to any platform.

High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)

9
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it shares the same memory. Threads are important
for multi-media, Web applications etc.
Next Topic
Java Runtime Environment (JRE)

The Java Runtime Environment (JRE), also known as Java Runtime, is part of the Java
Development Kit (JDK), a set of programming tools for developing Java applications.The
Java Runtime Environment provides the minimum requirements for executing a Java
application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files.

Some of them are :


Eclipse IDE
NetBeans IDE
Borland JBuilder Personal Edition
Mac OS X Project Builder
BlueJ
Java Technologies to Use in Web Applications

There are too many Java technologies to list in one article, so this article will describe only the
ones most frequently used.

Java Servlet API

The Java Servlet API lets you define HTTP-specific classes. A servlet class extends the
capabilities of servers that host applications that are accessed by way of a request-response
programming model. Although servlets can respond to any type of request, they are commonly
used to extend the applications hosted by web servers. For instance, you might use a servlet to
get the text input from an online form and print it back to the screen in an HTML page and
format, or you might use a different servlet to write the data to a file or database instead. A
servlet runs on the server side -- without an application GUI or HTML user interface (UI) of its
own. Java Servlet extensions make many web applications possible.
Figure 1 shows clients talking to Java Servlet extensions. Clients may range in complexity from
simple HTML forms to sophisticated Java technology-based applets.

Java Message Service API


Messaging is a method of communication between software components or applications. A
messaging system is a peer-to-peer facility. In other words, a messaging client can send

10
messages to and receive messages from any other client. Each client connects to a messaging
agent that provides facilities for creating, sending, receiving, and reading messages. By
combining Java technology with enterprise messaging, the Java Message Service (JMS) API
provides a powerful tool for solving enterprise computing problems.
Enterprise messaging provides a reliable, flexible service for the exchange of business data
throughout an enterprise. The JMS API adds to this a common API and provider framework that
enables the development of portable message-based applications in the Java programming
language.
The JMS API improves programmer productivity by defining a common set of messaging
concepts and programming strategies that all JMS technology-compliant messaging systems will
support.
.

JavaMail API and the JavaBeans Activation Framework

Web applications can use the JavaMail API to send email notifications. The API has two parts:
an application-level interface that the application components use to send email and a service
provider interface. Service providers implement particular email protocols, such as SMTP.
Several service providers are included with the JavaMail API package, and others are available
separately. The Java EE platform includes the JavaMail extension with a service provider that
allows application components to send email.

Java API for XML Processing


The Java API for XML Processing (JAXP), part of the Java SE platform, supports the processing
of XML documents using the Document Object Model (DOM), the Simple API for XML (SAX),
and Extensible Stylesheet Language Transformations (XSLT). JAXP enables applications to
parse and transform XML documents independent of a particular XML-processing
implementation.
JAXP also provides namespace support, which lets you work with schemas that might otherwise
have naming conflicts. Designed to be flexible, JAXP lets you use any XML-compliant parser or
XSL processor from within your application and supports the W3C schema.
.

NetBeans IDE
NetBeans IDE is free and open source. This IDE is written in the Java programming language
and provides the services common to desktop applications, such as window and menu
management, settings storage, and so forth. It is also the first IDE to fully support JDK 5.0
features. In addition, it supports web tools, including the NetBeans IDE Enterprise Pack, which
adds everything you need to immediately start writing, testing, and debugging Java technology-
based web applications.
The pack provides visual design tools for Unified Modeling Language (UML) modeling, XML
schema creation, modification, and visualization, as well as development of secure, identity-
enabled web services.

11
BASICS OF CLASS IN JAVA
CODING :

class A
{
public void show()
{
System.out.println("Welcome in Java");
}
}
class B
{
public void show()
{
System.out.println("You are entered in world of Java");
}
}
class Shivani
{
public static void main(String[] args)
{
A ob=new A();
B ob1=new B();
ob1.show();
ob.show();
System.out.println("Enjoy Java");
}
}
OUTPUT :

12
EXPERIMENT NO.2
AIM: Write a Java program to print Hello World.
CODING:

public class Q1

public static void main(String args[])

System.out.println("hello world");

o/p:

13
EXPERIMENT NO.3
AIM: Write a Java program to show addition, subtraction, multiplication
and division of two numbers [num1=90, num2=10]

CODING:
public class Q2

public static void main(String args[])

{int num1=90,num2=10;

int sum=num1+num2;

int dif=num1-num2;

int mul=num1*num2;

int div=num1/num2;

System.out.println("sum is:"+sum);

System.out.println("dif is:"+dif);

System.out.println("mul is:"+mul);

System.out.println("div is:"+div);

o/p:

14
EXPERIMENT NO.4

AIM: Using if statement write a program to check whether one number is


greater than, less than or equal to another number.

CODING:
public class Q3

public static void main(String args[])

int x=5;

int y=6;

if(x<y)

System.out.println("y is greater");

if(x>y)

System.out.println("x is greater");

if(x==y)

System.out.println("equal");

15
o/p:

16
EXPERIMENT NO.5
AIM:Using for loop write counting from 1 to 100 in ascending order.
CODING:
public class Q4

{public static void main(String args[])

int n=1;

for(n=1;n<=100;n++)

System.out.println(n);

o/p:

17
EXPERIMENT NO.6
AIM:Write a program to calculate area and perimeter of circle with
radius 12.
CODING:
public class Q5

public static void main(String args[])

double r=12.0;

double PI=3.14;

double area=PI*r*r;

double cir=2*PI*r;

System.out.println("area of circle:"+area);

System.out.println("circum of circle:"+cir);

o/p:

18
EXPERIMENT NO.7
AIM:Write a program to print default value for each primitive data type.
CODING:

public class Q6

static byte b;

static short s;

static int i;

static long l;

static float f;

static double d;

static boolean bo;

static char c;

public static void main(String args[])

{System.out.println("byte:"+b);

System.out.println("short:"+s);

System.out.println("int:"+i);

System.out.println("long:"+l);

System.out.println("float:"+f);

System.out.println("double:"+d);

System.out.println("boolean:"+bo);

System.out.println("char:"+c);

19
}

o/p:

20
EXPERIMENT NO.8
AIM:Using command line argument, write a program to take input from
user for example his/her name and print Hello <his/her name>.
CODING:

public class Q7

public static void main(String args[])

System.out.println("Hello"+args[0]+" "+args[1]);

Output:

21
EXPERIMENT NO.9

AIM:Using arrays write a program to store number of days in each month,


then print April has 30 days.
CODING:

public class Q8

public static void main(String args[])

int month_days[];

month_days = new int[12];

month_days[0] = 31;

month_days[1] = 28;

month_days[2] = 31;

month_days[3] = 30;

month_days[4] = 31;

month_days[5] = 30;

month_days[6] = 31;

month_days[7] = 31;

month_days[8] = 30;

month_days[9] = 31;

month_days[10] = 30;

month_days[11] = 31;

System.out.println("April has " + month_days[3] + " days.");

22
Output:

23
EXPERIMENT NO.10

AIM:Write a program to show average of 10 floating point numbers.

CODING:
class Q9

public static void main(String[] args)

double[] numbers = new double[]{1.0,2.1,3.2,4.3,5.4,5.6,1.9,6.6,5.4,3.5};

double sum = 0;

for(int i=0; i < numbers.length ; i++)

sum = sum + numbers[i];

double average = sum / numbers.length;

System.out.println("Average value of 10 floating point numbers is : " + average);

Output:

24
EXPERIMENT NO.11
AIM:Using 2D array write a program to show following output
01234
56789
10 11 12 13 14
15 16 17 18 19
CODING:
class Q10

public static void main(String[] args)

int[][] values = new int[4][];

values[0] = new int[5];

values[0][0] = 0;

values[0][1] = 1;

values[0][2] = 2;

values[0][3] = 3;

values[0][4] = 4;

values[1] = new int[5];

values[1][0] = 5;

values[1][1] = 6;

values[1][2] = 7;

values[1][3] = 8;

values[1][4] = 9;

values[2] = new int[5];

values[2][0] = 10;

25
values[2][1] = 11;

values[2][2] = 12;

values[2][3] = 13;

values[2][4] = 14;

values[3] = new int[5];

values[3][0] = 15;

values[3][1] = 16;

values[3][2] = 17;

values[3][3] = 18;

values[3][4] = 19;

for (int[] array : values) {

for (int element : array) {

System.out.print(element);

System.out.print(" ");

System.out.println();

Output:

26
EXPERIMENT NO.12
AIM:Using ternary operator write a program to show the absolute value
of -10.
CODING:
public class Q11

public static void main(String args[])

int i,k;

i=10;

k=i<0?-i:i;

System.out.println(i+" is " +k);

Output:

27
EXPERIMENT NO.13
AIM:Write a program to show which months fall in winter season,
spring season, summer season, and autumn season.
CODING:

class Example12

public static void main(String[] args)

int month;

String season = null;

month = Integer.parseInt(args[0]);

if(month==12||month==1||month==2)

season = "Winter";

System.out.println("The month falls in :" + season);

if(month==3||month==4||month==5)

season = "Spring";

System.out.println("The month falls in :" + season);

if(month==6||month==7||month==8)

28
{

season = "Summer";

System.out.println("The month falls in :" + season);

if(month==9||month==10||month==11)

season = "Autumn";

System.out.println("The month falls in :" + season);

OUTPUT :

29
EXPERIMENT NO.14
AIM:Using loop write a program to print 1 to 10, in English words.
[i.e. One , Two Ten] using for loop and switch.

CODING:
public class count {

public static void main(String[] args)


{
for(int i=1;i<11;i++)
{
switch(i)
{
case 1:System.out.println("One");
break;
case 2:System.out.println("Two");
break;
case 3:System.out.println("Three");
break;
case 4:System.out.println("Four");
break;
case 5:System.out.println("Five");
break;
case 6:System.out.println("Six");
break;
case 7:System.out.println("Seven");
break;
case 8:System.out.println("Eight");
break;
case 9:System.out.println("Nine");
break;
case 10:System.out.println("Ten");
break;
default:System.out.println("Enter correct no.");
break;
}
}

30
OUTPUT :

31
EXPERIMENT NO.15
AIM:Using for loop write a program to show following output
01
23
45
67
89
CODING:

public class Entry {


public static void main(String[] args) {

int i;
for(i=0;i<10;i++)
{
System.out.print(i + " ");
if(i%2==0)
{
continue;
}
System.out.println("\n");
}
}
}

OUTPUT :

32
EXPERIMENT NO.16
AIM:Write a Java class to create a box having width, height and
depth, using java objects create two boxes of different dimensions
and calculate their volume.
CODING:

class Box

double width;

double height;

double depth;

public class Entry

{public static void main(String[] args)

Box obj=new Box();

Box obj2=new Box();

Double vol;

obj.height=20;

obj.width=30;

obj.depth=50;

vol=obj.height*obj.width*obj.depth;

System.out.println("volume of 1st box "+vol+" cube ");

obj2.height=20;

33
obj2.width=18;

obj2.depth=10;

vol=obj2.height*obj2.width*obj2.depth;

System.out.println("Volume of 2nd box is "+vol+" cube ");

Output Screenshot:-

34
EXPERIMENT NO.17
AIM:In above question use constructors to create two boxes and
calculate their volume.
CODING:

class Box

double width;

double height;

double depth;

public Box() //default constructor

width=10;

height=30;

depth=20;

public Box(double width,double height,double depth) //constructor with arguments

this.width=width;

this.height=height;

this.depth=depth;

double volume()

35
return width*height*depth;

public class Entry

public static void main(String[] args)

Box obj=new Box();

Box obj2=new Box(10,10,10);

System.out.println("volume of 1st box "+obj.volume()+" cube ");

System.out.println("Volume of 2nd box is "+obj2.volume()+" cube ");

OUTPUT :

36
EXPERIMENT NO.18
AIM:Give an example of
a. Method overloading in java
b. Constructor overloading in java

CODING:

METHOD OVERLOADING
class Add

int i,j,k,c;

public Add()

i=10;

j=20;

void Add()

k=i+j;

void Add(int a,int b)

c=a+b;

37
public class Entry

public static void main(String[] args)

Add a1=new Add();

a1.Add();

System.out.println(a1.k);

a1.Add(5, 6);

System.out.println(a1.c);

OUTPUT :

38
CONSTRUCTOR OVERLOADING

class Box

double width;

double height;

double depth;

public Box() //default constructor

width=10;

height=30;

depth=20;

public Box(double width,double height,double depth) //constructor with arguments

this.width=width;

this.height=height;

this.depth=depth;

double volume()

return width*height*depth;

public class Entry

39
{

public static void main(String[] args)

Box obj=new Box();

Box obj2=new Box(10,10,10);

System.out.println("volume of 1st box "+obj.volume()+" cube ");

System.out.println("Volume of 2nd box is "+obj2.volume()+" cube ");

OUTPUT :

40
EXPERIMENT NO.19
AIM:Write an example to show use of this keyword
a. with variables
b. with methods
c. with constructors
CODING:

WITH METHODS

class Great

int i,j,k;

void add()

k=i+j;

System.out.println(" in default argument portion ");

void add(int i,int j)

System.out.println("in two argument constructor portion");

this.add();

public class Entry

public static void main(String[] args)

41
{

Great g=new Great();

g.add(2,3);

OUTPUT :

42
WITH VARIABLES AND CONSTRUCTOR
class Add

int i,j,k;

Add(int i,int j)

this.i=i;

this.j=j;

k=i+j;

System.out.println(k);

Add()

this(10,30);

public class Entry

public static void main(String[] args)

Add object=new Add();

Add obj=new Add(2,3);

43
OUTPUT :

44
EXPERIMENT NO.20
AIM:Write a program to demonstrate
a.Call by value
b.Call by reference
CODING:

public class Test

{
int i,j;
void fun(inti,intj)
{
this.i=i*2;
this.j=j/2;

void fun(Test b)
{
b.i=b.i*2;
b.j=b.j/2;
}

45
BY CALL BY VALUE

public class CallbyValue


{
publicstaticvoid main(String[] args)
{
Test t=new Test();
int a=10;
int b=20;
System.out.println("value of a"+a);
System.out.println("value of b"+b);
t.fun(a, b);

System.out.println("value of a"+a);

System.out.println("value of b"+b);
//no change in call by value now we ll do by call by refrence

OUTPUT :

46
CALL BY REFRENCE
public class Test

int i,j;

void fun(inti,intj)
{
this.i=i*2;
this.j=j/2;
}

void fun(Test b)

b.i=b.i*2;
b.j=b.j/2;
}

public classCallbyRefrence {

publicstaticvoid main(String[] args)

Test t=new Test();

t.fun(10,20);

System.out.rintln("value of a"+t.i);

System.out.println("value of b"+t.j);

t.fun(t);

System.out.println("value of a"+t.i);

System.out.println("value of b"+t.j);

47
OUTPUT :

48
EXPERIMENT NO.21
AIM:Using recursion write a program to show factorial of a number.
CODING:

public class facto {

public static void main(String[] args)


{
factorial f=new factorial();
System.out.println("The factorial of 4: "+f.fact(4));
System.out.println("The factorial of 5: "+f.fact(5));
System.out.println("The factorial of 6: "+f.fact(6));
}
}
public class factorial
{
int fact(int n)
{
int result;
if(n==1)
return 1;
result=fact(n-1)*n;
return result;
}
}

OUTPUT :

49
EXPERIMENT NO.22
AIM:Write a program to show the difference between various
access modifiers i.e. public, private, and protected and default.
CODING:
Default Access Modifier:
class A
{
int i, j; // default access specifier
void setij(int x,int y)
{
i=x;
j=y;
}
}
class B extends A {
int total;

void sum()
{
total=i+j;
}

}
class Access {
public static void main(String args[]) {
B subob=new B();
subob.setij(10,12);
subob.sum();

System.out.println("Total is " + subob.total);


}
}
OUTPUT:

50
Public Access Modifier:

class A
{
int i;
public int j; // public to A
void setij(int x,int y)
{
i=x;
j=y;
}
}
//A's j is accessible here.
class B extends A {
int total;
void sum()
{
total=i+j; // j will be accessible here
}
}
class Access {
public static void main(String args[]) {
B subob=new B();
subob.setij(10,12);
subob.sum();

System.out.println("Total is " + subob.total);


}
}

OUTPUT:

51
Protected Access Modifier:

pakcage p1;
class A
{
protected int i;
int j;
void setij(int x,int y)
{
i=x;
j=y;
}
}
class B extends A {
int total;

void sum()
{
total=i+j;
}

}
class Accesss {
public static void main(String args[]) {
B subob=new B();
subob.setij(10,12);
subob.sum();

System.out.println("Total is " + subob.total);


}
}

OUTPUT:

52
Private Access Modifier:

class A
{
int i;
private int j; // private to A
void setij(int x,int y)
{
i=x;
j=y;
}
}

//A's j is not accessible here.

class B extends A {
int total;

void sum()
{
total=i+j; // ERROR j will not be accessible here
}

}
class Access {
public static void main(String args[]) {
B subob=new B();
subob.setij(10,12);
subob.sum();

System.out.println("Total is " + subob.total);


}
}

OUTPUT:

53
EXPERIMENT NO.23
AIM:Write a program to show
a. Difference between static variable and not static variable
b. Difference between static method and not static method
c. Significance of static block.
CODING:

public class StaticDemo


{
static int a=2;
static int b;
static void display(int x)
{
System.out.println("X is:"+ x);
System.out.println("A is:"+ a);
System.out.println("B is:"+ b);
}
public static void main(String[] args)
{
display(10);
}}

OUTPUT :

54
CODING:

public class withoutStaticDemo


{
int a=2;
int b;

void display(int x)
{
System.out.println("X is:"+ x);
System.out.println("A is:"+ a);
}
public static void main(String[] args)
{
withoutStaticDemo d=new withoutStaticDemo();
d.display(10);
}
}

OUTPUT :

55
EXPERIMENT NO.24
AIM:Create three arrays of different dimensions and write a
program to display their size.
CODING:

public class Entry


{

public static void main(String[] args)


{

int arr[]=new int[10];


int z[]=new int[]{1,2,3,4};
int arr2[]=new int[7];
System.out.println(arr.length);

System.out.println(z.length);
System.out.println(arr2.length);
}

OUTPUT :

56
EXPERIMENT NO.25
AIM: Can we define a class inside a class in java, if yes show with an
example.
CODING:
class outer {

int outer_x=100;

void test()

{inner i = new inner();

i.display();

class inner{

void display()

System.out.println(outer_x);

} }}

public class demo{

public static void main(String[] args) {

outer o1= new outer();

o1.test();

}}

OUTPUT :

57
EXPERIMENT NO.26
AIM:Write a program to store your name twice in two strings i.e.
one in upper case and another in lower case, check weather both
strings are equal, find the length of string and character at index 3.
CODING:

public class Name

{
public static void main(String[] args)
{
String str1 = "ASHWANI";
String str2 = new String("ashwani");
boolean str3 = str1.equals(str2);
System.out.println(str1 == str2);

int i = str1.length();
char str4 = str1.charAt(3);

System.out.println(i+" "+str4);
}

}
OUTPUT :

58
EXPERIMENT NO.27
AIM:Give an example of inheritance in Java show
a. Method inheritance
b. Variable inheritance.
METHOD INHERITANCE
CODING:
public class method
{

public static void main(String[] args)


{
int rupee=10;
y Y=new y();
Y.drive();
}

class y extends method


{
int dollar=20;
void drive()
{
System.out.println("Rash Driver");
}
}

OUTPUT :

59
VARIABLE INHERITANCE
CODING:
public class vehicle
{
int no_of_wheels;
public static void main(String[] args)
{
Bus b=new Bus();
b.display();
cycle c=new cycle();
c.display1();
autoscooter as=new autoscooter();
as.display2();
}
}
class Bus extends vehicle
{
void display()
{
no_of_wheels=4;
System.out.println(no_of_wheels);
}
}
class cycle extends vehicle
{
void display1()
{
no_of_wheels=2;
System.out.println(no_of_wheels);
}
}
class autoscooter extends vehicle
{
void display2()
{
no_of_wheels=3;
System.out.println(no_of_wheels);
}
}
OUTPUT :

60
EXPERIMENT NO.28
AIM:Write an example to show use of super keyword
a. with variables
b. with methods
c. with constructors
CODING:

class Person
{ private String Firstname;
private String Lastname;
private int age;
public Person(String thefirstname,String thelastname)
{ Firstname=thefirstname;
Lastname=thelastname;
}
public Person(String thefirstname,String thelastname,int theage)
{ Firstname=thefirstname;
Lastname=thelastname;
age=theage;
}
public void setName(String thefirstname,String thelastname)
{ Firstname=thefirstname;
Lastname=thelastname;
}
public void setAge(int theage)
{ age=theage;
}
public String getName()
{ return Firstname+Lastname;
}
public int getAge()
{ return age;
}
}
class Student extends Person
{ private int studentid;
public Student(String thefirstname,String thelastname,int theage,int num)
{ super(thefirstname,thelastname,theage);
studentid=num;

61
}
public void display()
{ System.out.println("Name:"+this.getName());
System.out.println("Age: "+this.getAge());
System.out.println("Student id: "+this.getStudentId());
}
public int getStudentId()
{ return studentid;
}
}
public class q27
{
public static void main(String[] args)
{
Student sob=new Student("ASHWANI"," KUMAR",20,8614147);
sob.display();
}
}

Output:

62
EXPERIMENT NO.29
AIM:Demonstrate use of final
a. With variables
b. With methods in Java.
WITH VARIABLES
CODING:

public class finaldemo


{
int i=10;
final int j=20;
int sum=0;
void add()
{
sum=sum+i;
}
void display()
{
//j=30;
System.out.println(sum);
}
public static void main(String[] args)
{
finaldemo fd=new finaldemo();
fd.add();
fd.display();
}
}

OUTPUT :

63
WITH METHODS
CODING:
public class parent
{
final void eatinghabits()
{
System.out.println("Pure Vegetarian");
}
void driving()
{
System.out.println("Smooth Driving");
}
public static void main(String[] args)
{
parent p=new parent();
p.eatinghabits();
p.driving();
child c=new child();
c.driving();
}
}

OUTPUT :

64
EXPERIMENT NO.30
AIM:Can we declare a method without body in Java, if yes how?
What are abstract classes?
CODING:
abstract public class polygon
{
abstract void area();
public static void main(String[] args)
{
trianglechild ts=new trianglechild();
ts.area();
rectangle r=new rectangle();
r.area();
}
}

abstract class triangle extends polygon


{
void area()
{
System.out.println(0.5*5*10);
}
}
class rectangle extends polygon
{
void area()
{
System.out.println(10*5);
}
}
class trianglechild extends polygon
{
void area()
{
System.out.println(0.5*5*10);
}
}

OUTPUT :

65
EXPERIMENT NO.31

AIM:- How we create package in java and how do we import them,


give an example.
(a)Creating package:-

CODING:

package ems.result;

class test

{public static void main(String[] args)

int a=10,b=20,sum;

sum=a+b;

System.out.print(""+sum);

OUTPUT:

66
EXPERIMENT NO.32
AIM :-Give an example to show difference between abstract class and
interface.

ABSTRACT CLASS INTERFACE

Allows partial abstraction only. Allows full abstraction.

Abstract class can have abstract and Interface can have only abstract
non abstract methods. methods.

Abstract class doesn't support Interface supports multiple


multiple inheritance. inheritance.

Abstract class can have final, non- Interface has only static and final
final, static and non-static variables.
variables.

Abstract class can have static Interface can;t have static methods,
methods, main method and constructor. main method or constructor.

Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

67
The abstract keyword is used to The interface keyword is used to
declare abstract class. declare interface.

Example: Example:

public abstract class Shape{ public interface Drawable{

public abstract void draw(); void draw();

} }

CODING:

//Creating interface that has 4 methods

interface A{

void a();//bydefault, public and abstract

void b();

void c();

void d();

//Creating abstract class that provides the implementation of one method of A interface

abstract class B implements A{

public void c(){System.out.println("I am C");}

//Creating subclass of abstract class, now we need to provide the implementation of rest of the
methods

class M extends B{

68
public void a(){System.out.println("I am a");}

public void b(){System.out.println("I am b");}

public void d(){System.out.println("I am d");} }

//Creating a test class that calls the methods of A interface

class Q32{

public static void main(String args[]){

A a=new M();

a.a();

a.b();

a.c();

a.d();

}}

OUTPUT :

69
EXPERIMENT NO.33
AIM :-Write a program to take two input numbers from user using
scanner class and display their modulus.
CODING:

import java.util.Scanner;

class Scanner1 {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

int i=s.nextInt();

int j= s.nextInt();

int k=i%j;

System.out.println(k);

OUTPUT :

70
EXPERIMENT NO.34
AIM:- Generate an editor screen containing menus, dialog boxes etc
using Java.
CODING:

import java.awt.Color;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

class Editor1 {

JFrame Frame;

public static void main(String[] args) {

Editor1 e= new Editor1();

Editor1() {

Frame= new JFrame("My First Frame");

JMenuBar mbar = new JMenuBar();

JMenu filemenu = new JMenu("File");

JMenu editmenu= new JMenu("Edit");

Frame.setSize(400, 400);

Frame.setVisible(true);

Frame.setJMenuBar(mbar);

71
mbar.add(filemenu);

mbar.add(editmenu);

JMenuItem filenew= new JMenuItem("New");

filemenu.add(filenew);

JMenuItem fileopen= new JMenuItem("Open");

filemenu.add(fileopen);

JMenuItem fileclose= new JMenuItem("Close");

filemenu.add(fileclose);

JMenuItem filesave= new JMenuItem("Save");

filemenu.add(filesave);

JMenuItem editcut= new JMenuItem("Cut");

editmenu.add(editcut);

JMenuItem editcopy= new JMenuItem("Copy");

editmenu.add(editcopy);

JMenuItem editpaste= new JMenuItem("Paste");

editmenu.add(editpaste);

JMenuItem editinsert= new JMenuItem("Insert");

72
editmenu.add(editinsert);

OUTPUT :

73
EXPERIMENT-35
AIM:- Create an applet with a text field and three buttons. When you
press each button, make some different text appear in the text field.
Add a check box to the applet created, capture the event and insert
different text in the text field.

CODING :

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/*<applet code ="three.class" width=500 height=500 ></applet>*/

public class three extends Applet implements ActionListener,ItemListener


{
Button b1,b2,b3;
Checkbox cb;
TextField tf;

public void init()


{
tf=new TextField ("checked",10);
b1=new Button (" Shivani ");
b2=new Button (" Praseedha ");
b3=new Button (" Alisha ");
cb=new Checkbox (" 2813091 ",null,true);

setLayout(new FlowLayout());
add (b1);
add (b2);
add (b3);
add (cb);
add (tf);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

cb.addItemListener(this);
tf.addActionListener(this);

74
setBackground(Color.RED);
}

public void actionPerformed(ActionEvent e)


{
String s;
s=e.getActionCommand();
if(s.equals(" Shivani "))
tf.setText("Shivani");
if(s.equals(" Praseedha "))
tf.setText("Praseedha");
if(s.equals(" Alisha "))
tf.setText("Alisha");
}
public void itemStateChanged(ItemEvent e)
{
if (cb.getState())
{
tf.setText("checked");
}
else
{
tf.setText("unchecked");
}}}

OUTPUT :

COMMAND PROMPT :

75
OUTPUT :

APPLET VIEW :

76
EXPERIMENT-36
AIM: Create an applet with a button and a text field. Write a
handleEvent( ) so that if the button has the focus, characters typed into it
will appear in the text field

CODING :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="abc.class" width=500 height=500></applet>*/

public class abc extends Applet implements FocusListener


{
Button b1,b2;
TextField t1;

public void init()


{
t1=new TextField("Focussed",30);

b1=new Button(" LOGIN ");


b2=new Button(" LOGOUT ");
setLayout(new FlowLayout());
add(t1);
add(b1);
add(b2);

b1.addFocusListener(this);
b2.addFocusListener(this);
setBackground(Color.GREEN);
}

public void focusGained(FocusEvent fe)


{
if(fe.getSource()==b1)

{
t1.setText("LOGIN is focussed");

77
}
else if(fe.getSource()==b2)
{
t1.setText("LOGOUT is focussed");
}
}

public void focusLost(FocusEvent fe)


{
t1.setText("focus lost");
}

OUTPUT :

COMPILATION and RUNNING on cmd :

78
APPLET VIEW : (when button LOGOUT is clicked)

(when neither of button is clicked)

79
EXPERIMENT-37
AIM: Java Networking Java Sockets and RMI.

CODING:
SERVER:

import java.io.*;
import java.net.*;

public class server


{
public static void main(String[] args) throws Exception
{
ServerSocket s=new ServerSocket(8979);
while(true)
{
System.out.println("Server started");
Socket cs=s.accept();
System.out.println("Server connected to client");

PrintWriter toClient = new PrintWriter(cs.getOutputStream(),true);


BufferedReader fromClient =new BufferedReader(new
InputStreamReader(cs.getInputStream()));
String line = fromClient.readLine();
System.out.println("Server received: " + line);
toClient.println("message to client: "+line.toUpperCase() );
toClient.println("Thank you for connecting Goodbye!");
}
}
}

80
CLIENT:

import java.io.*;
import java.net.*;

public class client


{
public static void main(String[] args) throws Exception
{
Socket cs=new Socket("localhost",8979);
System.out.println("connected");

PrintWriter toServer = new PrintWriter(cs.getOutputStream(),true);


BufferedReader fromServer = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
toServer.println("hello");
String line = fromServer.readLine();
System.out.println("Client received: " + line + " from Server");
toServer.close();
fromServer.close();
cs.close();
}
}

81
OUTPUT:

Command prompt output of Server side:

Command prompt output of Client side:

82
Q38 Using JAVA develop a front end for a contact management program using a flat file database. DB
needs to be distributed or centralized.

Code:

import java.io.*;

public class Q38{

public static void main(String args[]) throws IOException {

File inputFile=new File("source.txt");

File outputFile=new File("destination.txt");

//FileInputStream in=new FileInputStream(inputFile);

//FileOutputStream out=new FileOutputStream(outputFile,true);

FileReader in=new FileReader(inputFile);

FileWriter out=new FileWriter(outputFile,true);

int c;

while((c=in.read())!=-1)

out.write(c);

//out.write(c);

//System.out.println(c);

in.close();

out.close();

83
Source:

Output:

1.

2.

3.

Destination

84

You might also like