SlideShare une entreprise Scribd logo
1  sur  23
ME-306Computer Programming(Java)
List Of Practical’s
1. What is Java? Define features of Java. How to differ from C & C++.
2. Write a program to perform arithmetic operations.
3. Write a program to print “my first java….”.
4. Write a program to Swap two numbers.
5. Write a program to print Floyd’s Triangle.
6. Write a program to calculate a Factorial of a number.
7. Write a program to print the Fibonacci Series.
8. Write a program to show Exception Handling in Java.
9. Write a program to show Inheritance .
10. Write a program to show how to input an Array Element through Java and find the sum
of those elements.
11. Write a program to demonstrate difference between Swing & AWT.
12. Write a program to demonstrate AWT.
13. What is the major difference between an Interface and Abstract Class.
14. What is a Package? How do we tell Java that we want to use a particular package in a
file.
15. What is an Applet ? How do applets differ from applications in Java.
1.What is Java? Define features of Java. How Java differ from C & C++.
A high-level programming language developed by Sun Microsystems. Java was originally
called OAK, and was designed for handheld devices and set-top boxes. Oak was unsuccessful so
in 1995 Sun changed the name to Java and modified the language to take advantage of the
burgeoning World Wide Web.
Java is an object-oriented language similar to C++, but simplified to eliminate language features
that cause common programming errors. Java source code files (files with a .java extension)
are compiled into a format called byte code (files with a .class extension) , which can then be
executed by a Java interpreter. Compiled Java code can run on most computers because Java
interpreters and runtime environments, known as Java Virtual Machines(VMs), exist for
most operating systems, including UNIX, the Macintosh OS, and Windows. Byte code can also
be converted directly into machine language instructions by a just-in-time compiler (JIT).
Java is a general purpose programming language with a number of features that make the
language well suited for use on the World Wide Web. Small Java applications are called
Java applets and can be downloaded from a Web server and run on your computer by a Java-
compatible Web browser, such as Netscape Navigator or Microsoft Internet Explorer.
Features Of Java
1) Compiled and Interpreter:- has both Compiled and Interpreter Feature Program of java is
First Compiled and Then it is must to Interpret it .First of all The Program of java is Compiled
then after Compilation it creates Bytes Codes rather than Machine Language. Then After Bytes
Codes are Converted into the Machine Language is Converted into the Machine Language with
the help of the Interpreter So For Executing the java Program First of all it is necessary to
Compile it then it must be Interpreter
2) Platform Independent:- Java Language is Platform Independent means program of java is
Easily transferable because after Compilation of java program bytes code will be created then we
have to just transfer the Code of Byte Code to another Computer. This is not necessary for
computers having same Operating System in which the code of the java is Created and Executed
After Compilation of the Java Program We easily Convert the Program of the java top the
another Computer for Execution.
3) Object-Oriented:- We Know that is purely OOP Language that is all the Code of the java
Language is Written into the classes and Objects So For This feature java is Most Popular
Language because it also Supports Code Reusability, Maintainability etc.
4) Robust and Secure:- The Code of java is Robust and Means first checks the reliability of the
code before Execution When We trying to Convert the Higher data type into the Lower Then it
Checks the Demotion of the Code the It Will Warns a User to Not to do this So it is called as
Robust
Secure : When We convert the Code from One Machine to Another the First Check the Code
either it is Effected by the Virus or not or it Checks the Safety of the Code if code contains the
Virus then it will never Executed that code on to the Machine.
5) Distributed:- Java is Distributed Language Means because the program of java is compiled
onto one machine can be easily transferred to machine and Executes them on another machine
because facility of Bytes Codes So java is Specially designed For Internet Users which uses the
Remote Computers For Executing their Programs on local machine after transferring the
Programs from Remote Computers or either from the internet.
6) Simple Small and Familiar:- is a simple Language Because it contains many features of
other Languages like c and C++ and Java Removes Complexity because it doesn’t use pointers,
Storage Classes and Go to Statements and java Doesn’t support Multiple Inheritance
7) Multithreaded and Interactive:- Java uses Multithreaded Techniques For Execution Means
Like in other in Structure Languages Code is Divided into the Small Parts Like These Code of
java is divided into the Smaller parts those are Executed by java in Sequence and Timing Manner
this is Called as Multithreaded In this Program of java is divided into the Small parts those are
Executed by Compiler of java itself Java is Called as Interactive because Code of java Supports
Also CUI and Also GUI Programs
8) Dynamic and Extensible Code:- Java has Dynamic and Extensible Code Means With the
Help of OOPS java Provides Inheritance and With the Help of Inheritance we Reuse the Code
that is Pre-defined and Also uses all the built in Functions of java and Classes
9) Distributed:- Java is a distributed language which means that the program can be design to
run on computer networks. Java provides an extensive library of classes for communicating
,using TCP/IP protocols such as HTTP and FTP. This makes creating network connections much
easier than in C/C++. You can read and write objects on the remote sites via URL with the same
ease that programmers are used to when read and write data from and to a file. This helps the
programmers at remote locations to work together on the same project.
10) Secure: Java was designed with security in mind. As Java is intended to be used in
networked/distributor environments so it implements several security mechanisms to protect you
against malicious code that might try to invade your file system.
Java differ from C & C++.
Feature C C++ Java
Programming
Approach
Procedural
Programming
Language
Procedural, OOP, Generic
Programming languages
OOP, Generic
Programming languages.
Compiled
Source Code
Executable in
Native Code
Executable in Native Code
Compiled into Java byte
code
Memory
management
Manual Done, Manual Done,
Managed, using a
garbage collector
Pointers
Yes, very
commonly used.
Yes, very commonly used, but
some form of references
available too.
No pointers; references
are used instead.
Preprocessor Yes Yes No
String Type Character arrays Character arrays, objects Objects
Complex Data
Types
Structures, unions Structures, unions, classes Classes
Inheritance N/A Multiple class inheritance
Single class inheritance,
multiple interface
implementation
Operator
Overloading
N/A Yes No
Automatic
coercions
(Conversion)
Yes, with
warnings if loss
could occur
Yes, with warnings if loss could
occur
Not at all if loss could
occur; must cast
explicitly
Variadic
Parameters
Yes Yes No
Goto Statement Yes Yes No
2. Write a program to perform arithemetic operations.
import java.util.*;
class ArithOp
{
public static void main(String args[])
{
int num1,num2,Add,Mul,Div,Sub;
System.out.println("enter the two numbers to perform operations");
Scanner sc= new Scanner(System.in);
System.out.println("first number is: ");
num1= sc.nextInt();
System.out.println("Second number is: ");
num2= sc.nextInt();
Add = num1+num2;
Mul= num1 * num2;
Div= num1/num2;
Sub= num1-num2;
System.out.println("Addition of two number is: =" +Add);
System.out.println();
System.out.println("Multiplication of two number is: =" +Mul);
System.out.println();
System.out.println("Division of two number is: =" +Div);
System.out.println();
System.out.println("Subtraction of two number is: =" +Sub);
System.out.println();
}
}
Output:
3. Write a program to print “My first program….”
import java.io.*;
public class FirstProg
{ //This is a first simple java program.
public static void main(String[] args)
{
System.out.println("My First JAVA program...............");
System.out.println("hello i run java first time");
}
}
Output:
4. Write a program to swap to numbers.
import java.util.*;
class Swap
{
public static void main(String[]args)
{
int a,b,c;
System.out.println("enter two variable to swap");
Scanner sc = new Scanner(System.in);
a=sc.nextInt();
System.out.println("The variable is "+a);
b=sc.nextInt();
System.out.println("The variable is "+b);
c=a;
a=b;
b=c;
System.out.println("The swapped variable");
System.out.println("The variable is "+a);
System.out.println("The variable is "+b);
}
}
Output:
5. Write a program to print FLOYD’S Triangle.
import java.io.*;
import java.util.Scanner;
class TriangleFloyd
{
public static void main(String[]args)
{
int i,j,k=1,n;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the rows");
n= sc.nextInt();
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(k);
k++;
}
System.out.println();
}
}
}
Output:
6.Write a program to calculate a factorial of a number.
import java.io.*;
import java.util.Scanner;
class Factorial
{
public static void main(String arg[])
{
int n,c,fact=1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in=new Scanner(System.in);
n=in.nextInt();
if(n<0)
System.out.println("Number should be non-negative");
else
for(c=1;c<=n;c++)
fact=fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
}
Output:
7. Write a program to print a Fibonacci series.
import java.io.*;
import java.util.Scanner;
class Factorial
{
public static void main(String arg[])
{
int n,c,fact=1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in=new Scanner(System.in);
n=in.nextInt();
if(n<0)
System.out.println("Number should be non-negative");
else
for(c=1;c<=n;c++)
fact=fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
}
Output:
8. Write a program to exception handling in Java.
import java.io.*;
import java.util.Scanner;
class Exceptionhandling
{
public static void main(String args[])
{
int a=10;
int b=5,c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Syntax error");
}
y=a/(b+c);
System.out.println("value of y is"+y);
}
}
Output:
9.Write a program to show Inheritance.
class Base
{
void show1()
{
System.out.println("base show");
}
int x=10;
}
class Child extends Base
{
int x=20;
void show()
{
System.out.println("child show");
System.out.println("child class value "+x);
System.out.println("base class value "+super.x);
}}
class Main
{
public static void main(String args[])
{
Child c = new Child();
c.show();
}}
Output:
10. Write a program to show how to input array element through Java and find the sum of
those element.
import java.io.*;
import java.util.*;
class Array
{
public static void main(String args[])
{
int total=0;
Scanner sc= new Scanner(System.in);
System.out.println("enter the size of array");
int z=sc.nextInt();
int x[]= new int[z];
System.out.println("enter the array element");
for(int i=0; i<x.length;i++)
x[i]=sc.nextInt();
System.out.println("array element are");
for(int i=0; i<x.length;i++)
System.out.println(x[i]);
for(int i=0; i<x.length;i++)
total = total + x[i];
System.out.println("Sum of array element is:"+total);
}
}
Output:
11.Write a program to demonstrate difference between Swing and AWT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class SFrame3 implements ActionListener
{
JTextField jt;
JButton b;
Button b1;
JFrame f;
SFrame3(String s)
{
f=new JFrame(s);
f.setVisible(true);
f.setSize(400,400);
b= new JButton("Swing");
b.setBounds(40,40,100,100);
b1= new Button("awt");
b1.setBounds(40,150,100,100);
jt= new JTextField();
jt.setBounds(150,40,100,100);
f.add(b);
f.add(b1);
f.add(jt);
f.setLayout(null);
b.addActionListener(this);
b1.addActionListener(this);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
jt.setText("Swing Example");
if(e.getSource()==b1)
jt.setText("awt Example");
}
public static void main(String args[])
{
new SFrame3("MY_SWING_FRAME_WITH_EVENT");
}
}
Output:
12.Write a program to demonstrate AWT.
import java.awt.*;
import java.awt.event.*;
class EventDemo1 implements ActionListener
{
Frame f;
Button b,b1;
TextField tf;
EventDemo1(String d)
{
f=new Frame(d);
b= new Button("ok");
b1= new Button("cancel");
b.setBounds(10,50,40,30);
b1.setBounds(10,90,40,30);
b.addActionListener(this);
b1.addActionListener(this);
f.add(b);
f.add(b1);
tf= new TextField();
tf.setBounds(20,120,40,80);
f.add(tf);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
tf.setText("ok");
else
if(e.getSource()==b1)
tf.setText("cancel");
}
public static void main(String f[])
{
new EventDemo1("EventDemo1");
}
}
OUTPUT:
13.What is the major difference between an Interface and Abstract Class.
Interface Abstract Class
Multiple inheritance A class may inherit several
interfaces.
A class may inherit only one
abstract class.
Default implementation An interface cannot provide
any code, just the signature.
An abstract class can provide
complete, default code and/or
just the details that have to be
overridden.
Access Modifiers An interface cannot have
access modifiers for the subs,
functions, properties etc
everything is assumed as
public.
An abstract class can contain
access modifiers for the subs,
functions, properties.
Homogeneity If various implementations
only share method signatures
then it is better to use
Interfaces.
If various implementations are
of the same kind and use
common behavior or status
then abstract class is better to
use.
Speed Requires more time to find the
actual method in the
corresponding classes.
Fast
Adding functionality If we add a new method to an
Interface then we have to track
down all the implementations
of the interface and define
implementation for the new
method.
If we add a new method to an
abstract class then we have the
option of providing default
implementation and therefore
all the existing code might
work properly.
Fields and Constants No fields can be defined in
interfaces.
An abstract class can have
fields and constants defined.
Terseness The constant declarations in an
interface are all presumed
public static final.
Shared code can be added into
an abstract class.
Constants Static final constants only, can
use them without qualification
in classes that implement the
interface.
Both instance and static
constants are possible. Both
static and instance intialiser
code are also possible to
compute the constants.
14.What is a Package? How do we tell Java that we want to use a particular package in a file.
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and name space management.
Some of the existing packages in Java are::
java.lang - bundles the fundamental classes
java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
Creating a package:
When creating a package, you should choose a name for the package and put
a package statement with that name at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be put into an unnamed package.
Example:
Let us look at an example that creates a package called animals. It is common practice to use
lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Now, put an implementation in the same package animals:
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Now, you compile these two files and put them in a sub-directory called animals and try to run
as follows:
$ mkdir animals
$ cp Animal. class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels
15.What is an Applet? How it is differ from applications in Java?
A Java applet is a special kind of Java program that a browser enabled with Java technology can
download from the internet and run. An applet is typically embedded inside a web page and runs
in the context of a browser. An applet must be a subclass of the java.applet.Applet class. The
Applet class provides the standard interface between the applet and the browser environment.
Swing provides a special subclass of the Applet class called javax.swing.JApplet. The JApplet
class should be used for all applets that use Swing components to construct their graphical user
interfaces (GUIs).
The browser's Java Plug-in software manages the lifecycle of an applet.
Every Java applet must define a subclass of the Applet or JApplet class. In the Hello World
applet, this subclass is called HelloWorld. The following is the source for the HelloWorld class.
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
public class HelloWorld extends JApplet
{
//Called when this applet is loaded into the browser.
public void init()
{
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
JLabel lbl = new JLabel("Hello World");
add(lbl);
}
}
}
catch (Exception e)
{
System.err.println("createGUI didn't complete successfully");
}
}
}
An applet can react to major events in the following ways:
 It can initialize itself.
 It can start running.
 It can stop running.
 It can perform a final cleanup, in preparation for being unloaded
Difference between applet and applications in Java
Applet Application
Small Program Large Program
Used to run a program on client
Browser
Can be executed on standalone
computer system
Applet is portable and can be executed
by any JAVA supported browser.
Need JDK, JRE, JVM installed on
client machine.
Applet applications are executed in a
Restricted Environment
Application can access all the
resources of the computer
Applets are created by extending the
java.applet.Applet
Applications are created by writing
public static void main(String[] s)
method.
Applet application has 5 methods
which will be automatically invoked on
occurrence of specific event
Application has a single start point
which is main method
Example:
import java.awt.*;
import java.applet.*;
public class Myclass extends Applet
{
public void init() { }
public void start() { }
public void stop() {}
public void destroy() {}
public void paint(Graphics g) {}
}
public class MyClass
{
public static void main(String
args[]) {}
}

Contenu connexe

Tendances (20)

Java essential notes
Java essential notesJava essential notes
Java essential notes
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Advanced programming ch1
Advanced programming ch1Advanced programming ch1
Advanced programming ch1
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Grade 8: Introduction To Java
Grade 8: Introduction To JavaGrade 8: Introduction To Java
Grade 8: Introduction To Java
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Bn1005 demo ppt core java
Bn1005 demo ppt core javaBn1005 demo ppt core java
Bn1005 demo ppt core java
 
Core java
Core javaCore java
Core java
 
Java seminar
Java seminarJava seminar
Java seminar
 
Java notes
Java notesJava notes
Java notes
 
Csharp
CsharpCsharp
Csharp
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
Introduction to java technology
Introduction to java technologyIntroduction to java technology
Introduction to java technology
 
Chapter 1. java programming language overview
Chapter 1. java programming language overviewChapter 1. java programming language overview
Chapter 1. java programming language overview
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Basic Java I
Basic Java IBasic Java I
Basic Java I
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Tutorial c#
Tutorial c#Tutorial c#
Tutorial c#
 
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technology
 
Java basics
Java basicsJava basics
Java basics
 

En vedette

LISP + GETVPN as alternative to DMVPN+OSPF+GETVPN
LISP + GETVPN as alternative to DMVPN+OSPF+GETVPNLISP + GETVPN as alternative to DMVPN+OSPF+GETVPN
LISP + GETVPN as alternative to DMVPN+OSPF+GETVPNJobSnijders
 
Krok 2 - 2010 Question Paper (Pharmacy)
Krok 2 - 2010 Question Paper (Pharmacy)Krok 2 - 2010 Question Paper (Pharmacy)
Krok 2 - 2010 Question Paper (Pharmacy)Eneutron
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Appletbackdoor
 
Basics of applets.53
Basics of applets.53Basics of applets.53
Basics of applets.53myrajendra
 
L5 classes, objects, nested and inner class
L5 classes, objects, nested and inner classL5 classes, objects, nested and inner class
L5 classes, objects, nested and inner classteach4uin
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programmingmcanotes
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Appletsamitksaha
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cyclemyrajendra
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 

En vedette (16)

LISP + GETVPN as alternative to DMVPN+OSPF+GETVPN
LISP + GETVPN as alternative to DMVPN+OSPF+GETVPNLISP + GETVPN as alternative to DMVPN+OSPF+GETVPN
LISP + GETVPN as alternative to DMVPN+OSPF+GETVPN
 
Krok 2 - 2010 Question Paper (Pharmacy)
Krok 2 - 2010 Question Paper (Pharmacy)Krok 2 - 2010 Question Paper (Pharmacy)
Krok 2 - 2010 Question Paper (Pharmacy)
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Applet
 
Satish training ppt
Satish training pptSatish training ppt
Satish training ppt
 
Basics of applets.53
Basics of applets.53Basics of applets.53
Basics of applets.53
 
L5 classes, objects, nested and inner class
L5 classes, objects, nested and inner classL5 classes, objects, nested and inner class
L5 classes, objects, nested and inner class
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programming
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Applets
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
Applet progming
Applet progmingApplet progming
Applet progming
 

Similaire à Java Programming Practical List

Java Evolution-2.pdf
Java Evolution-2.pdfJava Evolution-2.pdf
Java Evolution-2.pdfkumari36
 
Introducción a la progrogramación orientada a objetos con Java
Introducción a la progrogramación orientada a objetos con JavaIntroducción a la progrogramación orientada a objetos con Java
Introducción a la progrogramación orientada a objetos con JavaFacultad de Ciencias y Sistemas
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01Jay Palit
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkMohit Belwal
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software DevelopmentZeeshan MIrza
 
Core Java Slides
Core Java SlidesCore Java Slides
Core Java SlidesVinit Vyas
 
Notes of java first unit
Notes of java first unitNotes of java first unit
Notes of java first unitgowher172236
 
0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdfDeepakChaudhriAmbali
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaHarry Potter
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingJames Wong
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaHoang Nguyen
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaTony Nguyen
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingYoung Alista
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingFraboni Ec
 

Similaire à Java Programming Practical List (20)

Java Evolution-2.pdf
Java Evolution-2.pdfJava Evolution-2.pdf
Java Evolution-2.pdf
 
Introducción a la progrogramación orientada a objetos con Java
Introducción a la progrogramación orientada a objetos con JavaIntroducción a la progrogramación orientada a objetos con Java
Introducción a la progrogramación orientada a objetos con Java
 
Java ms harsha
Java ms harshaJava ms harsha
Java ms harsha
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
Core Java Slides
Core Java SlidesCore Java Slides
Core Java Slides
 
Notes of java first unit
Notes of java first unitNotes of java first unit
Notes of java first unit
 
0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf
 
Java presentation
Java presentationJava presentation
Java presentation
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
 
00 intro to java
00 intro to java00 intro to java
00 intro to java
 
Java lab zero lecture
Java  lab  zero lectureJava  lab  zero lecture
Java lab zero lecture
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 

Plus de Gaurav Singh

Plus de Gaurav Singh (8)

Oral presentation
Oral presentationOral presentation
Oral presentation
 
srgoc dotnet_ppt
srgoc dotnet_pptsrgoc dotnet_ppt
srgoc dotnet_ppt
 
Srgoc dotnet_new
Srgoc dotnet_newSrgoc dotnet_new
Srgoc dotnet_new
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
ADA FILE
ADA FILEADA FILE
ADA FILE
 
srgoc
srgocsrgoc
srgoc
 
Srgoc linux
Srgoc linuxSrgoc linux
Srgoc linux
 
cs506_linux
cs506_linuxcs506_linux
cs506_linux
 

Dernier

Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodManicka Mamallan Andavar
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSHigh Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSsandhya757531
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Communityprachaibot
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Coursebim.edu.pl
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSneha Padhiar
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfChristianCDAM
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Romil Mishra
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solidnamansinghjarodiya
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHSneha Padhiar
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.elesangwon
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionSneha Padhiar
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdfsahilsajad201
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfalene1
 

Dernier (20)

Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument method
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSHigh Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Community
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Course
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdf
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solid
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based question
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdf
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
 

Java Programming Practical List

  • 1. ME-306Computer Programming(Java) List Of Practical’s 1. What is Java? Define features of Java. How to differ from C & C++. 2. Write a program to perform arithmetic operations. 3. Write a program to print “my first java….”. 4. Write a program to Swap two numbers. 5. Write a program to print Floyd’s Triangle. 6. Write a program to calculate a Factorial of a number. 7. Write a program to print the Fibonacci Series. 8. Write a program to show Exception Handling in Java. 9. Write a program to show Inheritance . 10. Write a program to show how to input an Array Element through Java and find the sum of those elements. 11. Write a program to demonstrate difference between Swing & AWT. 12. Write a program to demonstrate AWT. 13. What is the major difference between an Interface and Abstract Class. 14. What is a Package? How do we tell Java that we want to use a particular package in a file. 15. What is an Applet ? How do applets differ from applications in Java.
  • 2. 1.What is Java? Define features of Java. How Java differ from C & C++. A high-level programming language developed by Sun Microsystems. Java was originally called OAK, and was designed for handheld devices and set-top boxes. Oak was unsuccessful so in 1995 Sun changed the name to Java and modified the language to take advantage of the burgeoning World Wide Web. Java is an object-oriented language similar to C++, but simplified to eliminate language features that cause common programming errors. Java source code files (files with a .java extension) are compiled into a format called byte code (files with a .class extension) , which can then be executed by a Java interpreter. Compiled Java code can run on most computers because Java interpreters and runtime environments, known as Java Virtual Machines(VMs), exist for most operating systems, including UNIX, the Macintosh OS, and Windows. Byte code can also be converted directly into machine language instructions by a just-in-time compiler (JIT). Java is a general purpose programming language with a number of features that make the language well suited for use on the World Wide Web. Small Java applications are called Java applets and can be downloaded from a Web server and run on your computer by a Java- compatible Web browser, such as Netscape Navigator or Microsoft Internet Explorer. Features Of Java 1) Compiled and Interpreter:- has both Compiled and Interpreter Feature Program of java is First Compiled and Then it is must to Interpret it .First of all The Program of java is Compiled then after Compilation it creates Bytes Codes rather than Machine Language. Then After Bytes Codes are Converted into the Machine Language is Converted into the Machine Language with the help of the Interpreter So For Executing the java Program First of all it is necessary to Compile it then it must be Interpreter 2) Platform Independent:- Java Language is Platform Independent means program of java is Easily transferable because after Compilation of java program bytes code will be created then we have to just transfer the Code of Byte Code to another Computer. This is not necessary for computers having same Operating System in which the code of the java is Created and Executed After Compilation of the Java Program We easily Convert the Program of the java top the another Computer for Execution. 3) Object-Oriented:- We Know that is purely OOP Language that is all the Code of the java Language is Written into the classes and Objects So For This feature java is Most Popular Language because it also Supports Code Reusability, Maintainability etc. 4) Robust and Secure:- The Code of java is Robust and Means first checks the reliability of the code before Execution When We trying to Convert the Higher data type into the Lower Then it Checks the Demotion of the Code the It Will Warns a User to Not to do this So it is called as Robust Secure : When We convert the Code from One Machine to Another the First Check the Code either it is Effected by the Virus or not or it Checks the Safety of the Code if code contains the Virus then it will never Executed that code on to the Machine.
  • 3. 5) Distributed:- Java is Distributed Language Means because the program of java is compiled onto one machine can be easily transferred to machine and Executes them on another machine because facility of Bytes Codes So java is Specially designed For Internet Users which uses the Remote Computers For Executing their Programs on local machine after transferring the Programs from Remote Computers or either from the internet. 6) Simple Small and Familiar:- is a simple Language Because it contains many features of other Languages like c and C++ and Java Removes Complexity because it doesn’t use pointers, Storage Classes and Go to Statements and java Doesn’t support Multiple Inheritance 7) Multithreaded and Interactive:- Java uses Multithreaded Techniques For Execution Means Like in other in Structure Languages Code is Divided into the Small Parts Like These Code of java is divided into the Smaller parts those are Executed by java in Sequence and Timing Manner this is Called as Multithreaded In this Program of java is divided into the Small parts those are Executed by Compiler of java itself Java is Called as Interactive because Code of java Supports Also CUI and Also GUI Programs 8) Dynamic and Extensible Code:- Java has Dynamic and Extensible Code Means With the Help of OOPS java Provides Inheritance and With the Help of Inheritance we Reuse the Code that is Pre-defined and Also uses all the built in Functions of java and Classes 9) Distributed:- Java is a distributed language which means that the program can be design to run on computer networks. Java provides an extensive library of classes for communicating ,using TCP/IP protocols such as HTTP and FTP. This makes creating network connections much easier than in C/C++. You can read and write objects on the remote sites via URL with the same ease that programmers are used to when read and write data from and to a file. This helps the programmers at remote locations to work together on the same project. 10) Secure: Java was designed with security in mind. As Java is intended to be used in networked/distributor environments so it implements several security mechanisms to protect you against malicious code that might try to invade your file system.
  • 4. Java differ from C & C++. Feature C C++ Java Programming Approach Procedural Programming Language Procedural, OOP, Generic Programming languages OOP, Generic Programming languages. Compiled Source Code Executable in Native Code Executable in Native Code Compiled into Java byte code Memory management Manual Done, Manual Done, Managed, using a garbage collector Pointers Yes, very commonly used. Yes, very commonly used, but some form of references available too. No pointers; references are used instead. Preprocessor Yes Yes No String Type Character arrays Character arrays, objects Objects Complex Data Types Structures, unions Structures, unions, classes Classes Inheritance N/A Multiple class inheritance Single class inheritance, multiple interface implementation Operator Overloading N/A Yes No Automatic coercions (Conversion) Yes, with warnings if loss could occur Yes, with warnings if loss could occur Not at all if loss could occur; must cast explicitly Variadic Parameters Yes Yes No Goto Statement Yes Yes No
  • 5. 2. Write a program to perform arithemetic operations. import java.util.*; class ArithOp { public static void main(String args[]) { int num1,num2,Add,Mul,Div,Sub; System.out.println("enter the two numbers to perform operations"); Scanner sc= new Scanner(System.in); System.out.println("first number is: "); num1= sc.nextInt(); System.out.println("Second number is: "); num2= sc.nextInt(); Add = num1+num2; Mul= num1 * num2; Div= num1/num2; Sub= num1-num2; System.out.println("Addition of two number is: =" +Add); System.out.println(); System.out.println("Multiplication of two number is: =" +Mul); System.out.println(); System.out.println("Division of two number is: =" +Div); System.out.println(); System.out.println("Subtraction of two number is: =" +Sub); System.out.println(); } }
  • 7. 3. Write a program to print “My first program….” import java.io.*; public class FirstProg { //This is a first simple java program. public static void main(String[] args) { System.out.println("My First JAVA program..............."); System.out.println("hello i run java first time"); } } Output:
  • 8. 4. Write a program to swap to numbers. import java.util.*; class Swap { public static void main(String[]args) { int a,b,c; System.out.println("enter two variable to swap"); Scanner sc = new Scanner(System.in); a=sc.nextInt(); System.out.println("The variable is "+a); b=sc.nextInt(); System.out.println("The variable is "+b); c=a; a=b; b=c; System.out.println("The swapped variable"); System.out.println("The variable is "+a); System.out.println("The variable is "+b); } } Output:
  • 9. 5. Write a program to print FLOYD’S Triangle. import java.io.*; import java.util.Scanner; class TriangleFloyd { public static void main(String[]args) { int i,j,k=1,n; Scanner sc= new Scanner(System.in); System.out.println("Enter the rows"); n= sc.nextInt(); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) { System.out.print(k); k++; } System.out.println(); } } } Output:
  • 10. 6.Write a program to calculate a factorial of a number. import java.io.*; import java.util.Scanner; class Factorial { public static void main(String arg[]) { int n,c,fact=1; System.out.println("Enter an integer to calculate it's factorial"); Scanner in=new Scanner(System.in); n=in.nextInt(); if(n<0) System.out.println("Number should be non-negative"); else for(c=1;c<=n;c++) fact=fact*c; System.out.println("Factorial of "+n+" is = "+fact); } } Output:
  • 11. 7. Write a program to print a Fibonacci series. import java.io.*; import java.util.Scanner; class Factorial { public static void main(String arg[]) { int n,c,fact=1; System.out.println("Enter an integer to calculate it's factorial"); Scanner in=new Scanner(System.in); n=in.nextInt(); if(n<0) System.out.println("Number should be non-negative"); else for(c=1;c<=n;c++) fact=fact*c; System.out.println("Factorial of "+n+" is = "+fact); } } Output:
  • 12. 8. Write a program to exception handling in Java. import java.io.*; import java.util.Scanner; class Exceptionhandling { public static void main(String args[]) { int a=10; int b=5,c=5; int x,y; try { x=a/(b-c); } catch(ArithmeticException e) { System.out.println("Syntax error"); } y=a/(b+c); System.out.println("value of y is"+y); } } Output:
  • 13. 9.Write a program to show Inheritance. class Base { void show1() { System.out.println("base show"); } int x=10; } class Child extends Base { int x=20; void show() { System.out.println("child show"); System.out.println("child class value "+x); System.out.println("base class value "+super.x); }} class Main { public static void main(String args[]) { Child c = new Child(); c.show(); }} Output:
  • 14. 10. Write a program to show how to input array element through Java and find the sum of those element. import java.io.*; import java.util.*; class Array { public static void main(String args[]) { int total=0; Scanner sc= new Scanner(System.in); System.out.println("enter the size of array"); int z=sc.nextInt(); int x[]= new int[z]; System.out.println("enter the array element"); for(int i=0; i<x.length;i++) x[i]=sc.nextInt(); System.out.println("array element are"); for(int i=0; i<x.length;i++) System.out.println(x[i]); for(int i=0; i<x.length;i++) total = total + x[i]; System.out.println("Sum of array element is:"+total); } } Output:
  • 15. 11.Write a program to demonstrate difference between Swing and AWT import java.awt.*; import java.awt.event.*; import javax.swing.*; class SFrame3 implements ActionListener { JTextField jt; JButton b; Button b1; JFrame f; SFrame3(String s) { f=new JFrame(s); f.setVisible(true); f.setSize(400,400); b= new JButton("Swing"); b.setBounds(40,40,100,100); b1= new Button("awt"); b1.setBounds(40,150,100,100); jt= new JTextField(); jt.setBounds(150,40,100,100); f.add(b); f.add(b1); f.add(jt); f.setLayout(null); b.addActionListener(this); b1.addActionListener(this); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b) jt.setText("Swing Example"); if(e.getSource()==b1) jt.setText("awt Example"); }
  • 16. public static void main(String args[]) { new SFrame3("MY_SWING_FRAME_WITH_EVENT"); } } Output:
  • 17. 12.Write a program to demonstrate AWT. import java.awt.*; import java.awt.event.*; class EventDemo1 implements ActionListener { Frame f; Button b,b1; TextField tf; EventDemo1(String d) { f=new Frame(d); b= new Button("ok"); b1= new Button("cancel"); b.setBounds(10,50,40,30); b1.setBounds(10,90,40,30); b.addActionListener(this); b1.addActionListener(this); f.add(b); f.add(b1); tf= new TextField(); tf.setBounds(20,120,40,80); f.add(tf); f.setSize(400,400); f.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b) tf.setText("ok"); else if(e.getSource()==b1) tf.setText("cancel"); } public static void main(String f[]) { new EventDemo1("EventDemo1"); } }
  • 19. 13.What is the major difference between an Interface and Abstract Class. Interface Abstract Class Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class. Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden. Access Modifiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public. An abstract class can contain access modifiers for the subs, functions, properties. Homogeneity If various implementations only share method signatures then it is better to use Interfaces. If various implementations are of the same kind and use common behavior or status then abstract class is better to use. Speed Requires more time to find the actual method in the corresponding classes. Fast Adding functionality If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. Fields and Constants No fields can be defined in interfaces. An abstract class can have fields and constants defined. Terseness The constant declarations in an interface are all presumed public static final. Shared code can be added into an abstract class. Constants Static final constants only, can use them without qualification in classes that implement the interface. Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.
  • 20. 14.What is a Package? How do we tell Java that we want to use a particular package in a file. Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc. A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and name space management. Some of the existing packages in Java are:: java.lang - bundles the fundamental classes java.io - classes for input , output functions are bundled in this package Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, annotations are related. Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes. Creating a package: When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package. Example: Let us look at an example that creates a package called animals. It is common practice to use lowercased names of packages to avoid any conflicts with the names of classes, interfaces. Put an interface in the package animals: /* File name : Animal.java */ package animals; interface Animal { public void eat(); public void travel(); }
  • 21. Now, put an implementation in the same package animals: package animals; /* File name : MammalInt.java */ public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats"); } public void travel(){ System.out.println("Mammal travels"); } public int noOfLegs(){ return 0; } public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); } } Now, you compile these two files and put them in a sub-directory called animals and try to run as follows: $ mkdir animals $ cp Animal. class MammalInt.class animals $ java animals/MammalInt Mammal eats Mammal travels
  • 22. 15.What is an Applet? How it is differ from applications in Java? A Java applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of the java.applet.Applet class. The Applet class provides the standard interface between the applet and the browser environment. Swing provides a special subclass of the Applet class called javax.swing.JApplet. The JApplet class should be used for all applets that use Swing components to construct their graphical user interfaces (GUIs). The browser's Java Plug-in software manages the lifecycle of an applet. Every Java applet must define a subclass of the Applet or JApplet class. In the Hello World applet, this subclass is called HelloWorld. The following is the source for the HelloWorld class. import javax.swing.JApplet; import javax.swing.SwingUtilities; import javax.swing.JLabel; public class HelloWorld extends JApplet { //Called when this applet is loaded into the browser. public void init() { //Execute a job on the event-dispatching thread; creating this applet's GUI. try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { JLabel lbl = new JLabel("Hello World"); add(lbl); } } } catch (Exception e) { System.err.println("createGUI didn't complete successfully"); } } } An applet can react to major events in the following ways:  It can initialize itself.  It can start running.  It can stop running.  It can perform a final cleanup, in preparation for being unloaded
  • 23. Difference between applet and applications in Java Applet Application Small Program Large Program Used to run a program on client Browser Can be executed on standalone computer system Applet is portable and can be executed by any JAVA supported browser. Need JDK, JRE, JVM installed on client machine. Applet applications are executed in a Restricted Environment Application can access all the resources of the computer Applets are created by extending the java.applet.Applet Applications are created by writing public static void main(String[] s) method. Applet application has 5 methods which will be automatically invoked on occurrence of specific event Application has a single start point which is main method Example: import java.awt.*; import java.applet.*; public class Myclass extends Applet { public void init() { } public void start() { } public void stop() {} public void destroy() {} public void paint(Graphics g) {} } public class MyClass { public static void main(String args[]) {} }