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[]) {}
}