You are on page 1of 17

CSS 1021

Object Oriented Programming


BS 2020
Department of CS and SE

Lab Session 1: Introduction to Java NetBeans


NetBeans IDE - The Smarter and Faster Way to Code
NetBeans is a Java-based integrated development environment (IDE). The term also refers to the IDE’s
underlying application platform framework.
The IDE is designed to limit coding errors and facilitate error correction with tools such as the NetBeans
FindBugs to locate and fix common Java coding problems and Debugger to manage complex code with
field watches, breakpoints and execution monitoring. Although the NetBeans IDE is designed specifically
for Java developers, it also supports C/C++, PHP, Groovy, and HTML5 in addition to Java, JavaScript
and JavaFX.

Download and Install NetBeans IDE


Go to https://netbeans.org/downloads to download the latest version of NetBeans IDE. You will see the
following page:

On this download page you see different download bundles. And for Java development only, we can
choose either Java SE or Java EE. We’d recommend you to choose Java EE which supports
comprehensive Java development (Java EE includes Java SE).
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE
So, click the Download button in the column Java EE to download NetBeans installer for Java EE
development. The file name of the installer program is something like netbeans-8.2-javaee-
windows.exe (on Windows).
Click on the installer file to start installing NetBeans IDE. You will be asked to install GlassFish and
Apache Tomcat server:

In this tutorial, you don’t need any server. However, you will need them later so let check both, and
click Next.
In the next screen, check ‘I accept the terms in the license agreement’:
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE
Click Next.
In the next screen, choose the installation directory and JDK version for the IDE:

You can keep the defaults and click Next.


In the next screen, choose installation directory and JDK version for GlassFish server:
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE
Click Next to see the summary:

And click Install to start installing NetBeans with GlassFish and Tomcat servers. Wait until the setup
complete:

Click Finish.
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE
Now you can start NetBeans IDE from the start menu. The splash screen appears:

And you should see the home screen of NetBeans:

 
Create Your First Java Project
Now, let’s create a Java project using NetBeans IDE. Go to menu File > New Project…
Under the New Project dialog, choose Java application as shown in the following screenshot:
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE

Click Next to advance to the next step. In the New Java Application screen, type Project Name, specify
Project Location and the main class:

In the Project Name area at the top, type a Name for your Project. Notice how the text at the bottom
changes to match your project name (in the text box to the right of Create Main Class). Note that we
check the option Create Main Class to generate the main class for the application. Here we specify the
package name net.codejava before the class name HelloWorld.
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE
The default location to save your projects appears in the Project Location text box. You can change this,
if you prefer. NetBeans will also create a folder with your project name, in the same location. Click the
Finish button and NetBeans will go to work creating all the necessary files for you.
When NetBeans returns you to the IDE, have a look at the Projects area in the top left of the screen (if
you can't see this, click Window > Projects from the menu bar at the top of the software):
Click the plus symbol to expand your project, and you'll see the following:

Now expand Source Packages to see your project name again. Expand this and you'll see the Java file that
is your source code.
This same source code should be displayed to the right, in the large text area. It will be
called HelloWorld.java. If you can't see a code window, simply double click HelloWorld.java in your
Projects window above. The code will appear, ready for you to start work.

You should see the following components, (as shown in the figure above):

 Projects window: Top left, contains a tree view of the components of the project, including
source files, libraries that your code depends on, and so on.
 Source Editor: Central area, contains files, where most of your work will be done, currently with
a Java source file called Main open.
 Navigator: Lower left, useful for quickly navigating between elements within the selected class.
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE

Write Your First Java Code


You can see a code editor for the HelloWorld.java file as shown in the following screenshot:

The method main() is the main entry to a Java application. All Java programs start from
the main() method. Now, let’s type some code in this method to print “Hello World Java!” on the screen:

1 System.out.println("Hello World Java!");

The whole program should look like this:


CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE
NetBeans is very smart, as it compiles the code instantly while you are typing the code. So, if there’s any
error, the IDE will inform you by underling the errors with red color, as shown in the following
screenshot:

If there’s no red marks like this, the code is fine and we’re ready to run the program.
Notice that when you press Ctrl+Space, the editor shows you multiple ways of completing the code at the
cursor, as well as related documentation:

Run Your First Java Program


To run the HelloWorld program above, there are several ways:
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE

 Go to menu Run > Run Project <ProjectName>


 Click Run Project icon in the toolbar.
 Press F6 key.
 Right click in the code editor, and select Run File (or press Shift + F6).

You should see the output of this program like this:

You see, it prints “Hello World Java!”. Congratulations, you have successfully created and run your first
Java program with NetBeans IDE. You can modify the program and run again to experiment more.
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 HelloWorld.class is generated. You can see where the new
file is generated by opening the Files window and expanding
the HelloWorld/build/classes/helloworld node.

Debugging Program in NetBeans


Step 0: Write a Java Program
The following program computes and prints the factorial of n (=1*2*3*...*n). The program, however, has
a logical error and produce a wrong answer for n=20 ("The Factorial of 20 is -2102132736" - a negative
number?!).

1/** Compute the factorial of n */


2public class Factorial {
3 // Print factorial of n
4 public static void main(String[] args) {
5 int n = 20;
6 int factorial = 1;
7
8 // n! = 1*2*3...*n
9 for (int i = 1; i <= n; i++) {
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE

10 factorial *= i;
11 }
12 System.out.println("The Factorial of " + n + " is " + factorial);
13 }
14}

Let us use the graphic debugger to debug the program.

Step 1: Set an initial Breakpoint


A breakpoint suspends program execution for you to examine the internal states of the program. Before
starting the debugger, you need to set at least one breakpoint to suspend the execution inside the program.
Set a breakpoint at main() method by clicking on the left-margin of the line containing main(). A red
circle or an inverted Triangle appears in the left-margin indicating a breakpoint is set at that line.

Step 2: Start Debugging


Right click anywhere on the source code ⇒ "Debug File". The program begins execution but suspends its
operation at the breakpoint, i.e., the main() method.
As illustrated in the following diagram, the highlighted line (also pointed to by a green arrow) indicates
the statement to be executed in the next step.
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE

Step 3: Step-Over and Watch the Variables and Outputs


Click the "Step Over" button (or select "Step Over" in "Debug" menu) to single-step through your
program. At each of the step, examine the value of the variables (in the "Variable" panel) and the outputs
produced by your program (in the "Output" Panel), if any. You can also place your cursor at any variable
to inspect the content of the variable.

Single-stepping through the program and watching the values of internal variables and the outputs
produced is the ultimate mean in debugging programs - because it is exactly how the computer runs your
program!
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE

Step 4: Breakpoint, Run-To-Cursor, Continue and Finish


As mentioned, a breakpoint suspends program execution and let you examine the internal states of the
program. To set a breakpoint on a particular statement, click on the left-margin of that line (or select
"Toggle Breakpoint" from "Run" menu).
"Continue" resumes the program execution, up to the next breakpoint, or till the end of the program.
"Single-step" thru a loop with a large count is time-consuming. You could set a breakpoint at the
statement immediately outside the loop (e.g., Line 11 of the above program), and issue "Continue" to
complete the loop.
Alternatively, you can place the cursor on a particular statement, and issue "Run-To-Cursor" to resume
execution up to the line.
"Finish" ends the debugging session. Always terminate your current debugging session using "Finish" or
"Continue" till the end of the program.

Java Basics
Primitive Types

Using Integer, Byte, Short and Long


classTestNum
{
public static void main(String arg[])
{
intnum=5;
bytebnum=10;
shortsnum=20;
longlnum=50l; // Note: long variable must be appended by ‘L’
System.out.println("The integer is "+ num+"\n byte is "+bnum+"\n Short is"+snum+"\n
long is "+lnum);
}
}

Using Float and Double


classTestFloat
{
public static void main(String arg[])
{
floatnum=5f; // Note: float variable must be appended by ‘F’
doublebnum=10;
System.out.println("The float is "+ num+"\n double is "+bnum);
}
}
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE

Using Character and Boolean


classTestChar
{
public static void main(String arg[])
{
charch='A';
booleanbol=true;
System.out.println("The character is " + ch+ "\n The boolean value is "+bol);
}
}
Operators

Using Arithmetic, Increment and Decrement Operators


public class MyArithmetic
{
public static void main(String args[])
{
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
// Check the difference in d++ and ++d
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}

Using Comparison/Relational Operators


public class Compare
{
public static void main(String args[])
{
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}

Using Logical Operators


public class Test
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}

Using Assignment Operators


public class Test
{
public static void main(String args[])
{
int a = 10;
int b = 20;
int c = 0;

c = a + b;
System.out.println("c = a + b = " + c );

c += a ;
System.out.println("c += a = " + c );

c -= a ;
System.out.println("c -= a = " + c );

c *= a ;
System.out.println("c *= a = " + c );

a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE
a = 10;
c = 15;
c %= a ;
System.out.println("c %= a = " + c );
}
}

Using Ternary Operators


public class Test
{
public static void main(String args[])
{
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}
CSS 1021
Object Oriented Programming
BS 2020
Department of CS and SE

Exercises

1. Write a program in Java to implement the formula: Area = Length * Width and use arbitrary
values to find the area of a rectangle.
2. Write a program to calculate perimeter of a square.
3. Suppose a student has achieved 76 marks in English, 88 in Maths, 94 in Physics and 85 in
History. Write a code to find the percentage of the student.

You might also like