Unit 3 Fundamentals of Java Programming - Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Class Notes

Class: XII
Topic: Unit-3:
Subject: Information Technology (802) Fundamentals of Java Programming_Notes

JOptionPane Message:
We use JOptionPane when we want to request information from the user, display information to the user
or a combination of both. It requires an import statement at the top of the program.
import javax.swing.JOptionPane;
OR
import javax.swing.*;
Method Description
showMessageDialog() Shows a one-button, modal dialog box that gives the user some information.
Example : JOptionPane.showMessageDialog(this,"Java and NetBeans");
showConfirmDialog() Shows a three-button modal dialog that asks the user a question.
User can respond by pressing any of the suitable buttons.
Example: Confirm=JOptionPane.showConfirmDialog(null,"quit?")
showInputDialog() Shows a modal dialog that prompts the user for input.
It prompts the user with a text box in which the user can enter the relevant input.
Example : name= JOptionPane.showInputDialog(this,"Name:");

WAP to check whether a person is eligibile to vote or not using ELSE condition
import javax.swing.JOptionPane;
int a= Integer.parseInt(JTF1.getText());
if (a >=18)
JOptionPane.showMessageDialog(null,"You are eligible To VOTE");
else
JOptionPane.showMessageDialog(null,"You are NOT eligible To VOTE"); }

Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected. The
radio buttons are used to provide the user several choices and allow him to select one of the choices (the
radio buttons belong to a group allowing the user to select single option). But radio buttons occupy a lot of
space. Radio Button is created through jRadioButton component. (The radio button must be attached to a
button group).The ButtonGroup takes care of unselecting the previously selected button when the user
selects another button in the group.
Method Description
getText() Retrieves the text displayed by radio button.
String str = <radiobutton-name>.getText();
isSelected() Returns true if the component is checked else returns false.
boolean b = <radiobutton-name>.isSelected();
setText() Changes the display text at runtime.
<radiobutton-name>.setText(String t);
setSelected() Checks(true) or unchecks the radio button.
<radiobutton-name>.setSelected(boolean b);

Design a JAVA application to display the result of arithmetic operations based on the
option selected by the user through RADIO Button.
int n1=Integer.parseInt(JTF1.getText());
int n2=Integer.parseInt(JTF2.getText());
int r1=0;
if (JRBAdd.isSelected()==true){
r1=n1+n2;
}
else if (JRBSub.isSelected()==true){
r1=n1-n2;
}
else if (JRBMul.isSelected()==true){
r1=n1*n2;
}
else if (JRBDiv.isSelected()==true){
r1=n1/n2;
}
result.setText(""+r1);
Using the Text Area Component and CheckBox
CheckBox is a small box like component that is either marked or unmarked. When it is clicked, it changes
from checked to unchecked or vice versa automatically.
Method Description
getText() Retrieves the text typed in String str = <checkbox-name>.getText();
isSelected() Returns true if the component is checked else returns false. boolean b = <checkbox-
name>.isSelected();
setText() Changes the display text at runtime. <checkbox-name>.setText(String t);
setSelected() Checks(true) or unchecks the checkbox. <checkbox-name>.setSelected(boolean b);
The Text Area component is used if we want to accept multiline input or want to display multiline
output. This component automatically adds vertical or horizontal scroll bars as and when required
during run time.
Handling a Password Field Component
The Password Field if we want that the text input by the user should not be displayed as characters but as
special characters (so that it is not readable by anyone). This component allows confidential input like
passwords which are single line.
We can use the Password Field if we want that the text input by the user should not be displayed as
characters but as special characters (so that it is not readable by anyone). This component allows confidential
input like passwords which are single line. Let us design a simple application which displays a simple
message when the user inputs a user name and password.
Variable Naming Conventions
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.
Switch Statement
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.
The syntax of the switch statement is as follows:
switch (Variable/Expression)
{
case Value1:statements1 ;
break ;
case Value2:statements2 ;
break ;
.
.
default:statements3 ;
}

Write a program to display weekday using Switch Case statement.


int a = Integer.parseInt(JTF1.getText());
switch (a) {
case 1:
JTF2.setText("Monday");
break;
case 2:
JTF2.setText("Tuesday");
break;
case 3:
JTF2.setText("Wednesday");
break;
case 4:

JTF2.setText("Thursday");
break;
case 5:
JTF2.setText("Friday");
break;
case 6:
JTF2.setText("Saturday");
break;
case 7:
JTF2.setText("Sunday");
break;
default :
JTF2.setText("Invalid day No.");
break;
}
Combo Box: It allows only single item selection. It takes less space initially and drops down when the user
clicks on its arrow. User can edit if he/she wishes. It is a cross between a text field and a list.
Method Description
getSelectedItem() Retrieves the selected item.
Object result = <combobox-name>.getSelectedItem();
getSelectedIndex() Retrieves the index of the selected item.
int result = <combobox-name>.getSelectedIndex();
setModel() Sets the data model that the combo box uses to get its list of elements.
<combobox-name>.setModel (ComboBoxModel aModel);
List Box: It allows us to select more than one item. It does’nt have a drop down menu. Users can select
items directly.
Method Description
getSelectedValue() Returns the selected value when only a single item is selected, if
multiple items are selected then returns first selected value.
Returns null in case no item selected
Object result= <list-name>.getSelectedValue(); isSelectedIndex()
Returns true if specified index is selected.
boolean b = <list-name>.isSelectedIndex(int index)
WAP to display the admission fee of selected Class through LIST box
String s=(String)JL.getSelectedValue();
if (s.equals("IX")==true){
JTF.setText("15000");
}
else if (s.equals("X")==true){
JTF.setText("17000");
}
else if (s.equals("XI")==true){
JTF.setText("21000");
}
else {JTF.setText("25000");
}

JAVA
Java is a very popular high level programming language and has been used widely to create various types of
computer applications such as database applications, desktop applications, Web based applications, mobile
applications, and games among others. A Java compiler instead of translating Java code to machine language
code, translates it into Java Bytecode (a highly optimized set of instructions). When the bytecode (also
called a Java class file) is to be run on a computer, a Java interpreter, called the Java Virtual Machine
(JVM), translates the bytecode into machine code and then executes it.
The advantage of such an approach is that once a programmer has compiled a Java program into bytecode,
it can be run on any platform (say Windows, Linux, or Mac) as long as it has a JVM running on it. This
makes Java programs platform independent and highly portable.

Data Types and Variables:


Variables:
To store the program data we will use variables. A variable is a placeholder for data that can change its
value during program execution.
In our percentage calculator program, we will use three variables named marks_obtained,total_marks and
percentage. The variables marks_obtained and percentage are declared of type double, since they can have
fractional values (floating point numbers). Inside the main method, we declare these variables, we also
assign them values using the = operator as shown below:
int total_marks = 400;
double marks_obtained = 346;
double percentage = 0.0;
To calculate the percentage
percentage = (marks_obtained/total_marks)*100;
To display the percentage in the IDE output window
System.out.println("Student1's Percentage = "+percentage);

Primitive Data Types


In all, Java supports eight primitive data types, they are byte, int, long, short, float, double, Boolean, char.

1. Variable names can begin with either an alphabetic character, an underscore (_), or a dollar sign ($).
However, convention is to begin a variable name with a letter. They can consist of only alphabets, digits, and
underscore.
2. Variable names must be one word. Spaces are not allowed in variable names. Underscores are allowed.
3. There are some reserved words in Java that cannot be used as variable names, for example - int.
4. Java is a case-sensitive language.
5. It is good practice to make variable names meaningful. The name should indicate the use of that variable.
6. You can define multiple variables of the same type in one statement by separating each with a comma.

String Variables: we want variables to store textual data, for example, the name of a student.
To store more than one character, we use the String class in Java. Eg. String first_name = "Mayank";

Control Flow: Is a sequence of instructions. Java executes the instructions in sequential order, that is, one
after the other.

Selection Structures
In real life, you often select your actions based on whether a condition is true or false. For example, if it is
raining outside, you carry an umbrella, otherwise not.
The if Else Statement : The if statement in Java lets us execute a block of code depending upon whether an
expression evaluates to true or false.

The Switch Statement:


The switch statement is used to execute a block of code matching one value out of many possible values.
The structure of the Java switch statement is as follows:
switch (expression) {
case constant_1 : statements;
break;
case constant_2 : statements;
break;


default : statements;
break;
}

Repetition Structures
The ability of a computer to perform the same set of actions again and again is called looping. The sequence
of statements that is repeated again and again is called the body of the loop.
The test conditions that determine whether a loop is entered or exited is constructed using relational and
logical operators. A single pass through the loop is called an iteration.
For example, a loop that repeats the execution of the body three times goes through three iterations.
Java provides three statements – the while statement, the do while statement, and the for statement for
looping.
The for Statement
The for loop is the most widely used Java loop construct. The structure of the Java for statement is as below:
for (counter=initial_value; test_condition;change counter)
{
statements
}

Example: WAP to display the values from 1 to 5 using FOR loop


int i;
For (i=1; i <=5; i++)
{
System.out.println(“” + i);
}

While Statement
The while statement evaluates the test before executing the body of a loop. A while loop is an entry
controlled loop. The structure of the Java while statement is as shown:
The While Statement
while (expression)
{
statements
}

Example: WAP to print first 5 natural numbers using WHILE loop


int i = 0;
while (i<=5)
{
System.out.println("" + i);
i++;
}

Do While Statement
The do while statement evaluates the test after executing the body of a loop.
A do-while loop is an exit control loop.
The structure of the Java do while statement is as shown:
do
{
statements
} while (expression);

Example: WAP to print first 5 natural numbers using do while loop


int i = 0;
do
{
System.out.println("" + i);
i++;
}
while (i <=5);

ARRAY
An array is a collection of similar types of data. Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value. To declare an array, define the variable type
with square brackets [ ]:
Types of Array in java
There are two types of
array. Single Dimensional
Array Multidimensional
Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java
1. dataType[] arr; (or)
2. dataType arr[];
Instantiation of an Array in Java
1. arrayRefVar=new datatype[size];
For example, if we want to store the names of 100 people then we can create an array of the string type that
can store 100 names.
String[] array = new String[100];
Here, the above array cannot store more than 100 names. The number of values in a Java array is always
fixed.
How to declare an array in Java?
In Java, here is how we can declare an array.
dataType[] arrayName;
dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
arrayName - it is an identifier
For example:
double[] data;
Here, data is an array that can hold values of type double.

Access the Elements of an Array:


Example:
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}
}
Output: Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Array Element


To change the value of a specific element, we have to refer to the index number:
cars[0] = "Opel";
Example:
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
}

Output: Opel

Array Length
To find out how many elements an array has, use the length property:
Example:
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
}

Output: 4

Loop Through an Array


Using loop through the array elements with the for loop, and use the length property to specify how many
times the loop should run.
Example:
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}

Example:
public static void main(String args[]) {
int a[]=new int[5];
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);

Multidimensional Array in Java


A multidimensional array is an array containing one or more arrays.
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
1. dataType[][] arrayRefVar; (or)
2. dataType []arrayRefVar[];

To create a two-dimensional array, add each array within its own set of curly braces:
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers is now an array with two arrays as its elements.
To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the
element inside that array.
Example:
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x);
}

Output: 7

Example:
//Java Program to illustrate the use of multidimensional array
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}

Example:
To store the marks of a student 5 students:
// TODO add your handling code here:
double[]marks = {346, 144, 103, 256.5, 387.5};
double total_marks = 400;
System.out.println("\tClass Report");
System.out.println(" ");
System.out.println("RollNo\tMarks\tPercentage\tResult");
System.out.println(" ");
for (int i = 0; i <marks.length; i++) {
double percentage =
(marks[i]/total_marks)*100; String result;
if (percentage >= 40)
result = "Passed";
else
result = "Failed";
System.out.print((i+1)+"\t");
System.out.print(marks[i]+"\t");
System.out.print(percentage+"\t\t");
System.out.println(result);
}

Example:
WAP to sort an array of Strings in alphabetic order:
public static void main(String args[]) {
String[] names = {"Shruti", "Kunal", "Gungun","Avani","Ravi","Tripti","Purva","Aditya","Chandan"};
System.out.println("Names Array before Sorting:");
for (int i = 0; i<names.length; i++)
System.out.print(names[i] + ",");
System.out.println();
Arrays.sort(names);
System.out.println("Names after Sorting:");
for (int i=0; i < names.length; i++)
System.out.print(names[i] + ",");
System.out.println();

Common Coding Errors: Arrays


For example, if the array size is 5, then loop index = 5 is an off by one error since array index can go only
from 0 to 4.
double [] ] marks = new double [5];
for (int i = 0; i <= 5; i++) {
System.out.print(marks[i]);
}
In this case an Array index out of bounds error occurs and the program terminates unexpectedly with an
error as below.
Exception in thread "main”
java.lang.ArrayIndexOutOfBoundsException: 5
at javaprograms.ArrayDemo.main(ArrayDemo.java:11)
Java Result: 1

User Defined Methods


A method in Java is a block of statements grouped together to perform a specific task. A
method has a name, a return type, an optional list of parameters, and a body.
A method is a block of code which only runs when it is called. You can pass data, known as parameters, into
a method.
Methods are used to perform certain actions, and they are also known as functions.
The structure of a Java method is as below:
return_type method_name(list of parameters separated by commas)
{
statements
return statement
}

Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println()
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example:
static void myMethod() {
System.out.println("I got FULL MARKS IN IT!");
}
public static void main(String[] args) {
myMethod();
}

A method can also be called multiple times:


public class Main {
static void myMethod() {
System.out.println("I got FULL MARKS IN IT!");
}
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}
Call a Method
Given the length and breadth of a rectangle as parameters returns the area of the rectangle.
static double rectangle_area (double length, double breadth)
{
return (length * breadth);

When the length and breadth of the rectangle as arguments in the method call. The arguments with which the
rectangle_area method is called are copied into its parameters. In this case, 45.5 is copied into the parameter
length and 78.5 is copied into the parameter breadth.

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as variables inside the method.
Parameters are specified after the method name, inside the parentheses. You can add as many parameters as
you want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter. When the method is
called, we pass along a first name, which is used inside the method to print the full name:

public class Main {


static void myMethod(String fname) {
System.out.println(fname + " Abraham");
}
public static void main(String[] args) {
myMethod(“Thomas");
myMethod("Jenny");
myMethod(“Raju");
}

Multiple Parameters
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod(“Thomas", 10);
myMethod("Jenny", 18);
myMethod(“Raju", 38);
}

Note: When you are working with multiple parameters, the method call must have the same number of
arguments as there are parameters, and the arguments must be passed in the same order.

Return Values:
If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of
void, and use the return keyword inside the method:
public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
A Method with If...Else
public class Main {
// Create a checkAge() method with an integer parameter called age
static void checkAge(int age) {
// If age is less than 18, print "access denied"
if (age < 18) {
System.out.println("Access denied - You are not old enough!");

// If age is greater than, or equal to, 18, print "access granted"


} else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(20); // Call the checkAge method and pass along an age of 20

Object Oriented Programming


Java - What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations on the data,
while object-oriented programming is about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:


OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain,
modify and debug
OOP makes it possible to create full reusable applications with less code and shorter development time

Java - What are Classes and Objects?


Classes and objects are the two main aspects of object-oriented programming.
Class – Car
Objects – Maruti, Hyundai, Volvo, Audi, Toyota

Object Oriented Programming


Java's most fundamental feature – Classes and Objects. Java is an Object Oriented Programming (OOP)
language. In an OOP language, a program is collection of objects that interact with other objects to solve a
problem. Each object is an instance of a class.

A class is a physical or logical entity that has certain attributes. The title, author, publisher, genre and price
are the data members of the class Book. Displaying book details and getting its price are method members
of the class Book. Method members can get, set or update the class data members.
Class - Book
Data Members – Title, Author, Publisher, Genre, Price
Method Members - display(), getPrice()

For example one book in the library would be an object populated with the following data members:
Book: book1, Title: Game of Thrones, Author: George R Martin, Publisher: Harper Collins
Genre: Fiction, Price: 450
Another book would be another object populated with the following data members:
Book: book2, Title: Fundamentals of Database Systems, Author: Shamkant Navathe
Publisher: Pearson, Genre: Educational, Price: 400
All objects of the same class have the same type of data members.
Class Design
A class in Java begins with the keyword class followed by the name of the class. The body of the class is
enclosed within curly braces. The body contains the definitions of the data and method members of the class.
The data members are defined by specifying their type. The method members of the class are defined just
like the user defined methods we saw earlier. The method members have access to all the data members of
the class and can use them in their body. The data members of a class are like global variables – they can be
accessed by all the method members of the class.

Constructors
A special method member called the constructor method is used to initialize the data members of the class
(or any other initialization is to be done at time of object creation).
The constructor has the same name as the class, has no return type, and may or may not have a parameter
list. Whenever a new object of a class is created, the constructor of the class is invoked automatically.

Access Modifiers
Data members of a class can be accessed from outside the class by default. However, it is generally not good
programming practice to allow data members to be accessed outside the class. By allowing objects to change
their data members arbitrarily, we lose control over the values being held in them. This makes debugging
code harder and our code vulnerable to security issues. To make a data member or a method member of a
class visible only within the class, we add the keyword private before its declaration. Private members of a
class cannot be accessed outside the class. Declaring the data members of the Book class private, we won't
be allowed access to them in the class

Getter and Setter Methods


Private data members of a class cannot be accessed outside the class however, you can give controlled access
to data members outside the class through getter and setter methods. A getter method returns the value of a
data member.
For example we could define a getter method in the Bookclass for the price data member as given below:
double getPrice ( ) {
return price;
}

Similarly, we define a setter method but control how the price is set. We do not allow a book price to
become lower than 100.00.
void setPrice(double newprice) {
if (newprice < 100)
System.out.println("Price cannot be set lower than 100!");
else
price = newprice;
}

Java Libraries
The power of Java comes from the hundreds of Java classes that are already prebuilt and can be used in your
programs. To use a prebuilt class and associated methods in those class, all you have to do is to use the
keyword import to import the class from the package in which it is contained into your space. The import
statements must appear before any class definitions in the file.

Data Input
A program is interactive if it is able to take input from the user and respond accordingly.
Write a program to take user input. To take user input we use the prebuilt Scanner class. This class is
available in the java.util package. First we import this class,
import java.util.Scanner;

Now we create an object of the class Scanner. The constructor of this class requires the source from which
input is to be taken. Since we will take input from the console, we use the System.in object.
Scanner user_input = new Scanner(System.in);
Then, we invoke the next() method of the Scanner class that returns the token read from the input stream as a
String object.
String name = user_input.next();
System.out.println("Hello "+ name);

To read numeric data input, again a Java prebuilt class comes to our rescue. This time we use the
Integer class. The class has a static method parseInt() that takes a String as parameter and returns the
equivalent integer.
String age_string = user_input.next( );
int age = Integer.parseInt(age_string);
System.out.print("In 5 years you will be "+ (age +5));
System.out.println(" years old.");

Array Manipulation
The Arrays class has a number of useful methods. Let us start by using the sort()method to sort an array of
integers in ascending order.

import java.util.Arrays class. Then in the main() method, we invoke the Arrays.sort() method on the array
we need to sort.
double[ ] marks = {103, 144, 256.5,346, 387.5};
Arrays.sort(marks);

String Manipulation
The first method we will use from the String class is the toUpperCase() method. This method converts a
string to all uppercase letters.
String myString = "Hello World";
System.out.println("UpperCase: " + myString.toUpperCase());

The output of the code given above will be:


HELLO WORLD

Assertions: An assertion is a useful mechanism for effectively identifying/detecting and correcting logical
errors in a program. An assert statement states a condition that should be true at a particular point during the
execution of the program.
There are two ways to write an assertion
assert expression;
assert expression1 : expression2

The first statement evaluates expression and throws an AssertionError if expression is false. The second
statement evaluates expression1 and throws an AssertionError with expression2 as the error message if
expression1is false.

The program fragment below demonstrates usage of the assert statement.


assert age >= 18:"Age not Valid";
When this statement is executed, we assert that the value of the variable age should be >= 18. If it is not, an
AssertionError is thrown and the error message “Age not Valid” is returned.

Threads: Threads allows a program to operate more efficiently by doing multiple things at the same
time. Threads can be used to perform complicated tasks in the background without interrupting the main
program.
In Java, threads can be created in two ways
1. By extending the Thread class
2. By implementing the Runnable interface
The first method to create a thread is to create a class that extends the Thread class from the java.lang
package and override the run() method. The run() method is the entry point for every new thread that is
instantiated from the class.
public class ExtendThread extends Thread {
public void run() {
System.out.println("Created a Thread");
for (int count = 1; count <= 3; count++)
System.out.println("Count="+count);
}

Wrapper Classes: Sometimes, you may need to pass the primitive datatypes by reference. That is when you
can use wrapper classes provided by Java. These classes wrap the primitive datatype into an object of that
class. For example, the Integer wrapper class holds an int variable.
Consider the following two declarations:
int a = 50;
Integer b = new Integer(50);
In the first declaration, an int variable is declared and initialized with the value 50. In the second declaration,
an object of the class Integer is instantiated and initialized with the value 50. The variable a is a memory
location and the variable b is a reference to a memory location that holds an object of the class Integer.

Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}

Another useful method is the toString() method, which is used to convert wrapper objects to strings.
In the following example, we convert an Integer to a String, and use the length() method of the String class
to output the length of the "string":
public class Main {
public static void main(String[] args) {
Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
}
}

The for Statement


The for loop is the most widely used Java loop construct. The structure of the Java for statement is as
below:
for (counter=initial_value; test_condition;change counter)
{
statements
}
Semicolons separate the three parts of a for loop:
The initial_value initializes the value of the loop counter.
The test_condition tests whether the loop should be executed again.
The loop is exited when the test condition fails.
The step updates the counter in each loop iteration.

WAP to display the values from 1 to 5 using FOR loop


int i;
for (i=1; i <=5; i++)
{
System.out.println(“” + i);
}

WAP to display first 5 Even numbers using FOR loop.


int i;
for (i=2; i <=10; i=i+2)
{
System.out.println(i);
}

Use of Break statement inside loop


int i;
for (i=1; i <=5; i++)
{
if (i ==3) {
break;
}
System.out.println(i);
}

Use of Continous statement inside loop


int i;
for (i=1; i <=5; i++)
{
if (i ==3) {
continue;
}
System.out.println(i);
}

The while statement evaluates the test before executing the body of a loop. A while loop is an entry
controlled loop. The structure of the Java while statement is as shown:
The While Statement
while (expression)
{
statements
}

WAP to print first 5 natural numbers using WHILE loop


int i = 1;
while (i<=5)
{
System.out.println("" + i);
i++;
}

The Do While Statement


The do while statement evaluates the test after executing the body of a loop.
A do-while loop is an exit control loop.
The structure of the Java do while statement is as shown:
do
{
statements
} while (expression);

WAP to print first 5 natural numbers using do while loop


int i = 1;
do
{
System.out.println("" + i);
i++;
}
while (i <=5);

The Switch Statement:


The switch statement is used to execute a block of code matching one value out of many possible values.
The structure of the Java switch statement is as follows:
switch (expression) {
case constant_1 : statements;
break;
case constant_2 : statements;
break;


default : statements;
break;
}

WAP to display weekday by using Switch Case Statement


int today = 5;
String day = "";
switch (today) {
case 1: day = "Monday";
break;
case 2: day = "Tuesday";
break;
case 3: day = "Wednesday";
break;
case 4: day = "Thursday";
break;
case 5: day = "Friday";
break;
case 6: day = "Saturday";
break;
case 7: day = "Sunday";
break;
default: day = "Incorrect Day!";
break;
}
System.out.println (day);

Exception Handling
Some of your programs when executed may have terminated unexpectedly with runtime errors. The errors
could have occurred because an array index reference was out of range, or an attempt was made to divide an
integer by zero, or there was insufficient computer memory and so on. Such an error situation that is
unexpected in the program execution and causes it to terminate unexpectedly is called an exception. As a
programmer, you should anticipate exceptions in your program that could lead to unpredictable results and
handle the exceptions.
Java provides an exception handling mechanism so that a program is able to deal with exceptions, and
continue executing or terminate gracefully. The basic idea in exception handling is to
 Denote an exception block - Identify areas in the code where errors can occur
 Catch the exception - Receive the error information
 Handle the exception - Take corrective action to recover from the error
Java provides the following keywords to handle an exception:
try - A try block surrounds the part of the code that can generate exception(s).
catch – The catch blocks follow a try block. A catch block contains the exception
handler - specific code that is executed when the exception occurs. Multiple catch
blocks following a try block can handle different types of exceptions.
The structure of a try-catch statement block for exception handling is as below:
try {
// Part of the program where an exception might occur
}
catch (exceptiontype1 argument1) {
// Handle exception of the exceptiontype1
}
catch (exceptiontype2 argument2) {
// Handle exception of the exceptiontype2
}
finally {
//Code to be executed when the try block exits
}

The try block is examined during execution to detect any exceptions that may be thrown by any
statements or any calls to methods within the block. If an exception is thrown, an exception object is created
and thrown. The program execution stops at that point and control enters the catch block whose argument
matches the type of the exception object thrown. If a match is found the statements in that catch block are
executed for handling the exception. If no exception is thrown during execution of the statements in the try
block, the catch clauses that follow the try block are not executed. Execution continues at the statement after
the last catch clause. The optional finally block is always executed when the try block exits. This means
the finally block is executed whether an exception occurs or not.

Database Connectivity
Connecting a database to a Java program is easy with NetBeans since it allows us to connect directly to a
MySQL server.
Connecting to the MySQL Server in NetBeans
Step 1: Click on the Services tab located on the left side of the NetBeans IDE. Right click the Databases
node and select Register MySQl Server

Step 2: In the MySQL Server Properties Dialog Box that opens up, type in the Administrator User Name
(if not displayed). Also type in the Administrator Password for your MySQl Server. Check the Remember
Password checkbox and click on OK

Step 3: In the same MySQL Server Properties Dialog Box, click on the Admin In the Path/URL to admin
tool field, type or browse to the location of your MySQL Administration application mysqladmin (you will
find it in the bin folder of your MySQL installation directory).
In the Path to start command, type or browse to the location of the MySQL start command mysqld (you
will find it in the bin folder of your MySQL installation directory).
In the Path to stop command field, type or browse to the location of the MySQL stop command
mysqladmin (you will find it in the bin folder of your MySQL installation directory). In the Arguments
field, type -u root stop to grant root permissions for stopping the server. When finished, the Admin
Properties tab should appear similar to Figure 3.11(c). Click on OK.
The MySQL Server should now appear under the Database node in the Services tab in the NetBeans IDE
Step 4:To connect the MySQL Server to NetBeans, under the Databases node, right click the MySQL
Server at localhost:3306 [root] (disconnected) and select Connect

Step5: When the server is connected you should see the [disconnected] removed from the MySQL Server
at localhost:3306 [root] database. You should also be able to expand the MySQL Server node by Clicking
on the + sign to view all the available MySQL databases

Adding the MySQL Connector JAR to the NetBeans Libraries


Before writing the Java program to connect to the database, we also need to add the mysql connector JAR
file to the Libraries in our project.

Step1: Under the Projects tab, right click on the Libraries node and select ADD JAR/Folder…
Step 2: In the Add JAR/Folder dialog box that appears, navigate to the your NetBeans Installation
Folder. Then navigate to the /ide/modules/ext folder and select the mysql-connector-java-5.1.23-bin.jar
file. Click on Open

Each database driver has a different syntax for the URL. The MySQl URL has a hostname, the port, and the
database name. In our program we construct a String with hostname as localhost, port number as 3306, and
the database name as bookstore.
String dbURL = "jdbc:mysql://localhost:3306/bookstore";

We also assign the username and password, this has to be the same username and password that is used for
starting the MySQL Server.
String username ="root";
String password = "password";
Next, we invoke the getconnection() method using the URL, username, and password:
Connection dbCon =DriverManager.getConnection(dbURL, username, password);
Next, we use the Connection object returned by the getconnection() method and invoke the
createStatement() method. This method returns a Statement object for sending SQL statements to the
database.
Statement stmt = dbCon.createStatement();

Next, we invoke the executeQuery() method of the Statement object to execute an SQL query. This method
returns a single ResultSet object. The ResultSet is a table of data returned by a specific SQL statement.
String query ="select * from book";
ResultSet rs = stmt.executeQuery(query);

Finally, we use the next() method of the ResultSet object to iterate through all the rows of data returned by
the query. When there are no more rows left, the next() method will return false. Since we know there are 5
columns in the book table.
we use a for loop and the getString() method of the ResultSet object to print all the five columns.
while(rs.next()){
for (int i = 1; i <=5; i++) {
System.out.print(rs.getString(i));
System.out.print("|");
}
System.out.println();
}

All the statements described above have to be put in a try catch block to catch Exceptions (of the Exception
type SQL Exception) that can occur while connecting or fetching data from the database.

Assignment:
1. Write a program in Java to print the square of every alternate number of an array.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy