0% found this document useful (0 votes)
9 views11 pages

Java Programming Basics Overview

This document provides an introduction to object-oriented programming (OOP) and Java programming basics. It covers key concepts such as structured programming limitations, OOP advantages, Java characteristics, and fundamental programming components like data types, control structures, and string operations. Additionally, it includes examples of Java syntax and programming practices.

Uploaded by

Roha Astro
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views11 pages

Java Programming Basics Overview

This document provides an introduction to object-oriented programming (OOP) and Java programming basics. It covers key concepts such as structured programming limitations, OOP advantages, Java characteristics, and fundamental programming components like data types, control structures, and string operations. Additionally, it includes examples of Java syntax and programming practices.

Uploaded by

Roha Astro
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

9/14/2014

Revision
 Introduction to object
 Elements of an object: attribute, behavior, state
 Characteristics of OOP: abstraction, encapsulation,
inheritance, polymorphism

Chapter 2: JAVA Programming


Basics
Mohammad Bakri Che Haron
Amended from slides by: Zulailie Mabni

1 Bakri 2 Bakri

Chapter Outline
 Structured language vs OOP language
 Introduction to Java Application
 Data types – primitives and objects
 Control Structures
 Array of primitives Structured vs OOP Language
 Packages

3 Bakri 4 Bakri

Structured programming Limitations of structured language


 During the 1970s and into the 80s, the primary software  There are some limitations of structured programming:
engineering methodology was structured programming.  It focuses almost entirely on producing the instructions
The structured programming approach to program was necessary to solve a problem.
based on the following method:  It is difficult to reuse work done for other projects.
 To solve a large problem, break the problem into several pieces  Some problems by their very nature do not fit the model that
and work on each piece separately. top-down design is based upon.
 To solve each piece, treat it as a new problem that can itself be
broken down into smaller problems;
 Repeat the process with each new piece until each can be
solved directly, without further decomposition.
 This approach also called top-down program design.

5 Bakri 6 Bakri

1
9/14/2014

Object-oriented programming (OOP) Advantages of OOP


 The central concept of object-oriented programming is  The advantages of this approach are as follow:
the object, which is a kind of module containing data and  The data is protected, since it can be manipulated only in
methods. An object is a kind of self-sufficient entity that known, well-defined ways;
has an internal state (the data it contains) and that can  It is easier to write programs to use a module because the
respond to messages (calls to its methods). details of how the data is represented and stored need not be
known;
 The storage structure of the data and the code for the
methods in a module may be altered without affecting
programs that make use of the module as long as the published
interfaces and the module’s functionality remain the same.

7 Bakri 8 Bakri

Intro to JAVA programming language


 A high-level object-oriented language.
 Developed by James Gosling and his team in 1991 at Sun Microsystems in
California.
 Originally called Green then Oak, finally renamed as Java.
 Based on C and C++, originally intended for writing programs that control
consumer appliances such as toasters, microwave, oven, etc. Later, modified
to focus on the WWW.
 Java’s clean design and wide availability make it an ideal language for Introduction to Java Application
teaching the fundamentals of computer programming.
 Characteristics:
 Simpler
 Safe – implements several security features
 Portable – platform independent (“write once, run anywhere”)
 Robust – reliable
 Multi-threaded – perform several tasks simultaneously
 Rich library – packages
 Designed for the Internet

9 Bakri 10 Bakri

Template for Simple JAVA Programs Java Program Components


 import statements
Import statements  Class declarations

public class { Class name

public static void main(String args[]) {

Method body

}
}

11 Bakri 12 Bakri

2
9/14/2014

Import Statements Java Programs


 Syntax:  Every program consists of one or more classes.
 [<package_name>].<class_name>  Every source file can contain at most one public class
 Packages (main class).
 A group of pre-defined classes.
 Every java program must have a main method (inside the
 Can include sub-packages forming a hierarchy of packages.
main class).
 Example:
 [Link]  The name of the public class must match the name of the
file containing the class.
 By default, [Link] package is imported in every java
program.
 Provide classes that are fundamental to the design of the Java
language.
 [Link] : Class Object is the root of the class hierarchy.

13 Bakri 14 Bakri

Why Use Standard Classes JOptionPane


 Don’t reinvent the wheel. When there are existing  Using showMessageDialog of the JOptionPane class is a
libraries that satisfy our needs, just use them. simple way to display a result of a computation to the
 Learning how to use standard Java classes is the first step user.
toward mastering OOP. Before we can learn how to
define our own classes, we need to learn how to use [Link](null, “I Love Java”);
existing classes.
 Example of standard classes:
 JOptionPane
 String
 Date

15 Bakri 16 Bakri

String String is an Object


 A sequence of characters separated by double quotes is a 1 String name;
2 name = new String(“Jon Java”);
String constant.
 There a close to 50 methods defined in the String class. 1. The identifier name is 2. A String object is
We will introduce three of them here: declared and space is created and the identifier
allocated in memory name is set to refer to it.
 substring, length and indexOf
name name
 We will also introduce a string operation called
1 1
concatenation.
: String

Jon Java

17 Bakri 18 Bakri

3
9/14/2014

Definition: Substring Examples: Substring


 Assume str is a String object and properly initialized to  String text = “Expresso”;
a String.  [Link](6,8) -> “so”
 [Link](i,j) will return a new string by  [Link](0,8) -> “Espresso”
extracting characters of str from position i to j-1where  [Link](1,5) -> “spre”
0<= i <= length of str, 0 < j < length of str, and i<= j.  [Link](3,3) -> “”
 If str is “programming”, then [Link](3,7)  [Link](4,2) -> error
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.

19 Bakri 20 Bakri

Definition: Length Examples: Length


 Assume str is a String object and properly initialized to a String str1, str2, str3, str4;
string. str1 = “Hello”;
str2 = “Java”;
 [Link]() will return the number of characters in str. str3 = “”; //empty string
str4 = “’ ”; //one space
 If str is “programming”, then [Link]() will return 11
because there are 11 characters in it.
 The original string str remains unchanged. [Link]() -> 5
[Link]() -> 4
[Link]() -> 0
[Link]() -> 1

21 Bakri 22 Bakri

Definition: IndexOf Examples: IndexOf


 Assume str and substr are String objects and properly String str;
initialized. str = “I love Java and Java loves me.”;
 [Link](substr) will return the first position substr
3 7 21
occurs in str.
 If str is “programming” and substr is “gram”, then
[Link](substr) will return 3 because the position of
[Link]( “J” ) -> 7
the first character of substr in str is 3. [Link]( “love” ) -> 21
[Link]( “ove” ) -> 3
 If substr does not occur in str, then -1 is returned. [Link]( “Me” ) -> -1
 The search is case-sensitive.

23 Bakri 24 Bakri

4
9/14/2014

Definition: Concatenation Examples: Concatenation


 Assume str1 and str2 are String objects and properly
String str1, str2;
initialized.
str1 = “Jon”;
 str1 + str2 will return a new string that is a str2 = “Java”;
concatenation of the two strings.
 If str1 is “pro” and str2 is “gram”, then str1 + str2 will str1 + str2 -> “JonJava”
return “program”. str1 + “ “ + str2 -> “Jon Java”
str2 + “, “ + str1 -> “Java, Jon”
 Notice that this is an operator and not a method of the “Are you “ + str1 + “?” -> “Are you Jon?”
String class.
 The strings str1 and str2 remains the same.

25 Bakri 26 Bakri

Numerical Data Types


 There are six numerical data types: byte, short, int, long,
float and double.
 At the time a variable is declared, it also can be initialized.
 The six data types differ in the precision of values they
Data types – primitives and can store in memory.
objects

27 Bakri 28 Bakri

Arithmetic Operators Precedence Rules


 The following table summarizes the arithmetic operators
available in Java.

29 Bakri 30 Bakri

5
9/14/2014

Constants Primitive vs Reference


 We can change the value of a variable. If we want the  Numerical data are called primitive data types.
value to remain the same, we use a constant.  Objects are called reference data types, because the
contents are addresses that refer to memory locations
final double PI = 3.14159; where the objects are actually stored.
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.

31 Bakri 32 Bakri

Primitive Data Declaration and Assignments Assigning Numerical Data

A. Variables are number 35


237
allocated in memory.

A
firstNumber 234
int firstNumber, secondNumber; A. The variable
firstNumber = 234; is allocated in
B int number; A memory.
secondNumber = 87; secondNumber 87
number = 237; B B. The value 237
number = 35; is assigned to
C
number.
B. Values are assigned
to variables. C. The value 35
overwrites the
previous value 237.

Code State of Memory Code State of Memory

33 Bakri 34 Bakri

Assigning Objects Having Two References to a Single Object


customer
clemens

twain
Customer Customer
A A Customer

B A. The variable is B A. Variables are


Customer customer; Customer clemens, twain,
allocated in memory. allocated in memory.
customer = new Customer( ); clemens = new Customer( );
B. The reference to the B. The reference to the
customer = new Customer( ); new object is assigned twain = clemens; new object is assigned
to customer. to clemens.

C C. The reference to C C. The reference in


another object overwrites clemens is assigned to
the reference in customer. customer.

Code State of Memory Code State of Memory

35 Bakri 36 Bakri

6
9/14/2014

Type Conversion Other Conversion Methods


 Wrapper classes are used to perform necessary type
conversions, such as converting a String to a numerical
value.

int age;
String inputStr;

inputStr = “256”

age = [Link](inputStr);

37 Bakri 38 Bakri

Selection Statements
if ( <boolean expression> )
<then block>
else
<else block>
Boolean Expression
Control Structures
if ( testScore < 70 )

Then Block [Link]("You did not pass");


Controlling flow of program
else
[Link]("You did pass " );
Else Block

39 Bakri 40 Bakri

Control Flow Relational Operators


< //less than
<= //less than or equal to
false true
testScore < == //equal to
70 ? != //not equal to
> //greater than
>= //greater than or equal to

[Link]("You [Link]("You
did pass"); did not pass");

testScore < 80
testScore * 2 >= 350
30 < w / (h * h)
x + y != 2 * (a + b)
2 * [Link] * radius <= 359.99

41 Bakri 42 Bakri

7
9/14/2014

Compound Statements Semantics of Boolean Operators


 Use braces if the <then> or <else> block has multiple
statements.
if (testScore < 70)
{ P Q P && Q P || Q !P
[Link]("You did not pass“);
Then Block false false false false true
[Link]("Try harder next time“);
} false true false true true
else
true false false true false
{
[Link]("You did pass“); true true true true false
[Link](“Keep up the good work“);
Else Block
}

43 Bakri 44 Bakri

Boolean Variables Syntax for the switch Statement


switch ( <arithmetic expression> ) {
 The result of a boolean expression is either true or
<case label 1> : <case body 1>
false. These are the two values of data type boolean.

 We can declare a variable of data type boolean and assign <case label n> : <case body n>
a boolean value to it. } Arithmetic Expression
switch ( gradeLevel ) {
boolean pass, done; case 1: [Link]("Go to the Gymnasium");
pass = 70 < x; break;
Case
done = true; case 2: [Link]("Go to the Science Auditorium");
Label
if (pass) { break;
… Case
case 3: [Link]("Go to Harris Hall Rm A3");
} else { Body
break;

} case 4: [Link]("Go to Bolt Hall Rm 101");
break;
}

45 Bakri 46 Bakri

Repetition Statements Syntax for the while Statement


 Repetition statements control a block of code to be while ( <boolean expression> )
executed for a fixed number of times or until a certain
condition is met. <statement>
 Count-controlled repetitions terminate the execution of Boolean Expression
the block after it is executed for a fixed number of times.
 Sentinel-controlled repetitions terminate the execution of
while ( number <= 100 ) {
the block after one of the designated values called a
sentinel is encountered. sum = sum + number;
Statement
 Repetition statements are also called loop statements. (loop body) number = number + 1;
}

47 Bakri 48 Bakri

8
9/14/2014

Syntax for the do-while Statement The for Statement


for ( <initialization>; <boolean expression>; <increment> )
do
<statement>
<statement>
while ( <boolean expression> ) ;
Boolean
Initialization Increment
do { Expression

sum += number; Statement for ( i = 0 ; i < 20 ; i++ ) {


number++; (loop body)
number = [Link](); Statement
} while ( sum <= 1000000 ); sum += number; (loop body)
}
Boolean Expression

49 Bakri 50 Bakri

Array Basics
 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.
Array of primitives  In Java, an array is an indexed collection of data values of
the same type.

Collection of primitives value

51 Bakri 52 Bakri

Array of Primitive Data Types Array Processing – Sample1


 Array Declaration Scanner scanner = new Scanner([Link]);
double[] rainfall = new double[12];
The public constant
<data type> [ ] <variable> //variation 1 length returns the
capacity of an array.
<data type> <variable>[ ] //variation 2 double annualAverage,
 Array Creation sum = 0.0;

<variable> = new <data type> [ <size> ] for (int i = 0; i < [Link]; i++) {
[Link]("Rainfall for month " + (i+1));
 Example
Variation 1 Variation 2 rainfall[i] = [Link]( );
sum += rainfall[i];
double[ ] rainfall; double rainfall [ ];
}
rainfall rainfall
= new double[12]; = new double[12]; annualAverage = sum / [Link];

An array is like an object!


53 Bakri 54 Bakri

9
9/14/2014

Array Initialization Variable-size Declaration


 Like other data types, it is possible to declare and  In Java, we are not limited to a fixed-size array
initialize an array at the same time. declaration.
 The following code prompts the user for the size of an
int[] number = { 2, 4, 6, 8 };
array and declares an array of designated size.
double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,
9.00, 3.123, 22.084, 18.08 };
Scanner scanner = new Scanner([Link]);
String[] monthName = { "January", "February", "March", int size;
"April", "May", "June", "July", int[] number;
"August", "September", "October",
"November", "December" };
[Link]("Size of an array:"));
size= [Link]( );
[Link] 4
[Link] 9 number = new int[size];
[Link] 12

55 Bakri 56 Bakri

Java Package
 A Java package is a mechanism for organizing Java classes
into namespaces (like a folder).
 Java packages can be stored in compressed files called
JAR files.
Package  Programmers typically use packages to organize classes
belonging to the same category or providing similar
functionality.
Collection of classes

57 Bakri 58 Bakri

Standard Output
 Using [Link], we can output multiple lines of text to
the standard output window.
 We use the print method to output a value to the
standard output window.
Java Basic I/O (Extra)  Example:
 [Link]( “Hello, Dr. Caffeine.” );

Reading and displaying output

59 Bakri 60 Bakri

10
9/14/2014

The println Method Standard Input


 We use println instead of print to skip a line.  The technique of using [Link] to input data is called
int x = 123, y = x + x;
standard input.
[Link]( "Hello, Dr. Caffeine.“ );  We can only input a single byte using [Link] directly.
[Link]( " x = “ );
[Link]( x );  To input primitives data values, we use the Scanner class
[Link]( " x + x = “ );
[Link]( y ); (available from Java version 1.5).
[Link]( " THE END“ );

Scanner scanner;

scanner = new Scanner([Link]);

int num = [Link]();

61 Bakri 62 Bakri

Common Scanner Methods

Method Example

nextByte( ) byte b = [Link]( );


nextDouble( ) double d = [Link]( ); Math Class (extra)
nextFloat( ) float f = [Link]( );
nextInt( ) int i = [Link]( );
nextLong( ) long l = [Link]( ); Built-in math library in Java

nextShort( ) short s = [Link]( );


next() String str = [Link]();

63 Bakri 64 Bakri

The Math class Some Math Class Methods


 The Math class in the [Link] package contains class
methods for commonly used mathematical functions. Method Description
exp(a) Natural number e raised to the power of a.

log(a) Natural logarithm (base e) of a.

floor(a) The largest whole number less than or


double num, x, y; equal to a.
The larger of a and b.
max(a,b)
x = …;
y = …; pow(a,b) The number a raised to the power of b.

sqrt(a) The square root of a.


num = [Link]([Link](x, y) + 12.4);
sin(a) The sine of a. (Note: all trigonometric
functions are computed in radians)

65 Bakri 66 Bakri

11

You might also like