0% found this document useful (0 votes)
4 views

javaa notes

This document provides an overview of the NetBeans Integrated Development Environment (IDE) for Java programming, detailing its components, functionalities, and steps for creating Java applications. It covers key concepts of Object-Oriented Programming (OOP), variable declaration, control structures, and practical implementations for handling GUI events and user inputs. Additionally, it includes common methods and their uses, along with examples to aid in understanding Java programming fundamentals.

Uploaded by

jyotinanda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

javaa notes

This document provides an overview of the NetBeans Integrated Development Environment (IDE) for Java programming, detailing its components, functionalities, and steps for creating Java applications. It covers key concepts of Object-Oriented Programming (OOP), variable declaration, control structures, and practical implementations for handling GUI events and user inputs. Additionally, it includes common methods and their uses, along with examples to aid in understanding Java programming fundamentals.

Uploaded by

jyotinanda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Unit 5: Fundamentals of Java Programming

Chapter 1: Understanding Integrated


Development Environment (NetBeans)

Introduction to NetBeans IDE


NetBeans IDE is a popular, open-source integrated development environment used for Java programming. It
provides a user-friendly interface that simplifies Java application development using a graphical user
interface (GUI) approach. Developers can use the drag-and-drop feature to design forms quickly without
extensive coding.

Components of NetBeans IDE

1. Title Bar - Displays the name of the current project or file being worked on.
2. Menu Bar - Contains options such as File, Edit, View, Run, and more, allowing access to various
functionalities.
3. Toolbars - Provide quick access to frequently used tools and commands.
4. GUI Builder - Enables users to design graphical user interfaces in two modes: Design View (visual
interface layout) and Source View (where code is edited).
5. Palette - Contains essential GUI components such as buttons, text fields, labels, and more.
6. Inspector Window - Displays a hierarchy of all components placed in the current form, allowing
users to manage them effectively.
7. Properties Window - Enables customization of component properties, such as text, color, font, and
alignment.
8. Code Editor Window - The main area where developers write and edit Java code.

Components and Controls


 Parent/Container Controls: Act as a background for child controls (e.g., JFrame).
 Child Controls: Placed inside parent controls (e.g., JTextField, JLabel, JButton).

NetBeans provides various GUI components that can be used to create interactive applications. Below is a
summary of the most common components, their definitions, and frequently used properties and methods.

Component Definition Common Properties Common Methods


Main container window for title, setTitle(),
JFrame
Java applications. defaultCloseOperation setDefaultCloseOperation()
A clickable button that getText(), setText(),
JButton text, enabled, background
performs an action. setEnabled()
getText(), setText(),
JTextField A single-line text input field. text, editable, columns
setEditable()
Displays static text or an
JLabel text, font, foreground getText(), setText()
image.
text, rows, columns,
JTextArea A multi-line text input field. getText(), append(), setText()
lineWrap
A single-line secure input
JPasswordField echoChar, text getPassword(), setEchoChar()
field for passwords.
Component Definition Common Properties Common Methods
Allows selection of one text, selected,
JRadioButton isSelected(), setSelected()
option from a group. buttonGroup
Allows multiple selections
JCheckBox text, selected isSelected(), setSelected()
from options.
A drop-down menu for selectedItem, model, getSelectedItem(),
JComboBox
selecting an option. enabled setSelectedItem()

Steps to Create a New Project in NetBeans

1. Select New Project from the File menu.


2. Choose Java Application and click Next.
3. Enter a project name and location.
4. Click Finish.

Create a New JFrame Form

1. Open NetBeans and go to your project.


2. Right-click on the Source Packages or your specific package (e.g., mycalculator).
3. Select New > JFrame Form.
4. Name the form (e.g., CalculatorFrame).
5. Click Finish.

Now, a new file (CalculatorFrame.java) is created in your project with a graphical design interface.

Open the JFrame Form in Design View

1. Double-click the newly created CalculatorFrame.java file.


2. It will open in Design View, where you can visually add components.

Add Components to JFrame

1. Open the Palette Window (on the right side in NetBeans).


2. Drag and drop the components you need, such as:
o JButton (for actions like addition, subtraction, etc.).
o JTextField (for user input).
o JLabel (for displaying results).
o JPanel (for organizing layout).
3. Resize and arrange the components as needed.

Add Event Handling (Make Buttons Work)

1. Double-click on a button (e.g., btnAdd).


2. NetBeans will switch to Source View and generate an event method:

java
CopyEdit
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// Code to handle button click event
}

3. Write Java Code inside the method to define the button's behavior.
Object-Oriented Programming (OOP)
OOP is a programming paradigm that focuses on using objects and classes. The key concepts include:

 Class: A blueprint for creating objects.


 Object: An instance of a class with attributes and behaviors.
 Encapsulation: Wrapping data and methods into a single unit.
 Inheritance: Allowing one class to inherit properties of another.
 Polymorphism: Allowing methods to have multiple implementations.

Data Members and Methods

 Data Members: Variables that store object attributes.


 Methods: Functions that define object behavior.

Main Functions Used in This Chapter and Their Uses

1. setText(String text)

📌 Use: Sets or updates the text of GUI components like JTextField, JLabel, and JButton.
📌 Example:

jTextField1.setText("Hello, Java!");

📌 Explanation: This sets the text inside jTextField1 to "Hello, Java!".

2. getText()

📌 Use: Retrieves the current text from text-based components like JTextField and JTextArea.
📌 Example:

String name = jTextField1.getText();

📌 Explanation: This stores the user input from jTextField1 into the variable name.

3. getPassword()

📌 Use: Retrieves the text entered in a JPasswordField, returning it as a char[] for security.
📌 Example:

char[] password = jPasswordField1.getPassword();

📌 Explanation: This gets the password input securely, instead of using getText() which is less secure.

4. isSelected()
📌 Use: Checks if a JRadioButton or JCheckBox is selected.
📌 Example:

if (jRadioButton1.isSelected()) {
System.out.println("Option Selected");
}

📌 Explanation: If the radio button is selected, it prints "Option Selected".

5. setEnabled(boolean value)

📌 Use: Enables or disables a component (e.g., a button or text field).


📌 Example:

jButton1.setEnabled(false);

📌 Explanation: This disables jButton1, preventing the user from clicking it.

6. JOptionPane.showMessageDialog(Component parent, String message)

📌 Use: Displays a simple message dialog box.


📌 Example:

JOptionPane.showMessageDialog(null, "Hello, User!");

📌 Explanation: This shows a pop-up window with "Hello, User!".

7. JOptionPane.showConfirmDialog(Component parent, String message)

📌 Use: Displays a confirmation dialog with Yes/No options.


📌 Example:

int choice = JOptionPane.showConfirmDialog(null, "Are you sure?");

📌 Explanation: This asks the user "Are you sure?" and stores their choice in choice (Yes = 0, No = 1,
Cancel = 2).

8. JOptionPane.showInputDialog(Component parent, String message)

📌 Use: Displays an input dialog box for the user to enter data.
📌 Example:

String name = JOptionPane.showInputDialog(null, "Enter your name:");

📌 Explanation: This prompts the user to enter their name and stores it in name.
9. Integer.parseInt(String text)

📌 Use: Converts a String into an int.


📌 Example:

int age = Integer.parseInt(jTextField1.getText());

📌 Explanation: This converts the text from jTextField1 into an integer value.

10. Double.parseDouble(String text)

📌 Use: Converts a String into a double.


📌 Example:

double price = Double.parseDouble(jTextField1.getText());

📌 Explanation: This converts text input from jTextField1 into a decimal number.

11. setDefaultCloseOperation(int operation)

📌 Use: Defines what happens when the JFrame is closed.


📌 Example:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

📌 Explanation: This closes the application when the JFrame window is closed.

12. switch Statement

📌 Use: Allows multi-way branching based on a variable’s value.


📌 Example:

switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Invalid day");
}

📌 Explanation: This prints the corresponding day of the week based on the value of day.

13. System.exit(int status)

📌 Use: Terminates the program.


📌 Example:

System.exit(0);
📌 Explanation: This closes the application immediately.

14. append(String text)

📌 Use: Adds text to an existing JTextArea.


📌 Example:

jTextArea1.append("New line of text\n");

📌 Explanation: This adds "New line of text" to the JTextArea.

15. setSelected(boolean value)

📌 Use: Selects or unselects a radio button or checkbox.


📌 Example:

jCheckBox1.setSelected(true);

📌 Explanation: This pre-selects jCheckBox1.

16. getSelectedItem()

📌 Use: Retrieves the selected item from a JComboBox.


📌 Example:

String selection = jComboBox1.getSelectedItem().toString();

📌 Explanation: This gets the currently selected option from a drop-down list.

Summary Table of Functions

Function Use

setText(String text) Sets text in JTextField, JLabel, or JButton.

getText() Gets text from a text-based component.

getPassword() Retrieves password input securely.

isSelected() Checks if a radio button or checkbox is selected.

setEnabled(boolean value) Enables or disables a component.

JOptionPane.showMessageDialog() Displays a message dialog.


Function Use

JOptionPane.showConfirmDialog() Shows a Yes/No confirmation dialog.

JOptionPane.showInputDialog() Prompts user input via a pop-up.

Integer.parseInt(String text) Converts text to an integer.

Double.parseDouble(String text) Converts text to a decimal.

setDefaultCloseOperation() Defines the JFrame close behavior.

switch Statement Allows multi-case branching.

System.exit(int status) Terminates the program.

append(String text) Appends text to a JTextArea.

setSelected(boolean value) Pre-selects a radio button or checkbox.

getSelectedItem() Retrieves selected item from a JComboBox.

GUI-Based Practical Implementations with Detailed Explanations


Handling Events in Java GUI

 Events occur when a user interacts with components.


 Example: Clicking a button triggers an action.

Displaying Message in a Dialog Box

Explanation:

 JOptionPane is a class in javax.swing used to create pop-up dialogs.


 showMessageDialog displays a simple message in a pop-up window.
 he first parameter (null) means the dialog is centered on the screen.
 The second parameter ("Hello, User!") is the message to be displayed.

Using TextField to Display a Message


Explanation:

 setText() updates the displayed text inside a JTextField.

Using TextField Component to Accept Input

Explanation:

 getText() retrieves the current text entered into the JTextField.

Creating a Simple Application

1. Create a new JFrame Form.


2. Add components using drag-and-drop.
3. Modify properties using the Properties Window.
4. Write Java code in the Source Window.
5. Attach event handlers to components.
6. Run the application.

Example: Button to Exit Application

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

System.exit(0);

PRACTICAL 1 (GOOD MORNING-EVENING PRACTICAL)


Handling Radio Button Component

PRACTICAL 2 (mr-mrs radio button)

Important step :-

1. Add an button group (leave anywhere in the form)


2. Select both radio button>right click>properties>buttonGroup>buttonGroup1
Using Text Area Component

PRACTICAL 3 (friends and colleagues)


Handling a password field component

PRACTICAL 4 (password field)


PRACTICAL 5 (Price Calculator Application)
PRACTICAL 6 (Price Calculator Application- using numbers and decimals)
Variable Declaration in Java

Variable declaration means telling Java:

 What type of data the variable will store (double, int, String, etc.).
 What name the variable will have (num1, num2, etc.).
 Sometimes, an initial value (like = Double.parseDouble(...)).

Declaration Example Comment

int Apples; Simple declaration of an integer variable named Apples.

float Sum = 4; Declaration of a float variable named Sum which has an initial value of 4.0.

Variable Naming Conventions

As mentioned above, each variable needs to have a name so that it can be referenced anywhere during the
application. Each programming language has its own set of rules for naming variables. The rules and conventions for
naming variables in Java are summarized below:

● Variable names are case sensitive.

● Keywords or words, which have special meaning in java, should not be used as the variable names.

● Variable names should be short and meaningful.

● All variable names must begin with a letter, an underscore (_) or a dollar sign ($). The convention is to always use a
letter and avoid starting variable names with underscore (_) and dollar sign ($).

● After the first initial letter, variable names may contain letters and digits (0 to ● 9) and (_,$), but no spaces or
special characters are allowed.

Acceptable Variable Names - Grade, Test_Grade, TestGrade

Unacceptable Variable Names - Grade(Test), 2ndTestGrade, Test Grade, Grade_Test#2 Try to

Java variable names are case sensitive, so sum1 and SUM1 aren't the same variable.

Example
Explanation:

 int age = 25; declares an integer variable named age and assigns it a value of 25.
 String name = "John"; declares a string variable to store text values.
 boolean isStudent = true; declares a boolean variable that can hold either true or false.

PRACTICAL 7 (variable declaration- character variables)


PRACTICAL 8 (variable declaration- making an operator calculator)
Examples of Variable Declarations in Your Code:

 double num1; → Declares a variable to store a decimal number.


 double result; → Declares a variable to store the calculation result.

Without declaring variables, you cannot store values and perform calculations.

PRACTICAL 9 (variable declaration-Simple Interest Calculator)


Control Structures in Java
Control structures are fundamental constructs in Java that control the flow of execution based on certain
conditions or repetitions. They determine how and when certain parts of the program will execute.

Types of Control Structures in Java

There are three main types of control structures:

1. Sequential Control Structure

The default flow of execution, where statements execute one after another in the order they are
written. (Each statement runs one after the other)
 Example:

2. Selection Statements/ Selection Control Structure (Decision Making)

 Used to execute specific code based on conditions.


 Types:
o if Statement
o if-else Statement
o if-else-if Ladder
o switch-case Statement
Selection Statements vs Conditional Statements

Simple if Statement in Java

An if statement is a conditional statement that executes a block of code only if a specified condition is
true.

Syntax:

Example:
Explanation:

1. The condition number > 0 is checked.


2. Since 10 > 0 is true, the code inside the if block runs.
3. Output:
4. The number is positive.

If the condition is false, the code inside the if block does not execute.

Points to remember about if statement:

• The conditional expression is always enclosed in parenthesis.

• The conditional expression may be a simple expression or a compound

expression.

• Each statement block may have a single or multiple statements to be executed. In

case there is a single statement to be executed then it is not mandatory to enclose

it in curly braces ({}) but if there are multiple statements then they must be enclosed

in curly braces ({}).

• The else clause is optional and needs to be included only when some action is to

be taken if the test condition evaluates to false.

Simple if-else Statement in Java/

An if-else statement is a conditional statement that executes one block of code if the condition is true
and another block if the condition is false.

Syntax:
Example:

Explanation:

1. The condition number > 0 is checked.


2. Since -5 > 0 is false, the else block executes.
3. Output:
4. The number is not positive.

This ensures that one of the two blocks is always executed.


PRACTICAL 10 (Voting Eligibility Checker- simple if-else statement)
.
PRACTICAL 11 (Week Day Finder- multiple if-else ladder)
PRACTICAL 12 (Vote eligibility check- nested if-else)
Switch Statement for Multi-Case Decision Making

 This selection statement allows us to test the value of an expression with a series of
character or integer values.
 On finding a matching value the control jumps to the statement pertaining to that
value and the statement is executed, till the break statement is encountered or the
end of switch is reached.
 The expression must either evaluate to an integer value or a character value.
 It cannot be a string or a real number.

SYNTAX
PRACTICAL 13 (SWITCH STATEMENT – DISCOUNT CALCULATOR)
DATA TYPES

 States the way the valies of that data type are stored, the operations that can be done on
that type, and the range for that type.

You might also like