Java Lab Manual
Java Lab Manual
Java Lab Manual
By
Dr.NARAYANA SWAMY RAMAIAH
A Checklist
To write your first program, you'll need:
1. The Java SE Development Kit (JDK 7 has been selected in this example)
o For Microsoft Windows, Solaris OS, and Linux: Java SE Downloads Index page
o For Mac OS X: developer.apple.com
c. In the New Project wizard, expand the Java category and select Java Application as shown in the
following figure:
d. In the Name and Location page of the wizard, do the following (as shown in the figure below):
o In the Project Name field, type Hello World App.
o In the Create Main Class field, type helloworldapp.HelloWorldApp.
e. Click Finish.
The project is created and opened in the IDE. You should see the following components:
The Projects window, which contains a tree view of the components of the project, including
source files, libraries that your code depends on, and so on.
The Source Editor window with a file called HelloWorldApp.java open.
The Navigator window, which you can use to quickly navigate between elements within the
selected class.
f. Add Code to the Generated Source File
When you created this project, you left the Create Main Class checkbox selected in the New
Project wizard. The IDE has therefore created a skeleton class for you. You can add the "Hello World!"
message to the skeleton code by replacing the line:
/**
*
* @author
*/
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
These four lines are a code comment and do not affect how the program runs. Later sections of this tutorial explain
the use and format of code comments.
Note: Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher (java)
arecase-sensitive, so you must capitalize consistently.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package helloworldapp;
/**
* The HelloWorldApp class implements an application that
* Simply prints "Hello World!" to standard output.
*/
/**
* @param args the command line arguments
*/
}
h. Compile the Source File into a .class File
To compile your source file, choose Run | Build Project (Hello World App) from the IDE's main menu.
The Output window opens and displays output similar to what you see in the following figure:
If the build output concludes with the statement BUILD SUCCESSFUL, congratulations! You have successfully
compiled your program!. If the build output concludes with the statement BUILD FAILED, you probably have a
syntax error in your code. Errors are reported in the Output window as hyperlinked text. You double-click such a
hyperlink to navigate to the source of an error. You can then fix the error and once again choose Run | Build Project.
When you build the project, the bytecode file HelloWorldApp.class is generated. You can see where the new file is
generated by opening the Files window and expanding the Hello World App/build/classes/helloworldapp node as
shown in the following figure.
Now that you have built the project, you can run your program.
i. Run the Program
From the IDE's menu bar, choose Run | Run Main Project. The next figure shows what you should now
see.
The program prints "Hello World!" to the Output window (along with other output from the build script).
Congratulations! Your program works!
1. Program to compute addition of numbers
/**
* program computes addition of two numbers
* @author Naray
*/
import java.util.Scanner;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int x,y,z;
System.out.println("Enter Two Integers To Calculate Their Sum");
x=in.nextInt();
y=in.nextInt();
z = x + y;
run:
Enter Two Integers To Calculate Their Sum
26
sum of entered integers = 8
2. Program to compute Area of Circle
/**
* program computes area of circle
* @author Naray
*/
/**
* @param args the command line arguments
*/
rad = 10.0;
run:
package sum;
/**
* program to add two number with command line arguments
* @author Naray
*/
/**
* @param args the command line arguments
*/
a. After build project, select Run -> set project configurations-> customize
b. Update the values in Arguments (for example 5 6)
c. Click on ok
d. Run program
run:
Sum = 11
4. Program to declare, initiliaze and print all the primitive data types
/**
*
* @author Naray
*/
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
byte b =100;
short s =123;
int v = 123543;
int calc = -9876345;
long amountVal = 1234567891;
float intrestRate = 12.25f;
double sineVal = 12345.234d;
boolean flag = true;
boolean val = false;
char ch1 = 88; // code for X
char ch2 = 'Y';
System.out.println("byte Value = "+ b);
System.out.println("short Value = "+ s);
System.out.println("int Value = "+ v);
System.out.println("int second Value = "+ calc);
System.out.println("long Value = "+ amountVal);
System.out.println("float Value = "+ intrestRate);
System.out.println("double Value = "+ sineVal);
System.out.println("boolean Value = "+ flag);
System.out.println("boolean Value = "+ val);
System.out.println("char Value = "+ ch1);
System.out.println("char Value = "+ ch2);
}
run:
byte Value = 100
short Value = 123
int Value = 123543
int second Value = -9876345
long Value = 1234567891
float Value = 12.25
double Value = 12345.234
boolean Value = true
boolean Value = false
char Value = X
char Value = Y
5. Program to discuss various types of variables available
/**
*
* @author Naray
*/
/*
* Below variable is INSTANCE VARIABLE as it is outside any method and it is
* not using STATIC modifier with it. It is using default access modifier.
* To know more about ACCESS MODIFIER visit appropriate section
*/
int instanceField;
/*
* Below variable is STATIC variable as it is outside any method and it is
* using STATIC modifier with it. It is using default access modifier. To
* know more about ACCESS MODIFIER visit appropriate section
*/
/*
* Instance variable can only be accessed by Object of the class only as below.
*/
obj.method();
System.out.println(obj.instanceField);
/*
* Static field can be accessed in two way.
* 1- Via Object of the class
* 2- Via CLASS name
*/
System.out.println(obj.staticField);
System.out.println(VariablesInJava.staticField);
System.out.println(new VariablesInJava().instanceField);
}
run:
Initial Value
0
null
null
0
/**
*
* @author Naray
*/
public class MaxConditionalOperator {
/**
* @param args the command line arguments
*/
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
max = ((a>b)?a:b);
Arguments 5 6
run:
Maximum Value is=6
7. Program to use instance operator
class ABC
{
ABC(){
System.out.println("Object is created ABC");
}
}
class XYZ
{
XYZ(){
System.out.println("Object is created XYZ");
}
}
/**
* @param args the command line arguments
*/
if (a instanceof ABC)
{
System.out.println("a is an instance of class ABC.");
}
else
{
System.out.println("a is not an instance of class ABC.");
}
if (b instanceof XYZ)
{
System.out.println("b is an instance of class XYZ.");
}
else
{
System.out.println("b is not an instance of class XYZ.");
}
}
}
run:
Object is created ABC
Object is created XYZ
a is an instance of class ABC.
b is an instance of class XYZ.
Operators and precedence
++ pre-increment
-- pre-decrement
+ unary plus
- 2 right to left
unary minus
! logical NOT
~ bitwise NOT
() cast
new 3 right to left
object creation
*
/ multiplicative 4 left to right
%
+ - additive
+ 5 left to right
string concatenation
<< >>
>>>
shift 6 left to right
< <=
> >= relational
instanceof 7 left to right
type comparison
==
!= equality 8 left to right
/*
*/
package fahrtocelcius;
import java.io.*;
/**
* @author Naray
*/
/**
*/
fahr = lower;
try {
}//End Class
2. Program to read from file
package readingfromfile;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
try {
while ( input.hasNext() ){
} // end while
} // end try
input.close();
} // end catch 1
System.exit( 1 );
} // end catch 2
if ( input != null )
/*
*/
package readingfromfile;
/**
* @author Naray
*/
read.openFile ();
read.readRecords ();
read.closeFile();
}}
3. Simple calculator
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}}
4. Java Username and password field
import javax.swing.*;
import java.awt.event.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
final JLabel label = new JLabel();
label.setBounds(20,150, 200,50);
final JPasswordField value = new JPasswordField();
value.setBounds(100,75,100,30);
JLabel l1=new JLabel("Username:");
l1.setBounds(20,20, 80,30);
JLabel l2=new JLabel("Password:");
l2.setBounds(20,75, 80,30);
JButton b = new JButton("Login");
b.setBounds(100,120, 80,30);
final JTextField text = new JTextField();
text.setBounds(100,20, 100,30);
f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username " + text.getText();
data += ", Password: "
+ new String(value.getPassword());
label.setText(data);
}
});
}
}