CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
CHAPTER 2: JAVA PROGRAMMING BASICS
1.0 HISTORY OF JAVA
• Java was developed by a team led by James Gosling at Sun Microsystems, a company best
known for its Sun workstations.
• 1991 – designed by Sun Microsystems as an internal corporate research project originally
called Green then Oak. It was designed for use in embedded consumer electronic applications.
• Mid 1990’s - Java was used to write applets.
• 1993 - World Wide Web exploded in popularity – Sun saw the potential of using Java to
create Web pages – with interactive and dynamic content.
• 1998 - Java 2 was released and become popular for writing application program.
• The power of Java is not limited to Web applications, for it is a general-purpose programming
language.
• It has full programming features and can be used to develop standalone applications.
1.1 CHARACTERISTICS OF JAVA
1.1.1 Java Is Simple
• No language is simple, but Java is a bit easier that the popular object-oriented
programming language C++, which was the dominant software-development
language before Java.
• Java is partially modeled on C++, but greatly simplified and improved.
• For instance, Java uses automatic memory allocation and garbage collection, whereas
C++ requires the programmer to allocate memory and collect garbage.
1.1.2 Java Is Object-Oriented
• Computers do not understand human languages, so you need to use computer
languages to communicate with them.
• There are more than 100 programming languages. Some of the most popular
language are:
COBOL (COmmon Business Oriented Language)
FORTRAN (FORmula TRANslation)
BASIC(Beginner All-purpose Symbolic Instructional Code)
C(So named because its developer designed B first)
C++ (an object-oriented language, based on C)
• All of these languages except C++ are procedural programming languages – based on
paradigm of procedures.
• Object-oriented programming models the real world in terms of objects.
• Everything in the world can be modeled as object – student, car, book, account, apple,
etc.
• A Java program is object-oriented because programming in Java is centered on
creating objects, manipulating objects, and making objects work together.
1.1.3 Java Is Distributed
• Distributed computing involves several computers working together on a network.
• Java is designed to make distributed computing easy.
• As an example, Figure 1.1 shows three programs running on three different system;
the three programs communicate with one another to perform a joint task.
Computer 1 Computer 2
Java Program 1 Java Program 2
Computer 3
Java Program 3
Figure 1.1 Java programs can run on different systems that work together.
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 1
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
1.1.4 Java Is Interpreted
• Java programs are compiled into the Java Virtual Machine code called bytecode.
• The bytecode is machine-independent and can run on any machine that has a Java
interpreter.
1.1.5 Java Is Robust
• Robust means reliable.
• No programming language can ensure complete reliability.
• Java puts a lot of emphasis on early checking for possible errors, because Java
compilers can detect many problems that would first show up at execution time in
other languages.
• Java has a runtime exception-handling feature to provide programming support for
robustness.
1.1.6 Java Is Secure
• As an Internet programming language, Java is used in a networked and distributed
environment.
• If you download a Java applet and run it on your computer, it will not damage your
system because Java implements several security mechanisms to protect your system
against harm caused by stray program.
• The security is based on the premise that nothing should be trusted.
1.1.7 Java Is Architecture-Neutral
• Java is interpreted. This feature enables Java to be architecture-neutral/platform-
independent.
• With a Java Virtual Machine (JVM), you can write one program that will run on any
platform.
1.1.8 Java Is Portable
• Java is architecture neutral.
• This feature enables Java programs to be portable because they can be run on any
platform without being recompiled.
• Moreover, there are no platform-specific features in the Java language.
• The Java environment is portable to new hardware and operating systems. In fact, the
Java compiler itself is written in Java.
1.1.9 Java’s Performance
• Java’s performance is sometimes criticized.
• The execution of the bytecode is never as fast as it would be with a compiled
language, such as C++.
• Because Java is interpreted, the bytecode is not directly executed by the system, but
is run through the interpreter.
• However the speed is more than adequate for most interactive applications, where the
CPU is often idle, waiting for input or for data from other sources.
• Sun recently developed the Java HotSpot Performance Engine, which includes a
compiler for optimizing the frequently used code. It can be plugged into a JVM to
dramatically boost its performance.
1.1.10 Java Is Multithreaded
• Multithreading is a program’s capability to perform several tasks simultaneously.
• For example, downloading a video file while playing the video would be considered
multithreading.
• Multithread programming is smoothly integrated in Java, whereas in other languages
you have to call procedures specific to the operating system to enable multithreading.
1.1.11 Java is Dynamic
• Java was designed to adapt to an evolving environment.
• New code can be loaded on the fly without recompilation.
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 2
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
• There is no need for developers to create, and for users to install, major new software
versions.
• New features can be incorporated transparently as needed.
1.2 C++ vs. JAVA
• The following table shows the differences between C++ and Java:
Feature compared C++ Java
1. Design goals To design a distributed OS For programming consumer
device
2. Designer Bjarne Stroustrup. James Gosling [Link].
AT&T Bell Labs in 1979 Sun Microsystems in 1990
3. Language paradigm Hybrid OO = structured + OO OO paradigm only
4. Prior language influence Syntax based on C. Efficient styles Syntax based on C++,
based on Simula67 approach based on Smalltalk
5. Strengths A high performance and powerful Cross-platform
language compatibility
6. Compilation Compilation-based – like most Compiled + Interpreted
language based
C++ source file -> binary file (*.exe) Java source file -> Java
bytecode -> JVM to execute
7. Architecture-neutral and Platform-dependent binary code Platform-independent
portability cannot be executed on a difference bytecode can run on any
machine machine supporting JVM
8. Simplicity More complex – pointer, operator Simpler – no pointer, no
overloading and etc. overloading and etc.
9. Performance About 1~20 times faster than Much slower than C++, but
equivalent JAVA code good enough to run
interactively for most
application.
10. Robustness Was not designed for robustness Originally designed for
writing highly reliable or
robust software.
11. Security Memory is handled at compile-time Byte-code is verified at run-
by compiler time to ensure security
restrictions are not violated.
Memory layout is handled at
run-time by JVM.
12. Networking Not a network-capable language. A network-capable
Network programming : harder language.
Network programming:
easier.
13. Multi-threaded Single-threaded – rely on external Multi-treaded language –
(concurrent libraries for multithreading provides native
programming) multithreading support.
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 3
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
1.3 INTRODUCTION TO JAVA APPLICATION
• Java programs:
o Java applications – standalone programs; applications can be executed from any
computer with a Java interpreter.
o Applets – special kinds of Java programs that can run directly from a Java-compatible
Web browser; suitable for Web projects.
• Writing simple Java application:
/* Program name: [Link]
Purpose: This application programs prints
Welcome to Java Programming
*/
public class FirstProgram
{
public static void main(String args[])
{
[Link](“Welcome to Java Programming”);
}//end of method main
}//end of class
1.4 IDENTIFIERS
• Identifier is a name given to a variable, class or method.
• Identifiers start with a letter, underscore ( _ ), or dollar sign ($).
• Subsequent characters can be digits.
• Identifiers are case-sensitive and have no maximum length.
• Examples:
student
mySchool
student_name
subject1
$money
_a
• An identifier cannot be a keyword, but it can contain a keyword as part of its name. For
example, thisOne is a valid identifier, but this is not because this is a Java technology
keyword.
1.5 JAVA KEYWORDS
• Keywords have special meaning to the Java technology compiler.
• They identify a data type name or program construct name.
• The following table list the keywords that are used in the Java programming language:
abstract continue goto package synchronized
assert default if private this
Boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
1.6 DATA TYPES
• There are two categories of data types – class/object types and primitive types.
• Primitive types are simple values, are not objects.
• Class types are used for more complex types, including all the types you declare yourself.
• Class types are used to create objects.
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 4
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
• The Java programming language defines eight primitive data types, which can be considered
in four categories:
o Logical – boolean
o Textual – char and String
o Integral – byte, short, int, and long
o Floating point – double and float
1.7 Logical – Boolean
• The boolean data type has two literals, true and false.
• For example, the statement:
boolean result = true;
declares the variable result as boolean type and assigns it a value of true.
1.8 Textual – char & String
• char – represents a 16-bit Unicode character
• Must have its literal enclosed in single quotes (‘ ’)
• For example:
char letter = ‘a’;
• String – is not a primitive data type; it is a class
• Has its literal enclosed in double quotes (“ ”)
• Can be used as follows:
String greeting = “Assalamualaikum”;
String errorMessage = “Record not found!!”;
1.9 Integral – byte, short, int, and long
• An integer literal can be assigned to an integer variable as along as it can fit into the
variable.
• Integral data types have the following ranges:
Integer Length Name or Type Range
8 bits byte -27 to 27-1
16 bits short -215 to 215-1
32 bits int -231 to 231-1
64 bits long -263 to 263-1
• For example:
int number = 12345;
1.10 Floating point – double and float
• Floating point literals are written with a decimal point.
• By default, a floating point literal is treated as a double type value.
• For example:
double price = 27.70;
double mark = 85.5;
1.11 Constants
• The value of a variable may change during the execution of the program, but a
constant represents permanent data that never change.
• The word final is a Java keyword which means that the constant cannot be
changed.
• For example:
final double PI = 3.14159;
1.12 Type Casting
• Casting means assigning a value of one type to a variable of another type.
• If the two types are compatible, the Java software performs the conversion
automatically.
• For example, an int value can always be assigned to a long variable.
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 5
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
• The desired target type is placed in parenthesis and used as a prefix to the expression
that must be notified.
• For example:
double number1 = 2.7, number2 = 7.5;
int result1 = (int)(number1 + number2); // = ?
int result2 = (int)number1 + (int)number2; // = ?
1.13 ARRAY OF PRIMITIVES
• An array is a collection of data values.
• If your program needs to deal with 100 integers, 500 Account objects, 365 real numbers, etc.,
you will use an array.
• In Java, an array is an indexed collection of data values of the same type.
• Array declaration:
<data type> [ ] <array_name> //variation 1
<data type> <array_name>[ ] //variation 2
• Array creation:
<array_name> = new <data type> [ <size> ]
• Example:
double[ ] rainfall; //variation 1
rainfall = new double[12];
double rainfall[ ]; //variation 2
rainfall = new double[12];
• The index of the first position in an array is 0.
• Sample array processing:
double[] rainfall = new double[12];
double annualAverage,sum = 0.0;
for (int i = 0; i < [Link]; i++) {
rainfall[i] = [Link](
[Link]("Rainfall for month " +
(i+1) ) );
sum += rainfall[i];
}
annualAverage = sum / [Link];
• Array Initialization
o Like other data types, it is possible to declare and initialize an array at the same time.
o Example:
int[] number = { 2, 4, 6, 8 };
double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,
9.00, 3.123, 22.084, 18.08 };
String[] monthName = { "January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 6
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
[Link] 4
[Link] 9
[Link] 12
• Variable-size Declaration
o In Java, we are not limited to fixed-size array declaration.
o The following code prompts the user for the size of an array and declares an array of
designated size:
o Example:
int size;
int[] number;
size= [Link]([Link](null,
"Size of an array:"));
number = new int[size];
1.14 CONTROL STRUCTURE
1.14.1 Branching Statements
• The Java programming language supports the if and switch statements for two-
way and multiple-way branching, respectively.
• The if, else statement:
if (boolean expression){
statement or block;
}
if (boolean expression){
statement or block;
}
else{
statement or block;
}
• The switch statement:
switch (expr1){
case constant2: statements;
break;
case constant3: statements;
break;
default: statements;
break;
}
1.14.2 Looping Statements
• Looping statements allow you to execute blocks of statements repeatedly.
• The Java programming language supports three types of loop constructs: for,
while and do loops.
• The for loops:
for(init_expr; boolean testexpr; alter_expr){
statements or block;
}
• The while loops:
while (boolean){
statements or block;
}
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 7
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
• The do/while loops:
do{
statements or block;
} while(boolean test);
1.15 PACKAGES
• A Java package is a group of related classes and interfaces.
• It facilitates software reuse by allowing programs to import classes from other packages
libraries to be shared by many users.
• For example: to use the JOptionPane class in the [Link] package, include the
import statement before class declaration:
import [Link];
1.16 INPUT & OUTPUT STATEMENT
1.16.1 Using Dialog Box
• Input – the showInputDialog method in [Link]
package is use.
• Has one String parameter which is the message to be displayed to the user.
• Returns the String keyed in by the user and returns the null String if user cancels.
Example:
String input;
input = [Link](“Enter a
number”);
• To do mathematical operations on the given data, the String returned by
showInputDialog must be converted to the required numerical data type.
• The parse functions in various wrapper classes are used:
int num = [Link](input);
float nom = [Link](input);
double x = [Link](input);
• Output – the showMessageDialog method is used.
• Has one String parameter which is the message to be displayed to the user.
String output;
output = “The answer is “ + num;
[Link](null, output);
1.16.2 Using Console I/O
• Input using the Scanner class (available in Java 5).
• Create a Scanner object by passing an input stream to the constructor
Scanner scanner = new Scanner([Link]);
• Use the nextInt(), nextDouble(), nextLine(), next() methods to
read data typed on the keyboard.
[Link](“Enter a number: “);
int num = [Link]();
• Output is done through the [Link] or [Link]
methods:
[Link](“The result is ”+ total);
[Link](“x = ”+ x + “y = ” + y);
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 8
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
2.0 USER-DEFINED METHOD (REVISION)
EXAMPLE:
Problem: Write a Java program that will calculate five test marks and find the average mark.
Display the total mark and the average mark accordingly.
Example solving the problem without using method:
import [Link].*;
public class TestMark
{
public static void main(String args[])
{
String input;
double mark, total, average;
total = 0;
for(int counter = 0; counter < 5; counter++){
input = [Link]("Enter test mark");
mark = [Link](input);
total = total + mark;
}
average = total/5;
[Link](null, "Total mark: " + total +
"\nAverage mark: " + average);
} // end of main method
} // end of class
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 9
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
2.0.1 Accept No Parameter & Return No Value
Example solving the problem using method:
import [Link].*;
public class TestMark
{
public static void main(String args[])
{
[Link](null, "In main method before
method call");
calculateMark(); //method call
[Link](null, "In main method after
method call");
} // end of main method
public static void calculateMark() // method heading
{
String input;
double mark, total, average;
total = 0;
for(int counter = 0; counter < 5; counter++){
input = [Link]("Enter test mark");
mark = [Link](input);
total = total + mark;
}
average = total/5;
[Link](null, "Total mark: " + total +
"\nAverage mark: " + average);
} // end of method calculateMark
} // end of class
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 10
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
2.0.2 Accept Parameter & Return No Value
import [Link].*;
public class TestMark
{
public static void main(String args[])
{
String input;
double mark, total;
total = 0;
for(int counter = 0; counter < 5; counter++)
{
input = [Link]("Enter test mark");
mark = [Link](input);
total = total + mark;
}
calculateMark(total); //method call
[Link](null, "In main method after
method call");
} // end of main method
public static void calculateMark(double total) // method heading
{
double average;
average = total/5;
[Link](null, "Total mark: " + total +
"\nAverage mark: " + average);
} // end of method calculateMark
} // end of class
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 11
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
2.0.3 Accept No Parameter & Return Value
import [Link].*;
public class TestMark
{
public static void main(String args[])
{
double sum, average;
sum = calculateMark(); //method call
average = sum / 5;
[Link](null, "Total mark: "+ sum +
"\nAverage mark: " + average);
} // end of main method
public static double calculateMark() // method heading
{
String input;
double mark, total;
total = 0;
for(int counter = 0; counter < 5; counter++)
{
input = [Link]("Enter test mark");
mark = [Link](input);
total = total + mark;
}
return total; // return value
} // end of method calculateMark
} // end of class
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 12
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
2.0.4 Accept Parameter & Return Value
import [Link].*;
public class TestMark
{
public static void main(String args[])
{
String input;
double mark, total, average;
total = 0;
for(int counter = 0; counter < 5; counter++)
{
input = [Link]("Enter test mark");
mark = [Link](input);
total = total + mark;
}
average = calculateMark(total); //method call
[Link](null, "Total mark: "+ total +
"\nAverage mark: " + average);
} // end of main method
public static double calculateMark(double total) // method
heading
{
double avg;
avg = total / 5;
return avg; // return value
} // end of method calculateMark
} // end of class
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 13
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
2.0.5 Accept Array Parameter
import [Link];
public class Salary
{
public static void main(String [] args)
{
double [] salary = {1500.00, 2500.75, 3150.50};
increaseSalary(salary);
displaySalary(salary);
}
public static void increaseSalary(double salary[])
{
for (int i=0; i<3; i++)
salary[i] = salary[i] * 1.1; /**10% increment*/
}
public static void displaySalary(double salary[])
{
DecimalFormat df = new DecimalFormat("0.00");
for (int i=0; i<3; i++)
[Link]("Salary" + (i + 1) + " : " +
[Link](salary[i]));
}
}
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 14
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
TUTORIAL
1. Write a program that allows the user to enter a value that represents the radius of a circle. The
program calculates the diameter and then calculates the circumference. The program prints both the
diameter and the circumference.
2. Given the interpretation of BMI for people 16 year or older is as follows:
BMI Interpretation
below 16 seriously underweight
16 – 18 underweight
19 – 24 normal weight
25 – 29 overweight
30 – 35 seriously overweight
above 35 gravely overweight
Write a program that prompts the user to enter a weight in pounds and height in inches and display
the BMI. Note that one pound is 0.4536 kilograms and one inch is 0.0254 meters.
3. Write a program by using multiple if statement. The requirements are as below:
a) Your program should be able to read the item code from the keyboard.
b) The item code determines the price for each item in the shop. The following table shows the
prices and tax charges for 7 items in the shop.
Item Code Price (RM) Charge Rate (%)
A 54.00 5
B 65.00 5
C 82.00 5
D 103.00 7
E 150.00 7
F 245.00 10
G 250.00 10
c) If the item code is not matched, an error message is displayed as follows:
Sorry, the item code is not found.
d) For each selected item, the charge is calculated by multiplying the item price with the charge
rate.
e) Then the payment is a summation of item price and charge. Your program is to display this
payment.
4. Write a program to display and find the sum of ALL numbers between 15 and 27 (inclusive) that
are divisible by three. Then, it displays the numbers and the sum of these numbers as output.
5. Convert your program in Question 3 using switch structure.
6. Write a program that allows the user to enter a value that represents the radius of a circle. The
program calculates the diameter and then calculates the circumference. The program prints both the
diameter and the circumference. Your program must contain at least the following methods:
a. A method that calculates the diameter and return the value.
b. A method that calculates the circumference and display the value.
7. Write a program for an insurance company’s premium-determining program. The program calls a
method that prompts the user for the type of policy needed – health or auto. Pass the user’s response
to a second method, where the premium is set – RM250 for a health policy or RM175 for an auto
policy. Pass the premium amount to the third method for printing.
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 15
CSC186-OBJECT ORIENTED PROGRAMMING (OOP) JAVA Programming Basics
8. Write a program to calculate class average test score. You may assume the following input data:
Name Score
Azrina Suhaimi 85
Liew Chee Ho 88
Rohana Abu 79
Vijayanand 56
Lua Siew Wee 85
Siti Nur Haliza 44
Store the test scores in an array of size SIX. Calculate the average of the students’ test scores and
output the results.
9. Modify the program in Question 8 so that the size of the array is based on user input. Create TWO
arrays to store the students’ name and the test scores. Display the all the input and the student’s
name with the highest score.
”Tatkala aku lesu pada pekerjaan, lalu aku memandang kepada temanku. Dari ketekunannya
berbuat taat, maka kembali kerajinanku kepada ibadah dan berpisah kemalasan. Teruslah aku bekerja
sampai seminggu lamanya”
Ja’far bin Sulaiman
Mazlyda Abd Rahman, 2021 | Edited by : Azrina Suhaimi 16