Unit III-Fundamentals of Java Programming
Unit III-Fundamentals of Java Programming
JAVA PROGRAMMING: 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. 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.
Integrated Development Environments (IDEs): There are a wide variety of Java Integrated Development
Environments (IDEs) available in the market that come equipped with a text editor and a Java compiler
thus simplifying writing, compiling and executing Java programs. Most of them are freely downloadable
from the Internet. We will be using the open source and free Java Net Beans IDE for writing Java
programs.
Step 2: All software development in NetBeans is organized in the form of Projects, so we begin a new
Project. In the IDE click File> New Project (Ctrl + Shift + N).
Step 3: In the New Project dialog box that appears, under the Categories list, select Java and under the
Projects list select Java Application (they should be already selected). Click on Next to create a new Java
Application Project.
S t e p 4 : In the New Java Application dialog box that appears, in the Project Name field, type a
name for the Project Figure 3.1(d). Here we have named the Project “HelloWorld”. When you type the
name of the project, the Project Folder field also changes automatically. So does the Create Main Class
field. You can optionally change the Project Location and the Project Folder by clicking the Browse
button. Click on Finish to finish creating the Java Application Project and to return to the IDE.
Step 6: In the IDE toolbar, click on File > Save (Ctrl + S) or File > Save All (Ctrl + Shift + S) to save the
HelloWorld.Java program
Step 7: In the IDE toolbar, click on Run > Run Main Project (F6)or Run >Run File (Shift +F6) to execute the
Java Program.
You can also run your program by clicking the green arrow button on the toolbar
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. Technically, a variable is the name for a storage location in the
computer's internal memory. The value of the variable is the contents at that location.
Datatype: Dataype is the type of data we are using in the Java NetBeans IDE (Ex. Int,Char, Long, Short,
Boolean).
Primitive Data Types: Java supports eight primitive data types.
String Variables: A variable of the primitive data type char can be used to store a single character. To
assign a value to a char variable we enclose the character between single quotes.
char middle_name = 'M';
To store more than one character, we use the String class in Java. To assign a text value to a String
variable we enclose the text between double quotes. For example,
String first_name = "Mayank";
String last_name = "Saxena";
To print char or String variables, we can use the System.out.println()method.
System.out.println(first_name+" "+ middle_name+" "+last_name);
The output from the statement given above is:
Mayank M Saxena
Operators: Operators are special symbols in a programming language and perform certain specific
operations.
Control Flow: A program is nothing but a sequence of instructions. Java executes the instructions in
sequential order, that is, one after the other. However, sometimes you might want to execute an
instruction only if a condition holds true. Or you may want to execute a set of instructions repeatedly
until a condition is met. Java provides selection structures for the former and repetition structures for
the latter.
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 structure of the Java if statement is as below.
Syntax for if Statement:
if (expression) {
statements
}
Example
if (percentage >= 40) {
System.out.println ("PASSED");
}
Syntax for if Else Statement:
if(expression) {
statements
}
else {
statements
}
Example
if (percentage >= 40) {
System.out.println("PASSED");
}
else {
System.out.println("FAILED");
}
The Switch Statement: The switch statement is used to execute a block of code matching one value out of
many possible values. If the expression evaluates to some constant = constant_1, the statements in the
case group constant_1 are executed. Similarly, if the expression evaluates to constant_2, the statements in
the case group constant_2 are executed. The break statement after each case group terminates the switch
and causes execution to continue to the statements after the switch. If there is no match for the expression
with any case group, the statements in the default part are executed. The expression in the switch
statement must evaluate to byte, short, int, or char.
Syntax for Switch Statement:
switch (expression) {
case constant_1 : statements;
break;
case constant_2 : statements;
break;
…
…
default : statements;
break;
}
Example
public class SwitchDemo {
public static void main (String[ ] args) {
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);
}
}
Repetition Structures: In real life you often do something repeatedly, for example, consider a task such as
reading a book, first you open the book, and then repeatedly - read a page; flip the page – until you get to
the end of the book, then close the book.
The While Statement: The while statement evaluates the test before executing the body of a loop. write
a program to print the squares of numbers from 1 to 5. The following steps need to be performed.
1. Initialize number = 1
2. Test if the number <= 5
3. If yes, print the square of the number;
Increment number (number = number + 1)
Go back to step 2
4. If no, exit the loop.
The tasks that need to be performed repeatedly are in step 3 – these constitute the body of the
loop. The test condition is in step 2.
The Do While Statement: The do while statement evaluates the test after executing the body of
a loop.
1. Initialize number = 1
2. Print the square of the number
3. Increment number (number = number + 1)
4. Test if the number <= 5
5. If yes, Go back to step 2
If no, Exit the loop
Syntax for Do While Statement:
do
{
statements
} while (expression);
Example:
public class DoWhileDemo {
public static void main (String[ ] args) {
int number = 1;
do {
System.out.print ("Square of " + number);
System.out.println (" = " + number*number);
++number;
} while (number <= 5);
}
}
The for Statement: The for loop is the most widely used Java loop construct.
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.
he step updates the counter in each loop iteration.
Syntax for For Statement:
for (counter=initial_value; test_condition;change counter)
{
statements
}
Example:
for (int number = 1; number<= 5; ++number)
{
System.out.print("Square of "+ number);
System.out.println(" = "+ number*number);
}
Arrays: Arrays are variables that can hold more than one value, they can hold a list of values of
the same type. Ex. double[] marks;
The two statements – declaring an array and specifying its size can also be done in one
statement. double[] marks = new double[5];
Now we can store five marks in the array, each element of the array is indexed by its position,
starting from 0. So the five elements of the array are available at positions 0 to 4 as given
below:
marks[0], marks[1], marks[2], marks[3], marks[4]
Note that the array index goes from 0 to n-1 for an array of size n and not from 1 to n. We can
initialize the array statically (that is at compile time) as shown below:
double[]marks = {346, 144, 103, 256.5, 387.5};
User Defined Methods: 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.
Syntax
return_type method_name(list of parameters separated by commas)
{
statements
return statement
}
Example
static double rectangle_area (double length, double breadth)
{
return (length * breadth);
}
Object Oriented Programming: 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.
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.
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.
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.
double getPrice ( ) {
return price;
}
we define a setter method but control how the price is set. We do not allow a book price to
become lower than 100.0.
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. To take user input we use the prebuilt Scanner class. This class is available in the
java.util package.
import java.util.Scanner;
Scanner user_input = new Scanner(System.in);
Array Manipulation: The Arrays class has a number of useful methods. Using the sort()method to
sort an array of integers in ascending order.
First we 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: to manipulate Strings using the String class present in the java.lang
package.
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
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, Such an error situation that is
unexpected in the program execution and causes it to terminate unexpectedly is called an
exception.
Java provides the following keywords to handle an exception:
1. try - A try block surrounds the part of the code that can generate exception(s).
2. 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.
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 Figure
Step 3: In the same MySQL Server Properties Dialog Box, click on the Admin Properties tab.
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.
Database Connection from Java: establish a database connection to the MySQL Server,
we invoke the getconnection() method of the DriverManager class. This method needs
three parameters –URL of the database, username, password to connect to the
database.
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
String dbURL = "jdbc:mysql://localhost:3306/bookstore";
Connection dbCon =DriverManager.getConnection(dbURL,
username, password);
Statement stmt = dbCon.createStatement();
String query ="select * from book";
ResultSet rs = stmt.executeQuery(query);
Threads: A multithreaded program is one that can perform multiple tasks concurrently
so that there is optimal utilization of the computer's resources. A multithreaded
program consists of two or more parts called threads each of which can execute a
different task independently at the same time.
In Java, threads can be created in two ways
1. By extending the Thread class
2. By implementing the Runnable interface
Wrapper Classes: By default, the primitive datatypes (such as int, float, and so on) of
Java are passed by value and not by reference. 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.
Consider the following two declarations:
int a = 50;
Integer b = new Integer(50);
Access to the value of a wrapper class object can be made through getter
functionsdefined in the class. For example, the intValue() member function of the
Integer wrapper class allows access to the int value held in it.
int c = a + b.intValue();
Another useful function defined in the Integer wrapper class lets you convert a string
into its integer value. The following statement converts the string “3456” into the
integer3456 and stores it in the int variable d.
int d = Integer.parseInt(“345”);
Note that the parseInt method is a static member of the Integer class and can be
accessed using the name of the class, that is, without creating an instance of the class.
String s = Integer.toString(3456);
*************************************END******************************************