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

READING ASSIGNMENT IntroductionToJava ClassesVariablesDataTypesOperators

This document provides an introduction to object-oriented programming (OOP) concepts and creating a Java application in NetBeans. It discusses key OOP concepts like classes, objects, properties, methods, and inheritance using a person as an example. It then explains how to set up a Java project in NetBeans, including choosing a project type, giving it a name and location, and an overview of the IDE interface. The document aims to teach basic OOP principles and getting started with Java development.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

READING ASSIGNMENT IntroductionToJava ClassesVariablesDataTypesOperators

This document provides an introduction to object-oriented programming (OOP) concepts and creating a Java application in NetBeans. It discusses key OOP concepts like classes, objects, properties, methods, and inheritance using a person as an example. It then explains how to set up a Java project in NetBeans, including choosing a project type, giving it a name and location, and an overview of the IDE interface. The document aims to teach basic OOP principles and getting started with Java development.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Mr.

John - CS Friday, January 19, 2024

“CLASS” OBJECT ORIENTED PROGRAMMING (OOP) OBJECT ORIENTED PROGRAMMING (CONT’D)


Object oriented programming, many consider to be the key Objects make up the different parts of the program
methodology of the future
Related in a hierarchical manner
A class is a set of code in a file Though we will be examining the methodology of object oriented
programming over time, the concept of using objects is not new to you… For example a fictitious example of an object might be a person
separate from the main program If we think about the world around us, we look and see various objects Each object can contain Person
several sub-objects
(subclasses), which are a
part of the larger object
(superclass)
Head Body

Nose Mouth Arm


These objects have certain properties and can serve certain functions
Main Program
Connected Class (methods)
This is the basis of Object Oriented Hand
Programming (OOP)

OBJECT ORIENTED PROGRAMMING (CONT’D) OBJECT ORIENTED PROGRAMMING (CONT’D) OBJECT ORIENTED PROGRAMMING (CONT’D)
You can traverse to the lower objects using dot notation Objects can also have several properties Properties
To traverse to the Hand you will…
Person.Body.Arm.Hand Properties Head.Size = Large
Size = Medium
Person Head.Color = Green
Color = Red
Body Shape = Round Head.Shape = Square
Hand is a property Head
Head
of Arm
Arm
Traverse: These properties can be read and sometimes Read Person.Head.Color
changed
To travel through, taking
Hand the right path
Green

Introduction To Java (Classes, Variables, Data Types, Operators) 1


Mr. John - CS Friday, January 19, 2024

OBJECT ORIENTED PROGRAMMING (CONT’D) CREATING A JAVA APPLICATION


Java programs will be edited and compiled using a new IDE
Objects can also have several (Integrated Development Environment) from Sun Microsystems

methods called NetBeans


Start the program (NetBeans
Methods can perform tasks and 8) from the Start menu
Once the program loads,
return results when they complete you must first set up
Students let us examine ...
their tasks CREATING YOUR FIRST JAVA
a project to work on
This is done through
We will expand on this in our next APPLICATION… the File menu:

unit

CREATING A JAVA APPLICATION (CONT’D) CREATING A JAVA APPLICATION (CONT’D) CREATING A JAVA APPLICATION (CONT’D)

A project is a group of programming source files (code) and Now give your project a Make sure your name has no spaces, special characters (e.g.
name and browse to a $^&*@-/), and it must begin
the settings with which you build, run, and debug those
location to save it (your with a letter (not a number)
source files
folder) When you look at the IDE you are seeing:
Once your have selected this, a dialog box will appear to Then click Finish Files window: shows a directory-based view of your projects
determine the type of project you wish to create (a template) where you can open and edit your project configuration files
You will see this
For now we will pick screen Runtime window: displays information during project
Java  Java runtime Navigator Window
Application Navigator window: displays information about the java
source files in the currently opened project
Then click Next >
Source Editor: is a full-featured text editor that is integrated
with the GUI Builder, Projects window, compiler, and
debugger

Introduction To Java (Classes, Variables, Data Types, Operators) 2


Mr. John - CS Friday, January 19, 2024

CREATING A JAVA APPLICATION (CONT’D) RUNNING AN APPLICATION


Toolbar and Once your code is finished editing, you can compile your code using the
menu for NetBeans IDE toolbar
common
commands This button will execute a build (compile)
This button will execute the code (if a build
Project has not yet occurred, it will automatically build first)
windows
The code output will
appear here in the
Code
runtime window
Navigator
Students let us examine ... If an error occurred
window

Main source
RUNNING A JAVA APPLICATION anywhere in the code,
errors will instead be
code editor generated and
displayed in the
Runtime runtime window
window

“HELLO WORLD” IN JAVA “HELLO WORLD” IN JAVA (CONT’D)

The “Hello World” program is traditionally the first program learned in The first lines of code (and all code shaded this way) is a Java comment
Computer Science because it gives the basics of any computer program (more on comments later)
If we look at the various code statements we can get an understanding of
what’s going on
Add to the code already
“// TODO code application logic here”
Add a new line here…

Students let us examine ...

THE BASIC “HELLO WORLD”


The next line defines the name of
PROGRAM IN JAVA… the package
A package is the way Java organizes all the necessary classes (more on
Now let’s examine the various lines… classes later in the course)

Introduction To Java (Classes, Variables, Data Types, Operators) 3


Mr. John - CS Friday, January 19, 2024

“HELLO WORLD” IN JAVA (CONT’D) CLASS NAMES… “HELLO WORLD” IN JAVA (CONT’D)
This line is the class
definition for the By convention, all class names in Java begin with a
class “Main” capital letter and have a capital letter for every word
Every program in Java consists of at least one class definition that is in the name
defined by ‘you’ the programmer For example:
These classes are therefore defined as “User-defined classes” (similar SampleClassNameDefined
to the concept of user-defined procedures and functions discussed in
earlier units) This name is called an identifier
The keyword public states that this class is public to the application Identifiers can contain letters, numbers, underscore The next lines are a collection of comments and
The keyword class defines this line as a class definition (_), and dollar signs ($) but cannot begin with a something called a constructor
The word Main is the user-defined name for this class, notice the number (public Main) which we will cover in later units
color coding of keywords, all Java keywords are always typed in Identifier names are case sensitive, A1 is different
lowercase letters this year
from a1
For now, we will just accept these lines and move on…

“HELLO WORLD” IN JAVA (CONT’D) “HELLO WORLD” IN JAVA (CONT’D)


The curly brackets define where something Class definitions contain one or more methods (one must be
begins and ends, for example where the class {
main)
begins and ends ...
Methods are able to perform tasks and return information
Good programming practice has you put the
} when done (they are functions)
closing brackets on their own line, this helps with
code readability The keyword void indicates that the main method does
Brackets that match up with a code line are placed on the same indent not return anything
level
The other words in this line should be mimicked for now, and
explained later Students let us examine ...

This line of code is part of every Java application COMMENTS AND GOOD
Java applications (like all applications) begin execution at main This line instructs the computer to perform an action PROGRAMMING STYLE
The brackets following this line define it as a method In this case, to print – println() – a string of text
A method is a function for the class
(contained within the quotations)

Introduction To Java (Classes, Variables, Data Types, Operators) 4


Mr. John - CS Friday, January 19, 2024

COMMENTS AND STYLE COMMENTS AND STYLE (CONT’D) COMMENTS AND STYLE (CONT’D)
Comments are important in Java just as in any programming Method Style is important, good programming standards must be adhered to for
language two… your Java assignments, and are normal professional standards
There is two ways we will use to comment in Java (there is also a The /* Using comments after curly brackets { is an example of this to help
third we will not be discussing) programmers track which bracket matches up with which
opens the
Method The following standards are expected for your Java applications and
comment,
one… applets you will be writing (some will become more clear as we cover
the */
these topics):
closes it
1. Each of your program files must begin with
anywhere in your code a comment
Comments are ignored by the compiler block like the
They are used for the benefit of the programmer following:

Used to describe code that otherwise might be misinterpreted


Anything after the // will be ignored until the end of the line
Also used for other relevant information such as name, date, etc.
This is known as a single line comment

COMMENTS AND STYLE (CONT’D) COMMENTS AND STYLE (CONT’D) COMMENTS AND STYLE (CONT’D)

2. Insert a prologue comment at the beginning of each method 7. Use meaningful but reasonable variable names 9. Avoid the use of literal constants ("magic numbers") in your
(function) after the method declaration, which contains: Start in lower case and capitalize only the first letter of program
Parts of the prologue may
each new word, for example: Generally use constant (final) identifiers rather than
be omitted if appropriate,
e.g. if the method has no
literal constants in your program
int a; // Very bad, too short, not meaningful
parameters.
int averageMark; // Good
int average_of_all_the_marks_in_the_list; // Bad, too long and wordy
Acceptable exceptions are strings that appear only
once in output titles and headings, and small
3. Use blank lines to separate blocks of code and declarations to fundamental values, for example:
improve readability 8. Additional documentation of variables should appear in a
4. Provide a comment for each major loop and other major control comment following the variable declaration (note that this sum = 0;
count = count + 1;
// Literal constant 0 is OK
// Literal constant 1 is OK
structures requires one variable declaration per line), for example: price = total * 1.07; // No create a named constant like:
final double PST_RATE = 1.07;
5. Comment blocks of code to describe why you wrote the code this double maxFlow; // in river channel [m3/s]
lastDigit = accountNumber % 10; // Literal constant 10 is OK
if(codeLetter == 'R') // No create a named constant like:
way, not what each line does int swapCount; // 0 swaps needed if data is sorted final char REFUND_CODE = 'R';
6. Avoid declaring variables "as you go"

Introduction To Java (Classes, Variables, Data Types, Operators) 5


Mr. John - CS Friday, January 19, 2024

COMMENTS AND STYLE (CONT’D)


10. Use indentation to clarify control structures (e.g. for loops and if
constructs)
Align else with the corresponding if for readability
Avoid long lines; where needed, continuations of a
statement on a new line should be indented too
Any readable and consistent style is acceptable, the
essential features are that all statements that are nested
within another statement must be indented, and that the Students let us examine ...
braces { } must be in predictable and consistent positions
11. Appropriate prompts should always be used for interactive input LET’S WORK ON A LARGE
12. All output produced by your programs must have appropriate EXAMPLE…
titles and headings
13. Never change the value of a for loop variable inside the loop

COMPUTER SCIENCE OUTPUT TIPS OUTPUT TIPS (CONT’D)

In order to have the user involved in our programs we need to What’s happening in this line is somewhat complex, but let’s
get inputs and provide outputs examine some of the fundamentals happening…
We will be looking at graphics and GUIs this year, but later in Any code word typed in Java that starts with a capital letter and
then uses camel casing is a class
the course
This means the class has properties (things about it) we can
So our inputs/output will be more basic to start
access, and methods (actions that perform functions) we can use
The most basic output already seen We can recognize a class (“System”) and the action we have
(System.out.println()) provides simple outputs
used (“println”) to produce the action of making text appear
on the screen
System.out is the standard output object – the screen

Inputs and Outputs in Java


object, so the line prints the string to the screen

Introduction To Java (Classes, Variables, Data Types, Operators) 6


Mr. John - CS Friday, January 19, 2024

OUTPUT TIPS (CONT’D) OUTPUT TIPS


The use of rounded brackets ( ) indicate a method (function) is We can display our output across several lines of text or one line
being used, and the string inside the brackets is the argument being
The
sent to the method System.out.println("string of text");
This line of code, which performs an action, is known as a statement statement will automatically add a new-line character after the string
Every statement in Java must terminate with a semicolon ; The System.out.print("string of text");
Omitting the semicolon is a common programming error in Java, this statement does not add a new-line character after the string, for example:
will generate a syntax error, preventing the code from being
System.out.print("Hello to the ");
compiled
Students let us examine ... System.out.println("World");
In addition, spaces, tabs, carriage returns, and blank lines help with
code readability ADDITIONAL JAVA OUTPUT TIPS System.out.print("From Mr. John");

White-space (space bar) is ignored by Java in your code lines Produces this output:
except if it is contained within quotations indicating that it is part of a Hello to the World

string of text inside the quotes From Mr. John

OUTPUT TIPS (CONT’D) Dialog Boxes


We can display our output across several lines of text using one statement if we
use escape characters So far we have seen output using System.out, but this
Escape characters are special codes used inside of strings to create special is very limited, and we cannot get input this way
things like new-lines, tabs, etc.
For example: In order to provide better output and get user input, we need
to introduce interactive objects in a package (library) called
System.out.print("Hello\nWorld\nFrom\nMr. John");
JOptionPane
Produces Hello Java’s class JOptionPane provides pre-packaged
this World Students let us examine ...
output dialog boxes that provide you with this ability
From Mr. John
JAVA DIALOG BOXES One of the strengths of Java is it’s rich set of pre-defined
Escape characters always begin with a backslash \ packages that programmers can use rather than “re-
Other escape characters include \t for a tab, \\ to print a backslash in output, inventing the wheel”
and \" to create a quote in output

Introduction To Java (Classes, Variables, Data Types, Operators) 7


Mr. John - CS Friday, January 19, 2024

Dialog Boxes (cont’d) Dialog Boxes (cont’d) Dialog Boxes (cont’d)


These packages are referred to as the “Java Applications Now that this package is imported, you can use some of This code invokes the action of displaying the message box,
Programming Interface” (Java API) these packages are spilt it’s code to create the boxes and the values (called arguments) placed inside the brackets
into core packages (java) and extension (javax) packages For example to create a message box you could type: effect the appearance of the box
and are included with a Java install Some of these values can be omitted
Packages contain classes, which we can again see in action When there is more than one, they are separated with
here with the capital “J” of JOptionPane – once again
commas
meaning we have actions we can access
The first argument for this action is always (for now) the word
The JOptionPane class is part of the swing extension null
package (javax.swing.JOptionPane)
The second argument is a string of text (inside quotes) and is
To use this package, it must be imported into your Java what is displayed in the box
program using an import statement before you define your
class, (though This again is complex classes of imported code we are using
NetBeans usually import javax.swing.JOptionPane; with the attached actions (methods) to produce outputs
does this for you) for public class Testing The next sets of code show some variations of the message
example: {
box with more parameters added:

Dialog Boxes (cont’d) Dialog


Dialog Boxes (cont’d) Boxes
(cont’d)

In addition to message boxes, input boxes can be used to get user


input
Normally the input dialog boxes are used in conjunction with variables
(which we will be learning about shortly), but for now, here is an
example of this…

And some optional


variations on this…

Introduction To Java (Classes, Variables, Data Types, Operators) 8


Mr. John - CS Friday, January 19, 2024

Dialog Boxes (cont’d)


Dialog Boxes (cont’d)
As well, to take it to the next level, another option
is to use a confirm dialog box (this will not be
needed for any assignment), which you can
experiment with (if you wish)…

Students let us examine ...

LET’S CONTINUE OUR WORK ON


OUR LARGE EXAMPLE…
And some optional
variations on this…

Introduction To Java (Classes, Variables, Data Types, Operators) 9


Mr. John - CS Friday, January 19, 2024

COMPUTER SCIENCE

Java Variables

Variables Variables (cont’d) Variables (cont’d)


The name of the variable, or identifier, is how the
Remember that a variable is a memory location value will be referred to in the program Java defines a number of basic
which stores a value Variables are used for two purposes in Java, to variable types
To use a variable in a program it must be reference objects, and to store values in memory
defined by giving its type and identifier The term variable implies that the value inside it may
We also call these primitive, or built-
The type of the variable indicates what kind of vary (change) in data types
value it will store A declaration statement must be used to tell the
compiler the name of the variable and it’s data type
Java has eight built in types: byte,
In Java, some data types are built into the short, int, long, float, double,
A variable whose data type is a class, makes a
language, and some are defined by
programmers
reference of that class type (know as an instance – char, and boolean
more later)

Introduction To Java (Classes, Variables, Data Types, Operators) 10


Mr. John - CS Friday, January 19, 2024

Declaring a Variable Declaring a Variable (cont’d)

Declaring a variable in Java is a specific For example…


process to bring the variable into
“existence” in your program, you must:
int number = 0;
1. Give the data type This declares a variable of type
Students let us examine ... 2. Then the variable name integer named number with an
DECLARING VARIABLES 3. Then you should initialize your initial value of 0
variable to a starting value (although We will now examine this more
this is actually optional) closely

(1.) Byte - byte (2.) Short - short


The byte type is a basically a simple number (a very small The short type is a basically a simple number (shorter integer),
integer), ranging from: ranging from:

-128 127 - 32,768 32,767


Remember, no decimal places Remember, no decimal places
Students let us examine ... 8 bits used to store the variables 16 bits used to store the variables
For example… For example…
JAVA DATA TYPES
byte number = 100; short number = 10000;

Introduction To Java (Classes, Variables, Data Types, Operators) 11


Mr. John - CS Friday, January 19, 2024

(3.) Integer - int (4.) Long - long (5.) Float - float


The integer type is a basically a simple number, Basically a longer integer, ranging from: Floating point are a (limited precision)
ranging from:
representation of real numbers on the
-9,223,372,036,854,775,808 9,223,372,036,854,775,807
-2,147,483,648 2,147,483,647 computer
Same properties as an integer
Remember, no decimal places A float requires 32 bits
64 bits used to store the variables
32 bits used to store the variables For example… For example…
For example…

long number = 1000000000000000000; float number = 1234.56789f;


int number = 1000000000;

(6.) Double - double (7.) Character - char (8.) Boolean - boolean


Double precision are also a representation of The char type hold one character, not a string of The Boolean values can only hold true and
real numbers characters false values
This is the largest decimal representation of The char type can hold any of the ASCII characters, Java uses the keyword boolean unlike
and must be enclosed in single quotes ''
‘real’ numbers Java’s parent language C++ (and C#), where
For example… char type variables are assigned Boolean variables are declared using the
For example… values with the character value in keyword bool
single quotations ''
For example…
double number = 1234567890.0987654321;
char charater = 'A'; boolean found = true;

Introduction To Java (Classes, Variables, Data Types, Operators) 12


Mr. John - CS Friday, January 19, 2024

Naming Variables Naming Variables (cont’d)

Java is a strongly typed language, meaning A strongly typed language makes for:
that we have to watch our syntax
More compiler errors
For example…
Fewer bugs (programmers must think)
char firstLetter = 'A'; Faster code when finished
Students let us examine ...

JAVA NAMING RULES Char secondLetter = 'B'; Variables identifier names have to
follow naming rules similar to other
This will compile with an error, you cannot use a
capital and it will not fix it for you programming languages

Naming Variables (cont’d) Naming Variables (cont’d) Naming Variables (cont’d)


You can use letters (A-z, a-z), numbers (0-9),
For example, these are legal… These are illegal…
dollar signs ($), and Underscore ( _ )
You cannot begin a variable name with a number int 42_is_a_Number = 0;
Case matters (e.g. MYNAME is different from char firstLetter = 'A';
myName) char president-Miyako = 'A';
int x = 0;
Dollar signs and underscore are not recommended to boolean how_Much_! = false;
begin variable names float x232Y = 0;
Remember that in good style you should use char your Name = 'B';
byte thisIsAVeryLongName = 0;
meaningful but reasonable variable names, start in
lower case and capitalize only the first letter of each Also, Java keywords are also illegal
new word

Introduction To Java (Classes, Variables, Data Types, Operators) 13


Mr. John - CS Friday, January 19, 2024

Operators Constants
Operators are used in the same way as VB ( +, -, *, / ) Constants can also be used in Java (and should
with precedence order
be used)
1. Unary minus –x 5. Division x / y
They define a variable value that doesn’t change
2. Addition x + y 6. Modulus x % y
However, in Java, the term final is used
3. Subtraction x - y instead of const (which is used in Java’s
Students let us examine ...
4. Multiplication x * y parent language C++)
USING JAVA VARIABLES
For example…
Integer division automatically truncates the
decimal point final float PI = 3.14;

Increment & Decrement Operators Short Hand Operators Using Variables (cont’d)
Java has two somewhat special operators As well, the basic math operations can use another short-hand public class VariableExample
notation to assign values to variables in a quicker (less-typing) {
The increment ++ and decrement -- way, for example… public static void main(String args[])
operators, for example… int x = 10, y = 7; {
int x = 6, y = 15, z = 0;
int moreCount = 0; x += y; //same as x = x + y char ch1 = 'L', ch2 = 'a', ch3 = 'r',

x -= y; //same as x = x - y ch4 = 'r', ch5 = 'y';


int lessCount = 10; z *= 5 * x - y;
x *= y; //same as x = x * y System.out.println(ch1 + ch2 + ch3 + ch4 +
moreCount++; //now 1 ch5 + " is a " + z);
x /= y; //same as x = x / y
} //end main
lessCount--; //now 9 x %= y; //same as x = x % y Larry is a 0
} //end class

Introduction To Java (Classes, Variables, Data Types, Operators) 14


Mr. John - CS Friday, January 19, 2024

Converting Data Types Converting Data Types (cont’d)


In Java arithmetic operation should always be done on To perform math on different variables types, conversion to one set
variables of the same type type must be done
Data types can be converted in two ways, which is known a type
For example adding two integers will return a integer result,
casting (or just casting)
multiplying two doubles will return a double result, etc.
Method 2 works with string (seen later), but method 1 works with
When performing arithmetic on two different types the result is numerical data
indeterminate Method 1:

Students let us examine ...


For example… int x = 0;
int count = 10; double y = 7.8;
CONVERTING BETWEEN DATA double score = 6.5; x = (int)y;
TYPES int average = count / score; /* this evaluates to 7, by converting the value
/* ERROR, the result would be a double (decimal) inside the double y to an integer and
which cannot be assigned to an integer */ therefore truncating the decimal portion*/

Converting Data Types (cont’d)


Other examples…
byte a = 50; short b = 50; int c = 50; long d = 50;
float e = 30; double f = 30.1234567890123456789;
a = (byte)b; b = (short)a; c = (int)d; d = (long)e;
e = (float)f; f = (double)a;
System.out.println("a is: " + a);
System.out.println("b is: " + b);
a is: 50
System.out.println("c is: " + c); b is: 50
System.out.println("d is: " + d); c is: 50
d is: 30
System.out.println("e is: " + e); e is: 30.123457
System.out.println("f is: " + f); f is: 50.0

Introduction To Java (Classes, Variables, Data Types, Operators) 15

You might also like