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

Chapter-1Notes Updated

Uploaded by

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

Chapter-1Notes Updated

Uploaded by

JB JIMENEZ
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Chapter 1

Java Fundamentals – Anatomy of a Basic Java Program

Section 1

Introduction to Java

History

• Java is an object-oriented programming language developed by James Gosling and


colleagues at Sun Microsystems in the early 1990s.

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

• Java Standard Edition (JavaSE)

– JavaSE(formerly J2SE) can be used to develop client-side standalone applications or


applets.

• Java Enterprise Edition (JavaEE)

– JavaEE (formerly J2EE) can be used to develop server-side applications such as Java
servlets and Java ServerPages.

• Java Micro Edition (JavaME).

– JavaME (formerly J2ME) can be used to develop applications for mobile devices such as
cell phones.

Getting Started with Java Programming

• A Simple Java Application

• Compiling Programs

• Executing Applications

A Simple Application

Example 1.1

//This application program prints Welcome

//to Java!

package chapter1;

public class Welcome {

public static void main(String[] args) {

System.out.println("Welcome to Java!");

Anatomy of a Java Program

• Comments

• Package

1
• Reserved words

• Modifiers

• Statements

• Blocks

• Classes

• Methods

• The main method

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

A statement represents an action or a sequence of actions. The statement


System.out.println("Welcome to Java!") in the program in Example 1.1 is a statement to display the
greeting "Welcome to Java!" Every statement in Java ends with a semicolon (;).

Blocks

A pair of braces in a program forms a block that groups components of a program.

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

public class MyFirstProgram {

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

What is System.out.println? It is a method: a collection of statements that performs a sequence of


operations to display a message on the console. It can be used even without fully understanding the
details of how it works. It is used by invoking a statement with a string argument. The string argument is
enclosed within parentheses. In this case, the argument is "Welcome to Java!" You can call the same
println method with a different argument to print a different message.

main Method

The main method provides the control of program flow. The Java interpreter executes the application by
invoking the main method.

The main method looks like this:

public static void main(String[] args) {

// Statements;

public static void main( String[ ] args ) {

• 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

Working with variables in java

• Data is an important part of programming and programs work by operating on data.

Kinds of data

 Text
 Numbers
 Pointers
 objects

or some specified memory location

• The name of the data and its value is referred to as a variable.

Types of Number data

3
 Integer
 double

Example
public static void main(String[ ] args) {

int age;

age = 20;

or

public static void main(String[ ] args) {

int age = 20;

To print the value of the variable

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.

Arithmetic Operators in Java

+ (the plus sign) for addition


- (the minus sign) for subtraction
* (the asterisk sign) for multiplication and
/ (the forward slash) for division

Working with Variables of int type

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.

Working with variables of double type

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:

– float basicSalary = 20000.78f;

– float allowances = 12000.88f;

Java order of Operators Precedence

• 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.

Working with Variables of String Type

• 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;

To assign values to the string variable

• sir_name = “Benta”;

7
• other_name = “Smith”;

Above code can also be written as:

• String sir_name = “Benta”;

• String other_name = “Smith”;

Using a variable of type char


char grade = 'B';

Remember:

A String variable has double quotes and a char variable has single quotes.

Section 2

Working with user inputs

• 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.* ;

• The first step is to create the InputStreamReader. The format is as follows:


InputStreamReader varName = new InputStreamReader(System.in) ;

• 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.

• This will be the actual code that we will use

InputStreamReader istream = new InputStreamReader(System.in) ; BufferedReader


bufRead = new BufferedReader(istream) ;

• Note the case of the characters and the semicolons.

• Next, we want to read a line in. You can do this by the following:

String firstName = bufRead.readLine();

Note the capital L.

• To read from the keyboard, you must also create a try catch block:

try {

catch (IOException err) {

• 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 {

String firstName = bufRead.readLine();

catch (IOException err) { System.out.println("Error reading line"); }

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 {

System.out.println("Please Enter In Your First Name: ");

String firstName = bufRead.readLine();

catch (IOException err) {

System.out.println("Error reading line");

9
import java.io.* ;

class Tut1 { public static void main(String args[]) {

InputStreamReader istream = new InputStreamReader(System.in) ;

BufferedReader bufRead = new BufferedReader(istream) ;


System.out.println("Welcome To My First Java Program");

try {

System.out.println("Please Enter In Your First Name: ");

String firstName = bufRead.readLine();

catch (IOException err) {

System.out.println("Error reading line");

• We also want to ask for the user’s birth year and the current year:

System.out.println("Please Enter In The Year You Were Born: "); String


bornYear = bufRead.readLine();

System.out.println("Please Enter In The Current Year: ");

String thisYear = bufRead.readLine();

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:

int bYear = Integer.parseInt(bornYear);

int tYear = Integer.parseInt(thisYear);

This code must go in a try catch block. You can then catch the conversion error:

catch(NumberFormatException err) { System.out.println("Error Converting


Number"); }

• The next step is to calculate the age of the person and output all the data:

int age = tYear – bYear ;

System.out.println(“Hello “ + firstName + ". You are " + age + " years


old");

10
THE COMPLETE CODE

import java.io.* ;

public class InputFromUser {

public static void main(String args[])

InputStreamReader istream = new InputStreamReader(System.in) ;

BufferedReader bufRead = new BufferedReader(istream) ;

System.out.println("Welcome To My First Java Program");

try {

System.out.println("Please Enter In Your First Name: ");

String firstName = bufRead.readLine();

System.out.println("Please Enter In The Year You Were Born: ");

String bornYear = bufRead.readLine();

System.out.println("Please Enter In The Current Year: ");

String thisYear = bufRead.readLine();

int bYear = Integer.parseInt(bornYear);

int tYear = Integer.parseInt(thisYear);

int age=tYear-bYear;

System.out.println("Hello " + firstName + ". You are " + age +


" years old");

catch (IOException err) {

System.out.println("Error reading line");

catch(NumberFormatException err) {

System.out.println("Error Converting Number");

Try the second example as follows

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.

• Set the class name to be UserInputs

• 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.

• We create the new object by using the following code:

Scanner user_input = new Scanner( System.in );

• 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.

Scanner user_input = new Scanner( System.in );

String user_name; user_name = user_input.next( );

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.

Scanner user_input = new Scanner( System.in );

String user_name;

System.out.print("Enter your 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;

System.out.print("Enter your name: ");

user_name = user_input.next( );

System.out.println("Your name is: " + user_name);

Section 3

Working with JAVA option panes

JOptionPane class

• JOptionPane is a class of the javax.swing library.

• 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;

response = JOptionPane.showInputDialog("What is a 'string' in


Java?") //Type as one line

• 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.

JOptionPane.showMessageDialog( null, response);

• 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:

• showMessageDialog(null, response, "Answer", JOptionPane.INFORMATION_MESSAGE);


//Type as one line.

• Other options of feel and look icons that you may try include:

Message dialogs: Feel and look icons

• 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

Control structures in java


– if statement

IF employee status = “manager” then add allowance

• 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.

• The structure of the IF Statement in Java is shown below:

if(condition) {

• create another class, call it Mycondition.

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

Control structures in java – the switch statement

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.

The structure of Switch statement in Java

• switch(Your test variable) {


case Testing value:
Statement to be executed;

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

Control structures in java – the FOR loop

• 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:

for(initial value; condition; increment/decrement)

{ // Type as one line

//Statements to be repeated if condition is TRUE

}
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

• Devise a program to count from 1 to 10 and output the values.

Exercise

• Make a for loop program to sum numbers 1 to 10.

Individual Practice 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

Control structures in java – the while loop

• The WHILE loop execute a statement or a group of statements so long as the specified condition
remains TRUE.

• The WHILE loop in Java has the following structure:

while( condition ) {

Section 7

Control structures in java – the do while loop

• The DO…WHILE loop execute statements a number of times so long as the specified condition
remains TRUE.

• The structure of the DO … WHILE loop is as follow:

do {

//Statements to execute

}while( condition to check );

21
Exercise

• Write a program to output the text “This is a while loop” for ten times on the console window.

Combining Control Structures in Java

• 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().

Java program using WHILE loop and IF..ELSE statement

Section 8

Working with arrays in java

22
Array

• is a collection of variables which are of the same type.

How to Declare an array

data_type arrayname[]=new data_type[size];

Examples:

int num[] = new int[3];

float num[]=new float[3];

double num[]=new double[3];

String name[]=new String[3];

package ArraysPrograms;

import java.util.Scanner;

public class ArrayProg1 {

public static void main(String[] args){

Scanner InputNum=new Scanner(System.in);

int Num[]=new int[3];

for(int x=0; x<=2; x++)

{int y=x+1;

System.out.println("Enter number"+y);

String strNum=InputNum.next();

Num[x]=Integer.parseInt(strNum);

for(int x=0; x<=2; x++)

{System.out.println("Num"+"["+x+"]"+"="+Num[x]); }

for(int x=0; x<=2; x++)

System.out.println(Num[x]);

Section 9

23
Working with STRINGS in java

Sample Program

import java.util.Scanner;

public class ArrayStrings {

//This program works with strings

public static void main(String[] args){

Scanner str=new Scanner(System.in);

System.out.println("Enter name");

String name=str.next();

if(name.equals("Juan")) System.out.println("Name is Juan Tamad");

24

You might also like