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

Topic 2 - Java Programming Basics (Part 1)

This document provides an overview of Java programming basics, including: - It compares structured programming vs object-oriented programming, noting that OOP focuses on data (objects) rather than processes and allows for more flexibility and reusability. - It introduces Java applications and the typical components of a Java program, such as import statements, class declarations, and the main method. - It covers Java's primitive data types (integral, floating-point, boolean) and objects, noting the differences between them. Guidelines are provided for selecting the appropriate data type. - Relational operators and precedence rules for expressions are also briefly discussed. The use of constants is explained.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Topic 2 - Java Programming Basics (Part 1)

This document provides an overview of Java programming basics, including: - It compares structured programming vs object-oriented programming, noting that OOP focuses on data (objects) rather than processes and allows for more flexibility and reusability. - It introduces Java applications and the typical components of a Java program, such as import statements, class declarations, and the main method. - It covers Java's primitive data types (integral, floating-point, boolean) and objects, noting the differences between them. Guidelines are provided for selecting the appropriate data type. - Relational operators and precedence rules for expressions are also briefly discussed. The use of constants is explained.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

TOPIC 2: JAVA PROGRAMMING BASICS (PART 1)

CSC 435 OBJECT ORIENTED PROGRAMMING

➢ Structured Language VS Object OOP Language


➢ Introduction to JAVA Application
➢ Data Types – Primitive and Objects
CHAPTER OUTLINE

 Structured language VS OOP language


 Introduction to JAVA Application
 Data Types – Primitives and Objects
 Control Structures
 Array of Primitives
 Packages
STRUCTURED LANGUAGE VS OOP LANGUAGE
Structured Programming

▪ Is a top‐down approach in programming

✓ Using function (emphasize on doing things such as withdraw, calculate, transfer )


✓ Program is divided into modules to perform a specific task
✓ Every module has its own data and function which can be called by other
module
✓ Each structure has a single entry and a single exit point.

▪ Three structures of structured programming approach:

✓ Sequence – perform an action


✓ Selection – select an action (if – true/false)
✓ Iteration – repeat an action (while/for/do‐while)
Structured Programming
Advantages of Structured Programming

▪ It is user friendly and easy to understand.

▪ It is easier to learn.

▪ They require less time to write.

▪ They are easier to maintain.


Limitations of Structured Programming

▪ Repetitive codes cause a longer program than necessary.


▪ Error control maybe harder to manage.
▪ Debugging could be difficult because the program will look and perform correctly
in one part of the program but not in another section.
▪ The structure of the program needs to be well-planned.
▪ Changing a single data will require changes at all parts of the program.
▪ Lack of reusability of code.
▪ Can support the software development projects easily up to a certain level of
complexity. Once it goes beyond limit, it becomes difficult to manage.
Object Oriented Programming

▪ Is a programming approach that focuses on using OBJECTS to design and build


applications.
▪ For example : Bank – customer, money, account
▪ 4 basic concepts:
✓ polymorphism
✓ inheritance
✓ Encapsulation
✓ Abstraction
▪ Other important concepts
✓ classes
✓ objects
✓ data abstraction
Example of Object Oriented Programming
Characteristics of Object Oriented Programming

▪ It gives importance to data (object) rather than


procedure (process)
▪ Programs are divided into objects
▪ Data is hidden
▪ Objects may communicate with each other
▪ New data and function can be easily added
▪ Employ bottom‐up approach
▪ An object is a kind of self-sufficient entity that has an internal state (the data it
contains) and that can respond to messages (calls to its methods).
✓ in OOP , you first write a base class, and constantly derive new child classes from
the existing one (like car class will probably derive from a class called vehicle)
Characteristics of Object Oriented Programming
Advantages of Object Oriented Programming

▪ Avoid redundancy in code and use existing class (reusability).

▪ Save time and high productivity

▪ Secure program codes

▪ Easy to partition the work based on objects

▪ Easy to upgrade from smaller to larger system

▪ Software complexity can be managed


DIFFERENCE BETWEEN STRUCTURED AND OOP

No STRUCTURED OBJECT ORIENTED


1 Focuses on process Focuses on data
2 Using top-down approach Using bottom up approach
3 Programs are divided into small self Programs are divided into small entities called
contained functions objects
4 Less secure as there is no way of data More secure since it has data hiding
hiding features
5 Can solve moderately complex programs Can solve any complex programs
6 Less reusability, more function More reusability, less function dependency
dependency
7 Less abstraction, less flexibility More abstraction, more flexibility.
INTRODUCTION TO JAVA APPLICATION
JAVA CLASS

 Everything in Java is a class.


 A class by default cannot be run. It’s purpose is to store attributes and
behaviors.
 To make it runnable, we will put a main function inside the class. We will call this
class as the main class or driver class.
 For a JAVA project with multiple classes, there will only be one main class which is
the execution starting point.
JAVA PROGRAMS

 Java applications – standalone programs; applications can be executed from any


computer with a Java interpreter
 Syntax of a class:

 Syntax of the main method:


TEMPLATE FOR SIMPLE JAVA PROGRAMS
JAVA PROGRAM COMPONENTS

 import statements
 Class declarations
IMPORT STATEMENTS

 Syntax:
 [<package_name>].<class_name>

 Packages
 A group of pre-defined classes.
 Can include sub-packages forming a hierarchy of packages.

 Example:
 java.util.Scanner

 By default, java.lang package is imported in every java program.


 Provide classes that are fundamental to the design of the Java language.
 java.lang.Object : Class Object is the root of the class hierarchy
ANATOMY OF JAVA PROGRAMS

 Classes
 A program is defined by using one or more classes

 Methods
 A collection of statements that perform sequence of operations to display message to the
standard output device. Example, System.out.println();

 The main method


 Every java application must have a user declared main method that defines where the program
execution begins. JVM executes the application by invoking the main method.
ANATOMY OF JAVA PROGRAMS

 Modifiers
 Specify the properties of the data, methods and classes and how they can be used.
Examples are public, private and static.

 Statement
 Represent an action or a sequence of actions
 Every statement ends with a semicolon (;)

 Blocks
 The braces in the program form a block that groups the component of the program. Every
class begin with opening braces ({)and ends with closing braces (})
EXAMPLE

/* Program name: FirstProgram.java


Purpose: This application programs prints Welcome to Java Class Name
Programming
Main method
*/ signature
public class FirstProgram
{
public static void main(String args[ ])
{
System.out.println(“Hello World”);
} //end of method main

} //end of class
WHY USE STANDARD CLASSES

 Don’t reinvent the wheel. When there are existing libraries that satisfy our needs, just
use them.
 Learning how to use standard Java classes is the first step toward mastering OOP.
Before we can learn how to define our own classes, we need to learn how to use
existing classes.
 Example of standard classes:
 JOptionPane
 String
 Date
JOPTIONPANE

 Using showMessageDialog of the JOptionPane class is a simple way to display a result of a


computation to the user.
JOptionPane.showMessageDialog(null, “I Love Java”);
DATA TYPES – PRIMITIVES AND OBJECTS
DATA TYPES

 The objective of a Java program is to manipulate data.


 Different programs manipulate different data .
 Data type: A set of values together with a set of operations.
 Data type can be divided into Primitive data type and Object data type.
PRIMITIVE DATA TYPES

Integers Decimal Numbers Logical Values


Ex: 1,5,10,-3 Ex: 1.5, -3.0, +6.1 Ex: True or False
INTEGRAL DATA TYPES

 Deals with integers, or numbers without a decimal part


FLOATING-POINT DATA TYPES

 Represent real numbers in scientific notation.


 Ex: 75.924➔ 7.5924 * 101 ➔7.592400E1 in Java
 Has two types :
 float:
 Values: -3.4E+38 → 3.4E+38
 Precision: 6 or 7 (4bytes)
 double:
 Values: -1.7E+308 → 1.7E+308
 Precision: 15 (8 bytes )
 The default type of floating-point numbers is double.
INT OR DOUBLE?

 When do we know to use int and when do we use double?


 If the data value you are going to use might be fractional then choose ➔ double
 If it will always going to be a whole number choose ➔ int

 Consider the following cases. What would you choose?


❑ Counting how many people have used a computer during a day.
❑ The area of the lecture room in meters.
❑ Average age of the students in CS230 .
BOOLEAN DATA TYPES

Has Two values:


❖ true
❖ false
 These are called the logical (Boolean) values.
 The central purpose of this data type is to manipulate logical (Boolean) expressions.
 Ex: ‘a’ != ‘A’ ➔ true
GUIDELINES FOR SELECTING DATA TYPES

 To represent integral values use type int. If a larger range of values is needed, use type
long.
 On some computers, long will take longer to execute, so care may be needed if a lot of
arithmetic is being performed.
 To represent non-integral values, use type double. Type float has similar properties
but less precision and a smaller range.
 If speed of execution is very important, the float type may offer advantages on some
computers.
 These are all what we call primitive types in Java. There are other types available.
RELATIONAL OPERATOR

 Allows you to make comparisons in a program


PRECEDENCE RULES
CONSTANTS

 We can change the value of a variable. If we want the value to remain the same, we use a
constant.

final double PI = 3.14159;


final int MONTH_IN_YEAR = 12;
final short FARADAY_CONSTANT = 23060;

The reserved word These are constants,


These are called
final is used to also called named
literal constant.
declare constants. constant.
PRIMITIVE VS REFERENCE/OBJECT DATA TYPES

 Numerical data are called primitive data types while Objects are called
reference data types
 Primitive type variables directly store data into their memory space.
 Reference variables store the address of the object containing the data.
✓ Object variables are used to access an object.
✓ Contains a pointer to a desired object.
PRIMITIVE DATA DECLARATION AND ASSIGNMENTS
It shows how two memory locations (variables) with name firstNunmer and
secondNumber are declared and values are assigned to them
ASSIGNING NUMERICAL DATA
ASSIGNING OBJECTS
WRAPPER CLASS

• Java provides routine for converting String to a primitive data types or vice versa

• It is called wrapper classes because the classes constructed by wrapping a class structure
around the primitive data types

int age;
String inputStr;

inputStr = “256”

age = Integer.parseInt(inputStr);
WRAPPER CLASSES
OBJECT DATA TYPE – CLASS STRING

▪ A sequence of characters separated by double quotes is a String constant.


▪ In JAVA, String is not a primitive data type like int and double. Instead, it is
an object of a class from package java.lang.
▪ There a close to 50 methods defined in the String class. We will introduce
three of them here:
• substring(), length() and indexOf()
 We will also introduce a string operation called concatenation [ + ].
OBJECT DATA TYPE – SUBSTRING

 Assume str is a String object and properly initialized to a String.


 str.substring(i,j) will return a new string by extracting characters of str
from position i to j-1where 0<= i <= length of str, 0 < j < length of str, and i<= j.
 If str is “programming”, then str.substring(3,7) will create a new string
whose value is “gram” because g is at position 3 and m is at position 6.
 The original string str remains unchanged.
OBJECT DATA TYPE – SUBSTRING

 String text = “Expresso”;


 text.substring(6,8) -> “so”
 text.substring(0,7) -> “Espress”
 text.substring(1,5) -> “xpre”
 text.substring(3,3) -> “”
 text.substring(4,2) -> error
OBJECT DATA TYPE – LENGTH

 Length of the string is the number of characters in it .


 Numeric strings consist of integers or decimal numbers.
 When determining the length of a string , blanks count .
 Example :
❖ ““ ➔ Empty String has length = 0
❖ “abc” ➔ has length = 3 , position of a = 0 ,b= 1 , c= 2
❖ “a boy” ➔ has length = 5
OBJECT DATA TYPE – LENGTH

 String str1, str2, str3, str4;


 str1 = “Hello”;
 str2 = “Java”;
 str3 = “”; //empty string
 str4 = “’ ”; //one space

str1.length() -> 5
str2.length() -> 4
str3.length() -> 0
str4.length() -> 1
OBJECT DATA TYPE – INDEXOF

 Assume str and substr are String objects and properly initialized.
 str.indexOf(substr) will return the first position substr occurs in str
 If str is “programming” and substr is “gram”, then str.indexOf(substr)
will return 3 because the position of the first character of substr in str is 3.
 If substr does not occur in str, then -1 is returned.
 The search is case-sensitive.
OBJECT DATA TYPE – INDEXOF

 String str;
 str = “I Love Java and Java loves me.”;

3 7 21

str.indexOf( “J” ) -> 7


str2.indexOf( “love” ) -> 21
str3.indexOf( “ove” ) -> 3
Str4.indexOf( “ME” ) -> -1

If there is more than one occurrence of the same substring, the index
position of the first character of the first matching substring is
returned.
OBJECT DATA TYPE – CONCATENATION

• Assume str1 and str2 are String objects and properly initialized.
• str1 + str2 will return a new string that is a concatenation of the
two strings.
• If str1 is “pro” and str2 is “gram”, then str1 + str2 will return
“program”.
• Notice that this is an operator and not a method of the String
class.
• The strings str1 and str2 remains the same.
OBJECT DATA TYPE – CONCATENATION

String str1, str2;


str1 = “Jon”;
str2 = “Java”;

str1 + str2 -> “JonJava”


str1 + “ “ + str2 -> “Jon Java”
str2 + “, “ + str1 -> “Java, Jon”
“Are you “ + str1 + “?” -> “Are you Jon?”

You might also like