Notes Java
Notes Java
Computer Programming
- computer science discipline dealing with the creation and maintenance of computer programs
- is just one activity in the more complex field of software engineering
Programming Language
- a standardized communication technique for expressing instructions to a computer. Like human
-
running programs
Java programming environment: Set of libraries that provide
Java
-
/* This program displays the message "Hello, World!" on the standard output device (usually the screen)...This
code must be saved in a file named HelloWorld.java...
*/
// this is the declaration of the HelloWorld class...
public class HelloWorld {
// the main method defines the "starting point" of the execution
// of this program...
Fundamental
Concepts
public
static
void
main(String[]
- Java programs
are
made
up ofargs)
one{ or more classes.
// this statement displays the programs output...
- A Java class is defined through a class declaration, which, aside from assigning a name for the class,
System.out.println("Hello, World!");
also
serves
to define
} //
end of method
main...the structure and behavior associated with the class.
By convention, Java class names start with an uppercase letter. Java programs are case-sensitive.
A Java source code file usually contains one class declaration, but two or more classes can be declared
in one source code file.
The file is named after the class it declares, and uses a .java filename
extension.
For a class to be executable, it must be declared public, and must provide a public static method called
extension.
- The Java Virtual Machine (java) is used to execute the class file.
Java Comments
- Comments are notes written to a code for documentation purposes. Those texts are not part of the
program and do not affect the flow of the program.
o Two types of comment
Single Line Comment
Example:
//This is an example of a single line comment
Multiline Comment
Example:
/* This is an example of a
multiline comment enclosed by two delimiters
that starts with a /* and ends with a */
*/
System.out.println(Hello world);
A block is one or more statements bounded by an opening and closing curly braces that groups the
statements as one unit. Block statements can be nested indefinitely. Any amount of white space is
allowed.
An example of block is,
public static void main (String[] args)
{
System.out.println(Hello) ;
System.out.println(World) ;
}
Java Identifiers
- Identifiers are tokens that represent names of variables, methods, classes, etc. Examples of identifiers
are: Hello, main, System, out.
Java identifiers are case-sensitive. This means that the identifier: Hello is not the same as hello.
Identifiers must begin with either a letter, an underscore _, or a dollar sign $. Letters may be lower
In case of multi-word identifiers, use capital letters to indicate the start of the word except the
first word. For example, charArray, fileNumber, ClassName.
Avoid using underscores at the start of the identifier such as _read or _write.
Coding and Debugging
- Most of the time, after a programmer has written the program, the program isnt 100% working right
away. The programmer has to add some fixes to the program in case of errors (also called bugs) that
-
Java Keywords
- Keywords are predefined identifiers reserved by java for specific purposes. You cannot use keywords as
names of variables, classes, methods, etc.
boolean variable can represent any two states such as a light bulb being on or off
example:
boolean isOn = true;
Characters
- a char variable stores a single character
- character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' '\n'
Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';
- A character set is an ordered list of characters, with each character corresponding to a unique number
- A char variable in Java can store any character from the Unicode character set
- The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters
- It is an international character set, containing symbols and characters from many world languages
- The ASCII character set is older and smaller than Unicode, but is still quite popular (in C programs)
- The ASCII characters are a subset of the Unicode character set, including:
Character Strings
- A string of characters can be represented as a string literal by putting double quotes around the text:
Examples:
"This is a string literal."
"123 Main Street"
"X"
- Note the distinction between a primitive character X, which holds only one character, and a String
object, which can hold a sequence of one or more characters
- Every character string is an object in Java, defined by the String class
Variables
- a variable is a name for a location in memory
- a variable must be declared by specifying the variable's name and the type of information that it will
hold
Variable Initialization
- assigning a value to a variable for the first time
- a variable can be given an initial value in the declaration with an equals sign
example:
int sum = 0;
int base = 32, max = 149;
prints as:
A piano has 88 keys
Assignment
- an assignment statement changes the value of a variable
- the equals sign is also the assignment operator
- the expression on the right is evaluated and the result is stored as the value of the variable on the left
- the value previously stored in total is overwritten
- you can only assign a value to a variable that is consistent with the variable's declared type
Constants
- a constant is an identifier that is similar to a variable except that it holds the same value during its
-
entire existence
as the name implies, it is constant, not variable
in Java, we use the reserved word final in the declaration of a constant
example:
final int min_height = 69;
any subsequent assignment statement with min_height on the left of the = operator will be flagged as
an error
Constants are useful for three important reasons
o first, they give meaning to otherwise unclear literal values
for example, NUM_STATES means more than the literal 50
o second, they facilitate program maintenance
if a constant is used in multiple places and you need to change its value later, its value
o
programmers
The println Method
- the System.out object represents a destination (the monitor screen) to which we can send output
System.out.println ("Whatever you are, be a good one.");
Object
Method
name
The print Method
- the System.out object provides another method
- the print method is similar to the println method, except that it does not start the next line
- therefore any parameter passed in a call to the print method will appear on the same line
System.out.print (Three );
System.out.print (Two );
prints as:
Three Two
String Concatenation
- the string concatenation operator (+) is used to append one string to the end of another
"Peanut butter " + "and jelly"
- it can also be used to append a number to a string
- a string literal cannot be broken across two lines in a program so we must use concatenation
System.out.println(We present the following facts for your + extracurricular edification);
- the + operator is also used for arithmetic addition
- the function that it performs depends on the type of the information on which it operates
- if both operands are strings, or if one is a string and one is a number, it performs string concatenation
- if both operands are numeric, it adds them
- the + operator is evaluated left to right, but parentheses can be used to force the order
System.out.println(24 and 45 concatenated: + 24 + 45);
prints as:
24 and 45 concatenated: 2445
- the + operator is evaluated left to right, but parentheses can be used to force the order
Addition is done first
System.out.println(24 and 45 added: + (24 + 45));
prints as:
Escape Sequences
- What if we want to include the quote character itself?
- The following line would confuse the compiler because it would interpret the two pairs of quotes as two
strings and the text between the strings as a syntax error:
Prints as:
Prints as:
Body temperature is 98.6 F.
Operators
In Java, there are different types of operators. There are arithmetic operators, relational operators,
logical operators and conditional operators. These operators follow a certain kind of precedence so that the
compiler will know which of the operator to evaluate first in case multiple operators are used in one
statement.
Arithmetic Operators
Operator
Operation
Addition
Subtraction
Multiplication
Division
Modulus (Remainder)
Example
2+4 =6
2 + 2.4 = 4.4
5.2 + 7.3 = 13.5
45 90 = - 45
2.9 2.5 = 0.399999999
2.9 2 = 0.8999999999
2 * 7 = 14
2.9 * 2 = 5 .8
2.9 * 2.1 = 6.09
2/7=0
2.9 / 2 = 1.45
2.1 /2.9 = 0.7241379310
2%7=2
2.9 % 2 = 0.8999999999
2.9 % 2.1 = 0.799999998
Note:
When evaluating the mod operator with negative integer operands, the answer always takes the sign of
the dividend.
Illustration:
-34 % 5 = -4
34 %-5 = 4
-34 %-5 = -4
34 % 5 = 4
Terms:
OPERANDS may refer to the numbers or alphabetical symbols that we use in our expression ( formula )
UNARY OPERATORS operators that only have one operand. (example: -5)
BINARY OPERATORS operators that have two operands
Increment/Decrement Operators
- Aside from basic arithmetic operators, Java also includes a unary increment operator and unary
decrement operator.
o Increment Operator (++)
- increases the value of a variable by 1
Example:
int count = 3;
count = count + 1;
// the above statement may be written as the one
//shown below.
count++;
Relational Operators
- Relational operators compare two values and determine the relationship between those values.
- The outputs of evaluation are the boolean values true or false.
Operator
Description
>
Greater than
>=
<
Less than
<=
==
Equal to
!=
Not equal to
Logical Operators
- Logical operators have Boolean operands that yield a Boolean result.
Operator
&&
||
Description
Logical AND
- Returns True if all of its boolean
operands are True, False if otherwise.
Logical OR
- Returns True if at least one of its
Boolean operands are True, otherwise
False
Logical NOT
- Reverses the value of its operand.
Illustration
True && True = True
True && False = False
False && False = False
True||True = True
True||False = True
False||False = False
!True = False
!False = True
Conditional Operators
- The conditional operator (?) is a ternary operator. This means that it takes three arguments that
together form a conditional expression. The structure of an expression using a conditional operator is,
exp1?exp2:exp3
Wherein exp1 is a Boolean expression whose result must either be True or False
If exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned.
Example:
Prints as
Failed