[Tutorial]Chapter 1 - Basic Java Syntax
Basic Java Syntax
Chapter 1 of Ultimate Java Tutorial
General Knowledge
All Methods, Classes, Loops, Conditionals begin with a { and end with a }
All Statements end with a ;
The Java Syntax is CASE SENSITIVE. This means that settitle, setTitle, SETTITLE, sEtTiTle are all different methods.
Indentation is the spacing of code in a program to make it more organized and easier to read.
Naming Convention
Classes and Interfaces – The first letter should be capitalized, and the beginning of a new word in the name should be capitalized (example: thisIsAnExample). This is called camelCase. Class names should typically be nouns (Dog, Account, PrintWriter). Interfaces should typically be adjectives (Runnable, Serializable).
Methods – The first letter should be lowercase, and then normal camelCase rules should be used. Also, typically should be verb-noun pairs (getBalance, doCalculation, setCustomerName).
Variables – camelCase format should be used, starting with a lowercase letter. Sun recommends short, meaningful names.
This means: buttonWidth, accountBalance, myString.
NOT: thisIsMyVariableWhoseNameShallNotBeWritten, _R%223f2rf, variablenumber24211
Constants – Java Constants (variables whos value does not change) are created by marking the variable static and final. They are to be named in all uppercase and underscores (_) for seperators (MIN_HEIGHT).
Identifiers
An Identifier is a word you use to access a variable, or, its name.
Java has rules for identifiers:
1. Identifiers must start with a letter, a currency character ($), or a connecting character (-,_). CANNOT START WITH A NUMBER.
2. After the first letter, the identifier can contain any combination of letters, currency characters, connecting characters, or numbers.
3. In practice, there is no limit to the number of characters an identifier can contain.
4. You cannot use a Java keyword as an identifier (any words used by Java already. Meaning, Class, main, abstract, int, char, etc..
5. Identifiers are case sensitive. foo is not FOO.
Example of legal and illegal identifiers:
Legal:
int _a;
int $c;
int ______2_w;
int _$;
int this_is_a_very_detailed_name_for_an_identifier;
Illegal:
int :b; (begins with a char)
int –d; (begins with a char)
int e#; (contains an illegal char (#))
int .f; (begins with a char)
int 7g; (begins with a number)
Modifiers
Modifiers are a big thing.
Modifiers are Java keywords used to describe the level of access allowed to a method, variable, or class.
Modifiers include:
Default: When no modifier is written before the class name. This gives any class in the same package (a collection of classes) access to that class. Any class outside the package cannot access the class. Example:
Code:
package cert;
Class Beverage { }
And then:
Code:
package stuff.stuff;
Import cert.Beverage;
Class Tea extends Beverage { }
The code imports the Beverage class. The tea file cannot compile, because its not in the same package as Beverage, and cannot access Beverage (You know the Beverage class is there, but to the tea class, its as if the Beverage class doesn’t exist, its invisible.)
Public – This gives all classes from all packages access.
Code:
package stuff;
public class Beverage
This gives any class access to the Beverage class. Using the public modifier makes the Beverage class visible to other classes.
Final – This modifier ensures that no class subclasses the class. More on “Subclassing” in Chapter two.
Abstract – An abstract class can never be instantiated (No object can be made of it, more on objects in chapter two). Its sole purpose is to be extended, subclassed. Abstract classes have methods and variables, but they are empty. Nothing. Nada. “Why?” you may ask.
Perhaps you have a class Car, but that’s just too generic. Whats the color? Horsepower? How many seats? All wheel drive? You can make the class abstract, and then when other classes extend it, they will override the methods.
Don’t worry about all of this Subclassing, Extending, and Overriding stuff. This will all be covered in upcoming chapters.
main()
As discussed in the previous chapter (Intro) all applications have a main() method. This is the method that gets everything started. When an application is started, only the main() method runs. You simply call upon other classes from the method.
What can I do in the main method?
Do something
Statements: Declarations, assignments, method calls, etc.
Code:
int x = 3;
String name = “Dirk”;
x = x * 17;
System.out.print(“x is “ + x);
double d = math.random();
// this is a comment
Do something again and again
Code:
while (x > 12) {
x = x – 1;
}
for (int x = 0; x < 10; x = x + 1) {
System.out.print(“x is now “ + x);
}
Do something under this condition
Code:
if (x ==10) {
System.out.print(“x must be 10”);
} else {
System.out.print(“x isn’t 10”);
}
If ((x < 3) & (name.equals(“Dirk”))) {
System.out.println(“Gently”);
}
System.out.print(“This line runs no matter what”);
Variables
Now, you’re ready to learn the variables.
There are two types of variables in Java.
Primitives – One of eight types: char, Boolean, byte, short, int long, double, or float. Once it is declared, it will always stay a primitive, but its value can (and should, 95% of the time).
Reference Variable – A reference to an object. This will be looked at more in depth later.
Declaring Primitives – Write out the type of primitive, a space, and the name, followed by either a comma (,) and then more names, or a “;”. Example:
Code:
byte b;
Boolean myBooleanPrimitive;
Int x, y, z; // This line makes 3 int variables, x, y, and z.
Assignment – Assigning a value to a primitive. “Reference, ‘=’, value”
Code:
int x; //Declare
x = 15; //Assign
String name; //Declare
Name = “Richard”; //Assign
short num = 3; //Declare and assign.
Primitives can hold a range of values. This is the range:
Byte – 8 bits. 1 Byte. Minimum Range = -2^7. Maximum Range = 2^7 – 1.
short – 16 bits. 2 Byte. Minimum Range = -2^15. Maximum Range = 2^15 – 1.
int – 32 bits. 4 Byte. Minimum Range = -2^31. Maximum Range = 2^31 – 1.
long – 64 bits. 8 Byte. Minimum Range = -2^63. Maximum Range = 2^63 – 1.
float – 32 bits. 4 Byte. Minimum Range = n/a. Maximum Range n/a.
double – 64 bits. 8 Byte. Minimum Range = n/a. Maximum Range = n/a.
Bytes, shorts, ints, longs hold whole digit values (1,6,19384,491849,-422) and cannot hold decimal values.
Floats and doubles hold decimal values (4.5, 8.5245, -9.452) and can hold whole digit values, but as“4.0”
Variables, like Classes, have modifiers.
Public – All classes, regardless of the package they belong to can access the method or variable.
Private – Cannot be accessed by any code outside of the class. The variable or method can only be called upon by other code in the class.
Protected – Any variable or method declared protected can be accessed by a subclass of the class they are located in, regardless of which package they are in.
Default – Variables or Methods without a modifier actually have a default modifier, and cannot be accessed by any class outside of the package they are in. (A class in Pack A cannot access a method in a class in Pack B).
Loops
Loops are used to do something over and over again.
There are three types of loops.
While Loop – Checks the condition at the beginning of the loop, and enters loop body code if the condition is met. If not, the entire loop is skipped.
Do…While Loop Enters the loop and completes one iteration, then checks a condition at the end, and if it is met, loops until it is not met.
For Loop A loop in which a counter variable is used, and completes when a condition is met. The counter variable changes each iteration.
Examples:
While Loop Example
Code:
x = 10;
While (x > 1) {
System.out.println(“x is “ + x);
x = x – 1;
}
Explanation:x is assigned the value “10”. The condition is checked, and approved ( 10 > 1 ). The loop writes “x is __” where __ is x’s value. Next, the value of x is decreased by one from 10 to 9. This continues over and over until x’s value is 1, and it no longer meets the condition, and the code after the loop continues.
Do…While Loop Example:
Code:
x = 10;
do {
System.out.println (“Cool, x > 8”);
x = x – 1;
} while (x > 8);
Explanation:x is assigned the value “10”. The loop begins, and it outputs “Cool, x > 8”. x’s value is decreased by one and its new value is 9. The condition is checked, approved, and the loop repeats. The condition is checked, not approved, and the rest of the code continues.
For Loop Example:
Code:
for (int x = 1; x < 5; x++) {
System.out.println(“One more time…”);
}
Explanation:x is assigned the value 1. The condition is assigned. The increment is assigned. This means that int x begins as the value 1, each iteration of the loop it increases by 1 (x++), and the loop will continue until the condition (x<5) is not met. This will print “One more time…” 4 times.
C++ freaks love this
Shorten your code.
Instead of using “x = x + 1”, you can write “x++;”
Theres a whole list of what you can do to shorten your code:
Increment a value by 1: x++;
Decrement a value by 1: x—;
Increment a value by a value: x += 5; versus x = x + 5;
Decrement a value by a value: x -= 5; versus x = x - 5;
Multiply a value by a value: x *= 5; versus x = x * 5;
Divide a value by a value: x /= 5; versus x = x / 5;
C++, C, and C# programmers love this because they enjoy making their code sloppy.
Please, only use this syntax in a for loop declaration (x++), don’t use it generally, it makes your code more difficult to understand. Type our your damn words.
Conditionals
What if you want to do something only if a condition is met, but only once (Not over and over like a loop)? Conditionals to the rescue.
Conditional: A block of code that is entered and completed if a Boolean expression is met (Boolean means true/false).
Example:
Code:
x = 5
y = 9
z = 46
if (y > x) {
System.out.println(“Y > X”);
}
if ((y>x) && (x>z)) {
System.out.println(“y>x, x>z”);
}
if (x == 5) {
System.out.println(“x is 5”);
} else {
System.out.println (“X is not 5”);
}
Explanation: X,Y, and Z are assigned the values 5, 9, and 46 (respectively). The first conditional checks if y > x (true, 9 > 5) and prints “Y > X”. The second conditional uses the && operator, meaning “And”. This means that for the conditional to be true, both Boolean expressions must be true. One is true, but one is not (x > z is false.), and because of this, the code is never entered. The “else” keyword after a conditional signifies that “If that conditional is true, do this”. You can optionally add an “if” after the else to make it “If this is not true, check if this is true”.
Operators in Conditionals
&&: Checks that both Boolean expressions are true. It’s like a True/False > T/F, T/F system. One false Boolean expression makes the “big” True/False condition to false.
[b]||[b]: “Or”. If either of the conditions, or both, are true, the code of the conditional will be entered.
==: “Equals”. Checks if the value on the left side is equal to the value on the right side.
!=: “Does not equal” Checks if the value on the left side does not equal the value on the right side. Example:
Code:
5 != 6 // This is true
6 != 6 // This is false
>, <, >=, <=: The typical Less than, greater than, less than or equal to, and greater than or equal to. I hope you know this stuff…
[b]^[b]: “Only one can be true”. Returns true if one of the two Boolean expressions, and only one, is true. If two are true, or none are true, it returns false.
The Next Chapter will be about Polymorphism and Objects