Vous êtes sur la page 1sur 27

“OOP LAB MANUAL (ECEG-3142)”

By
Dr.NARAYANA SWAMY RAMAIAH

Department of Electrical and Computer Engineering


ARBA MINCH UNIVERISTY,
ARBA MINCH INSTITUTE OF TECHNOLOGY
Nov 2016
"Hello World!" for the NetBeans IDE
It's time to write your first application! These detailed instructions are for users of the NetBeans IDE. The NetBeans
IDE runs on the Java platform, which means that you can use it with any operating system for which there is a JDK
available. These operating systems include Microsoft Windows, Solaris OS, Linux, and Mac OS X.
 A Checklist
 Creating Your First Application
o Create an IDE Project
o Add Code to the Generated Source File
o Compile the Source File
o Run the Program

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

2. The NetBeans IDE


o For all platforms: NetBeans IDE Downloads Index page
https://netbeans.org/downloads/

Creating Your First Application


Your first application, HelloWorldApp, will simply display the greeting "Hello World!" To create this program, you
will:

1. Create an IDE Project


When you create an IDE project, you create an environment in which to build and run your applications.
Using IDE projects eliminates configuration issues normally associated with developing on the command
line. You can build or run your application by choosing a single menu item within the IDE.

To create an IDE project:


a. Launch the NetBeans IDE.
o On Microsoft Windows systems, you can use the NetBeans IDE item in the Start menu.
b. In the NetBeans IDE, choose File | New Project....

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:

// TODO code application logic here

with the line:

System.out.println("Hello World!"); // Display the string.

Optionally, you can replace these four lines of generated code:

/**
*
* @author
*/

with these lines:

/**
* 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.

Be Careful When You Type

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.

HelloWorldApp is not the same as helloworldapp.

g. Save your changes by choosing File | Save.

The file should look something like the following:

/*
* 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.
*/

public class HelloWorldApp {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {


System.out.println("Hello World!"); // Display the string.
}

}
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;

public class AddTwoNumbers {

/**
* @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");

Scanner in = new Scanner (System.in);

x=in.nextInt();
y=in.nextInt();

z = x + y;

System.out.println("sum of entered integers = " +z);

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
*/

public class AreaCircle {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {


double rad;

final double PI = 3.14159;

rad = 10.0;

double area = PI * rad * rad;

System.out.print("\n Area of Circle is = " +area);

run:

Area of Circle is = 314.159


3. Program to add two numbers with command line arguments

package sum;

/**
* program to add two number with command line arguments
* @author Naray
*/

public class Sum {

/**
* @param args the command line arguments
*/

public static void main(String args[]) {

int num1, num2, sum;

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


num2 = Integer.parseInt( args[1] );

sum = num1 + num2;

System.out.println("Sum = " +sum);


}

Procedure to pass 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
*/

public class PrimitiveDemo {

/**
* @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
*/

public class VariablesInJava {

/*
* 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
*/

static String staticField;

public void method() {


/*
* Below variable is LOCAL VARIABLE as it is defined inside method in
* class. Only modifier that can be applied on local variable is FINAL.
* To know more about access and non access modifier visit appropriate
* section.
*
* Note* : Local variable needs to initialize before they can be used.
* Which is not true for Static or Instance variable.
*/

final String localVariable = "Initial Value";


System.out.println(localVariable);
}

public static void main(String[] args) {


VariablesInJava obj = new VariablesInJava();

/*
* 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

6. Program to find maximum of two numbers using conditional operator

/**
*
* @author Naray
*/
public class MaxConditionalOperator {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {


int a, b, max;

a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);

max = ((a>b)?a:b);

System.out.print("\n Maximum Value is=" +max);

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");
}
}

public class OpInstanceOf {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {

ABC a = new ABC();


XYZ b = new XYZ();

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

Operator Description Level Associativity

[] access array element


. access object member
() invoke a method 1 left to right
++ post-increment
-- post-decrement

++ 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

& bitwise AND 9 left to right

^ bitwise XOR 10 left to right

| bitwise OR 11 left to right

&& conditional AND 12 left to right


|| conditional OR 13 left to right

?: conditional 14 right to left


= += -=
*= /= %=
&= ^= |= assignment 15 right to left
<<= >>= >>>=

1. Program to write to file

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package fahrtocelcius;

import java.io.*;

/**

* @author Naray

*/

public class FahrToCelcius {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

double fahr, celsius;


double lower, upper, step;

lower = 0.0; // lower limit of temperature table

upper = 300.0; // upper limit of temperature table

step = 20.0; // step size

fahr = lower;

try {

FileOutputStream fout = new FileOutputStream("d:\\test.txt");

PrintStream myOutput = new PrintStream(fout); // now the //FileOutputStream into a


PrintStream

while (fahr <= upper) { // while loop begins here

celsius = 5.0 * (fahr-32.0) / 9.0;

myOutput.println(fahr + " " + celsius);

fahr = fahr + step;

} // while loop ends here

} // try ends here

catch (IOException e) { System.out.println("Error: " + e);

} // main ends here

}//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;

public class ReadingFromFile {

public int account;

public String firstName,lastName;

public double balance;

public Scanner input;

public void openFile(){ //method to open a file

try {

input = new Scanner(new File("d:\\amu.txt"));

}catch (FileNotFoundException fnfe )

{ System.err.println("Error opening file." +fnfe ); } // end of catch

} // end method openFile


public void readRecords() { // method to read record from file

ReadingFromFile record = new ReadingFromFile(); // object to be written to screen

System.out.printf( "%10s%12s%12s%10s\n", "account", "first name", "last name", "balance" );

try { // read records from file using scanner object

while ( input.hasNext() ){

record.account= input.nextInt() ; // read account number

record.firstName= input.next() ; // read first name

record.lastName= input.next() ; // read last name

record.balance= input.nextDouble() ; // read balance

// display record content

System.out.printf( "%10d%12s%12s%10.2f\n", record.account, record.lastName,


record.firstName, record.balance );

} // end while

} // end try

catch ( NoSuchElementException elementException )

{ System.err.println( "File improperly formed." );

input.close();

} // end catch 1

catch ( IllegalStateException stateException )

System.err.println( "Error reading from file." );

System.exit( 1 );

} // end catch 2

} // end method readRecords

public void closeFile() {// close file and terminate application

if ( input != null )

input.close(); // close file


} // end method closeFile

} // end class ReadingFromFile

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package readingfromfile;

/**

* @author Naray

*/

public class TestIO {

public static void main(String[] args) {

ReadingFromFile read = new ReadingFromFile ();

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);
}
});
}
}

Vous aimerez peut-être aussi