Chapter-1Notes Updated
Chapter-1Notes Updated
Section 1
Introduction to Java
History
JDK
• The Java Development Kit (JDK) is an implementation of either one of the Java SE, Java EE or
Java ME platforms released by Oracle Corporation in the form of a binary product aimed at Java
developers on Solaris, Linux, Mac OS X or Windows.
JDK Editions
– JavaEE (formerly J2EE) can be used to develop server-side applications such as Java
servlets and Java ServerPages.
– JavaME (formerly J2ME) can be used to develop applications for mobile devices such as
cell phones.
• Compiling Programs
• Executing Applications
A Simple Application
Example 1.1
//to Java!
package chapter1;
System.out.println("Welcome to Java!");
• Comments
• Package
1
• Reserved words
• Modifiers
• Statements
• Blocks
• Classes
• Methods
Comments
In Java, comments are preceded by two slashes (//) in a line, or enclosed between /* and */ in one or
multiple lines. When the compiler sees //, it ignores all text after // in the same line. When it sees /*, it
scans for the next */ and ignores any text between /* and */.
Package
The second line in the program (package chapter1;) specifies a package name, chapter1, for the class
Welcome. compiles the source code in Welcome.java, generates Welcome.class, and stores
Welcome.class in the chapter1 folder.
Reserved Words
Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used
for other purposes in the program. For example, when the compiler sees the word class, it understands
that the word after class is the name for the class. Other reserved words in Example 1.1 are public,
static, and void.
Modifiers
Java uses certain reserved words called modifiers that specify the properties of the data, methods, and
classes and how they can be used. Examples of modifiers are public and static. Other modifiers are
private, final, abstract, and protected. A public datum, method, or class can be accessed by other
programs. A private datum or method cannot be accessed by other programs.
Statements
Blocks
Classes
The class is the essential Java construct. A class is a template or blueprint for objects. To program in
Java, you must understand classes and be able to write and use them. The mystery of the class will
continue to be unveiled throughout the discussions. For now, though, understand that a program is
defined by using one or more classes.
2
The structure of a Java class
The above part of the code is called a class segment and it denotes the starting and ending of a Java
class segment code.
Methods
main Method
The main method provides the control of program flow. The Java interpreter executes the application by
invoking the main method.
// Statements;
• The above part of the code is called a method, public denotes that this segment of the code can
be accessed outside the class without creating any new objects as denoted by the keyword
static. void means this part of the code does not return any value.
• The “main” part denotes the starting point of the Java program. When you run the program, Java
compiler locate for this part of the code and execute any code inside “main”. Always include a
“main” in your code.
Section 2
Kinds of data
Text
Numbers
Pointers
objects
3
Integer
double
Example
public static void main(String[ ] args) {
int age;
age = 20;
or
The Output
4
Some of the Java Rules when naming variables
• A variable name cannot start with a number. So you cannot call a variable 1stsalary or 20years.
• A variable name cannot be the same as a keyword used in Java. Keywords in Java NetBeans
appear in blue in the code window, like int, so you can’t miss them.
• A variable name cannot have a space e.g. my Age. If you want to have two words for a variable
name, just join them e.g. myAge or use an underscore e.g my_age.
• Variable names are case sensitive. So Age and age are different variable names.
5
Displaying the result
System.out.println(“My Gross Salary is: “+grossSalary);
• The maximum integer value is 2,147,483,647. If you want a minus number the lowest value you
can have is -2,147,483,648.
• If you want larger or smaller numbers than that then you can use a number variable of type
double.
• The double variable type is also used to hold floating point numbers i.e. numbers with a decimal
point like 18.7, 10.3,154.108 etc.
• If you store a floating point value in an int variable, NetBeans will underline the faulty code and if
you run the program, the compiler will display an error message.
6
Working with Variables of float type
• The double values can store really big numbers of the floating point type. So, Instead of using
double, float type can be used. When storing a value of a float type, we add letter "f" at the end
of that value but before the semicolon. See below:
• Multiplication and Division are treated equally, but have high priority than Addition and
Subtraction
• Addition and Subtraction are treated equally but have a lower priority than multiplication and
division
NOTE:
If you are going to use more than one arithmetic operator in one statement, it a good
practice to always use some parentheses so as to avoid some output errors derived from
operators’ precedence.
• To store just one character, the char type variable is used, but to store more than one character
String type variable is used. Mostly you will use String type variable as you may need to store
lots of characters.
• To define a string variable, type the word String followed by a name for your variable. Note that
there's an uppercase "S" for String and the line ends with a semicolon.
• String sir_name;
• String other_name;
• sir_name = “Benta”;
7
• other_name = “Smith”;
Remember:
A String variable has double quotes and a char variable has single quotes.
Section 2
• We want the program to request data from the user via the keyboard.
• To read input from the keyboard, we can use the standard java classes. We will need to use the
InputStreamReader class which is in the java.io package.
• To use this class, we must import the java.io package into this class.
import java.io.* ;
• This will create the reader and assign it to the variable varName. You can change varName to
whatever you want provided you follow the naming rules for a variable.
This code does the actual reading from the keyboard and converts it to Unicode characters. This
is not very useful to us as we want the information in a string. This is where the BufferedReader
comes in:
8
• The rules with the variable names apply here. Note that you cannot have the InputStreamReader
and BufferedReader with the same name. Also the varName within the brackets in the
BufferedReader must be the variable name or your InputStreamReader.
• Next, we want to read a line in. You can do this by the following:
• To read from the keyboard, you must also create a try catch block:
try {
• To use a try catch block, you place the code for reading the values in, in the try section and in the
catch block, you place any error messages, or what to do if there is an error.
try {
Within the try block, we will also ask the user to enter in their first name or the user won't know
what she/he is supposed to enter:
try {
9
import java.io.* ;
try {
• We also want to ask for the user’s birth year and the current year:
From this information, we want to calculate the person’s age. But there is a problem - how do you take a
string from another string. You can't, so we must change the string value into a numeric value. We will
convert the string values into Integer values using the parseInt function:
This code must go in a try catch block. You can then catch the conversion error:
• The next step is to calculate the age of the person and output all the data:
10
THE COMPLETE CODE
import java.io.* ;
try {
int age=tYear-bYear;
catch(NumberFormatException err) {
11
• Create a new class in myfirstprogram package. So, right click the package myfirstprogram,
select New option from the menu and then select Java Class.
• Delete all the comments in the code editor. and then include the “main” method in your class.
One of the useful classes that handle inputs from a user in Java is the Scanner class. The Scanner class
is located in the util (utility) package of the Java library. To use the Scanner class, we use the keyword
import to reference it in our code, see below.
import java.util.Scanner;
The above statement tells Java that you want to use the Scanner class located in the util package of the
java library. To use the class, we create new object of the class. This object work as the link between our
code and the class and so we can be able to access the functions of the class from our code.
• Notice that instead of creating an int variable or a String variable, we are creating a Scanner
variable.
• We have called our Scanner variable user_input. After an equals sign, we have the keyword new.
The keyword new is used to create new objects from a class. Here, we are creating an object
from the Scanner class. In between the brackets we are specifying that the object is for a system
input and we show this by including System.in inside the brackets.
• To get the inputs from the user, we are going to use our new object, user_input, to call one of
the many input methods available in the Scanner class. We’ll use the next method. This method
gets the next string of text that a user types on the keyboard. It is one of the many methods in
Scanner class. As you type next in the code editor you’ll see a list of other available methods.
Before we take the user name as input, we’ll add another statement to ask the user to enter the input. We
have also created a String variable called user_name to store that input.
String user_name;
user_name = user_input.next( );
Notice that we have used print instead of println like we did earlier. The difference between the two is
that println makes the cursor to move to a new line after the output, but with print the cursor stays on the
same line. Let us now add our popular method to output the user input on the output window.
12
Scanner user_input = new Scanner( System.in );
String user_name;
user_name = user_input.next( );
Section 3
JOptionPane class
• This class contains dialogs that can be used to request information from the user, display
information or give the user a choice e.g. “OK” and “Cancel”, “Yes” and “No” etc. A dialog box is
a small graphical window that displays a message to the user or requests input.
JOptionPane class
• The class JOptionPane contains input boxes and dialogs as shown below:
13
• With JOptionPane class you can create customized dialogs that suit your needs in programming.
JOptionPane provides support for layout on standard dialogs by providing icons, specifying the
dialog title and text, and you can also customize the text contained in the command button.
• following image shows some of the icons that can be used with JOptionPane class compared to
the equivalent in Windows.
• To include JOption class, the following line of code must be included in your program just after
the package name:
import javax.swing.JOptionPane;
• The above line of code lets Java know that we are going to make use of JOptionPane class in
the javax.swing library.
• For the purpose of this lesson, create a new class, call it Jpane. Once you have created the
class, add the above statement.
• Get an input from the user and store it into a variable called response which will be of string
data type. Use one of the JOptionPane class methods called showInputDialog. So, add the
following lines of code in your “main” method:
String response;
• To display the response that the user has entered, we’ll use a message box. This is yet another
method in the JOptionPane class. Add the following statement in your code.
• The keyword null that will appear inside the brackets denotes that the message box is not
associated with any other output of our program. In between the brackets after the keyword null,
14
type response. This is the name of the variable that contains the output we want to display.
Because we have created several objects in our code, once we run the program we are going to
clear them. So, add the following statement in your code.
System.exit(0);
• Dialog boxes can be formatted to have a meaningful feel and look icon as shown by the following
code:
• Other options of feel and look icons that you may try include:
• ERROR_MESSAGE
• WARNING_MESSAGE
• QUESTION_MESSAGE
• PLAIN_MESSAGE
• Input dialog boxes can also work with numbers but because they take in text only you need to
convert strings into numbers.
• To convert strings into numbers, we use the method Integer.parseInt( text to convert
). Note inside the brackets we put the string we want to convert.
15
Section 4
• IF statement executes the code only if the condition specified is met i.e. is TRUE, otherwise if the
condition is not met, i.e. it is FALSE, the code will not be executed. Later on we shall see how we
can handle this situation where the condition may be FALSE.
if(condition) {
Operators in Java
16
Exercise
• Devise a program code that accepts an integer and determine whether the integer is positive or
negative.
Solution to Exercise
• Create a string variable, call it num, to hold the input entered by the user and another, call it
num2, to store the converted int value.
Section 5
switch Statement
• is a selection statement, that means when used, it select one value among many values. switch
statement can also be used instead of IF .. ELSE statement.
• For this lesson, you will need to create yet another class, call it myswitch.
17
break;
case Testing value:
Statement to be executed;
break;
default:
Statement to output if no matching case found;
• }
Exercise
• Devise a program that accepts any of the ff. input and return corresponding day equivalent.
• include the following header statement for Java Option Panes like we did in our earlier lessons.
import javax.swing.JOptionPane;
18
Java Program using Switch statement
Section 6
• Another way of controlling the flow of our program is by forcing it to repeat execution of
statements a number of times.
• This in programming is referred to as looping. Java has several looping control structures.
• The FOR loop is one of the most common looping controls used in Java. The FOR loop has the
following structure:
}
The 3 parts:
• Initial value – This part sets at what number should the repeat process start, usually it starts at 1
but it can be any other starting number.
• Condition – Because the repeat should occur only if a certain condition hold TRUE, this part
keep on checking whether the condition hold for every loop.
• Increment/decrement – The purpose of this part is to move the counter either forward or
backward depending on what type of repeat we want to do.
19
• After the round brackets there is a pair of curly braces. The curly braces are used to hold the
code that you want to execute repeatedly.
Exercise #1
Exercise
• Devise a program to output all odd numbers between 1 and 20. Odd numbers have a remainder
greater than zero when divided by 2.
• In addition, the program should sum all the odd numbers and sum all the even numbers between
1 and 20.
20
Section 7
• The WHILE loop execute a statement or a group of statements so long as the specified condition
remains TRUE.
while( condition ) {
Section 7
• The DO…WHILE loop execute statements a number of times so long as the specified condition
remains TRUE.
do {
//Statements to execute
21
Exercise
• Write a program to output the text “This is a while loop” for ten times on the console window.
• It will be a good programming practice if we can let the user attempt several times to enter the
password. We’ll set attempts to three times after which we’ll let the user know that our program
has been locked. To do this, we’ll need a WHILE loop, an IF ..ELSE statement and the method
called equals().
Section 8
22
Array
Examples:
package ArraysPrograms;
import java.util.Scanner;
{int y=x+1;
System.out.println("Enter number"+y);
String strNum=InputNum.next();
Num[x]=Integer.parseInt(strNum);
{System.out.println("Num"+"["+x+"]"+"="+Num[x]); }
System.out.println(Num[x]);
Section 9
23
Working with STRINGS in java
Sample Program
import java.util.Scanner;
System.out.println("Enter name");
String name=str.next();
24