Java Basics
An introduction to Java programming languages. This post is intended to people who already know Java language but not sure about limits of what they can do and they cant such as which identifiers are valid which are not valid. An array can be defined in how many different ways ? Variables in interfaces. Enum definitions. Naming rules.
Legal Identifiers
- Identifiers must start with letter, currency character ( $ ) or connecting character( _ ).
- After first character identifiers can contain any combination of numbers,letters,currency character or connecting characters.
- Identifier can be composed of unlimited character.
- You can not use Java keywords as identifier.
- Identifiers are case sensitive. abc,Abc,ABC are all different identifier.
Some valid identifiers
int _x; int $y; int _$ int _a_very_very_very_very_very_long_identifier; |
Some invalid identifiers
int :x; int y# |
Java Keywords
abstract |
continue |
for |
new |
switch |
assert*** |
default |
goto* |
package |
synchronized |
boolean |
do |
if |
private |
this |
break |
double |
implements |
protected |
throw |
byte |
else |
import |
public |
throws |
case |
enum**** |
instanceof |
return |
transient |
catch |
extends |
int |
short |
try |
char |
final |
interface |
static |
void |
class |
finally |
long |
strictfp** |
volatile |
const* |
float |
native |
super |
while |
| * | not used | |
| ** | added in 1.2 | |
| *** | added in 1.4 | |
| **** | added in 5.0 |
Sun Java Code Conventions
Classes and Interfaces
First letter should be uppercase, and class or interface name contains more than one word, each word should start with an uppercase letter.
Car
FileReader
DataValidator
Interfaces names should be adjective
Runnable
Serializable
Methods
First letter should be lowercase and each word should start with uppercase. It is prefferred to combine verb-noun pairs.
getName
setName
Variables
Format is similar to methods.
deviceValue
parameterCache
Constants
Constants is defined by using static final <VARIABLE_NAME>. All characters should be uppercase and each word should be seperated by underscore.
Java Beans
Java Beans are classes which also have properties. In here, properties means private instance variables. Since variables are private, ony way to access those variables is to use methods. Getters methods are retrieve value of properties and setters methods set the value of properties.
If your property is a boolean variable you should start your getter method with “is” or “get”. But if you property is not a boolean variable you should always use “get”. Setter methods start with “set”.
Getter methods should return some value, for example you dont need a “length” variable to define “getLength()” method. It is ok to return some value independent from any variable. Getter methods must be public without arguments.
Setter methods should be public with a void return value.
JavaBean Listener Naming Rules
Register listener format : add<Listener Type> -> addActionListener(ActionListener actionListener)
Unregister listener format: remove<Listener Type> -> removeActionListener(ActionListener actionListener)
Listener type must be passed as an argument to add and remove methods.
Valid JavaBeans
public void setValue(String value)
public Stirng getValue()
public boolean isOnline()
public void setOnline(boolean online)
public void addMyListener(MyListener m)
public void removeMyListener(MyListener m)
Invalid JavaBeans
void setValue(String value) -> must be public
String readValue() -> read is invalid, it must be getValue()
public void addMusicListener(ActionListener actionListener) -> listener type mismatch
Class Declaration
Source File Declaration
- There can be only one public class per source file
- Comments could be anywhere in source file.
- The name of public class must match file source file name.
- If class is in a package, “package” statement must be first statement.
- “import” statement must be between “package” statement and class declaration.
- A file can have more than one non-public class.
Class Declaration and Modifiers
class MyClass{}
Access Modifiers : private,protected,public
Non Access Modifiers : strictfp,final,abstract
Java is a package centric language, lets think that, you are using third party libraries and they dont put their classes in packages. If all libraries contains Utils class, when you use Util class compiler cannot know which Util class you are referring. Sun recommends using reverse domain names for package e.g com.eguller.server.Utils
Class Access
Default Access
If you dont use any modifier when defining a class, it means default access. A default access class can only be seen by classes in same package.
package common; class Car{} |
package auto.sports; import common.Car; class SportCar extends Car{} |
Car class compiles but when you try to compile SportCar class compilation fails because Car class is not visible for SportCar class, Car has default modifier, Car and SportCar are in different packages. This problem can be solved by defining Car class public.
Public Access
All classes can access a public, even if they are in different packages. To fix above problem, we can define Car class public.
package common; public class Car{} |
So SportCar class can be compiled successfully.
Final Classes
Final classes can not be extended buy why ? Is not it against nature of OO. In some cases you have to guarantee implementation of your methods. Most of core classes are final in Java library for example String,Integer etc.
package common; public final class Car{ public void break(){} } |
If we try to compile SportCar class you get an error. “Can’t subclass final classes”. Think about that we did not marked Car class as final, end another developer overrode break method and implemented acceleration. While you are expecting to break() method to stop Car, it causes a big crash for SportCar.
Abstract Classes
Abstract classes cannot be instantiated. So why they are exist ? You always have to subclass to use an abstract class. They are nearly opposite of final classes.
package common; public abstract class Car{ public abstract int getDoorCount(); } |
package auto.sports; import common.Car; class SportCar extends Car{ public int getDoorCount(){ return 2; } } |
package auto.sports; import common.Car; class FamilyCar extends Car{ public int getDoorCount(){ return 4; } } |
Abstract methods does not have a body and they are ended with a semicolon. All sub-classes of an abstract class must implement abstract methods of parent. But if sub-class is also an abstract class, you don’t have to implement abstract methods, sub-sub class is not abstract, it have to implement abstract methods.
If a class contains one abstract method, class also must be abstract.
Abstract classes can contains non-abstract methods.
Interface Declarations
Interfaces are simply abstract classes which all methods are abstract. Interfaces cannot be instantiated like abstract classes. Interfaces give common capabilities to unrelated classes. For example, Car and House, both have doors and you want to treat them same kind of object while making operation on door counts.
public interface DoorCountable { public int getDoorCount(); } |
public class Car implements DoorCountable { public int getDoorCount(){ return 2; } } |
public class House implements DoorCountable { public int getDoorCount(){ return 8; } } |
public class Doors { public static void main(String[] args){ DoorCountable houseDoor = new House(); DoorCountable carDoor = new Car(); } } |
- Interface methods cannot be static
- Interface methods cannot be final
- An interface can be extended only by interfaces.
- An interface is declared with interface keyword
Following interface declarations are valid and identical
“public interface DoorCountable” and “public abstract interface DoorCountable”
abstract and public modifiers on interface methods are redundant.
Interface Constants
Normally a constant composed of “static” “final” modifiers. But when you are defining constants in interfaces
you don’t need to type static and final explicitly.
All following are identical
public int x = 1; non-static,non-final but it is when you use interface. int x = 1; static int x = 1; final int x = 1; public static int x = 1; public final int x = 1; static final int x = 1; public static final int x = 1; |
Declare Class Members
Classes can use two of four access levels but class members can use four of them.
- public
- protected
- default
- private
When you don’t type any modifier, it refers to default access.
When a member defined as public, all other classes can be reach this class even if they are not in same package.
Private members cannot be accesses in another class except their own class.
Private members cannot be overridden.
A default member can only be accessed by a class in same package with its owner class.
Protected members can be accessed by a subclass even if subclass and superclass are in different packages.
package first; public class FirstClass{ void doSmth(){ // default access //do smth here } } |
package second; import first.FirstClass; public class SecondClass { public static void main(String[] args){ FirstClass first = new FirstClass(); first.doSmth(); // doSmth() method is not visible. } } |
Default access and protected access is different when we are mentioning about subclassing.
package a; public class A { void abc(){ } protected void xyz(){ } } |
Default access is based on package structure, abc() method is not visible to subclass B because abc() has default access and superclass A and subclass B are in different packages. protected members are independent from package, xyz() is visible to subclass B even if superclass A an subclass B are in different package.
package b; import a.A; public class B extends A { public B(){ super.xyz(); // valid - super.abc(); //invalid compile error. } } |
For a subclass outside the package, the protected member can be accessed only through inheritance.
What happens in following scenario. memberA is protected, and it is visible in class B, and class C is in same package with class B. Can class c access memberA via class B. No, memberA is protected in class A but when memberA is inherited by class B, it becomes private in class B, so nobody can access memberA except class B itself.
package a; public class A { protected int memberA = 0; } |
package b; import a.A; public class B extends A { } |
package b; public class C { B b = new B(); System.out.println(b.a); } |
Access modifiers cannot be applied to local members
package a; public class A { public void applyLocal(){ private int memberA = 0; //compile error. } } |
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
public |
Y | Y | Y | Y |
protected |
Y | Y | Y | N |
| no modifier | Y | Y | N | N |
private |
Y | N | N | N |
Non-access Modifiers
You already know final and abstract, others are transient, synchronized,native,scrictfp and static. We will talk about static later.
Final Methods
Final methods cannot be overidden.
Final Arguments
public int getPopulation(final String city)
You can not change value (re-assignment) of final method parameter. For example city’s value is
“istanbul” you can not do that, city=”athens” in method.
Abstract Methods
Abstract methods are just method definitions, method name + signature + method parameters. Abstract methods does not have functional code. Abtract methods ended with semicolon.
public abstract void playMusic();
If you have an abstract method, the class which owns abstract method also must be abstract. But vice versa, an abstract class can have non-abstract methods.
All non-abstract (concrete) subclasses of an abstract class must implement abstract class methods of superclass.
Synchronized Methods
If a method is synchronized only one thread can access method at a time. For more details see Java Threads section.
Native Methods
Native methods are implemented in platform dependent code like C.
Methods with Variable Arguments Lists
You often see methods in fixed size arguments.
public void doStuff(int a,String b); Arguments are “a” and “b”. If number of arguments changes according to condition you can use variable length arguments.
void doStuff(int… x){} this method is equals to doStuff(); , doStuff(int x); , doStuff(int x,int y); , doStuff(int x, int y, int z); and so on.
There are some rules about variable arguments. A method can only have one variable argument. Variable arguments must be last argument in method.
doStuff(int… x,char a); -> invalid.
doStuff(int x…); -> invalid.
doStuff(int… x, String… y); -> invalid.
Constructors
Every class have at least one constructor. Constructors are called at object creation. Even if you don’t define a constructor explicitly, a default constructor is created by compiler. Constructor seems like methods be they don’t have a return type. Constructor’s name must be same as its class name.
Car(){} -> constructor
void Car(){}->not a constructor.
House(String address){} -> constructors could have arguments.
public House(){} -> access modifiers.
Array Declarations
int [] x; -> valid, recommended.
int x[]; -> valid, not readable.
int [] x = new int[5] -> initialize array.
int [] x = {1,2,3,4,5} -> valid.
int [] x = new int[]{1,2,3,4,5};
int[][][] x; -> multi dimensional array.
int[][][] x = new int[2][3][4]; -> multi dimensional array
Transient Variables
If you mark a variable transient, it is skipped while serialization.
Enums
enum Car {AUDI,MERCEDES,FORD,BMW}; -> semicolon optional
Semicolon is optional at the end of enum definitions.
You can not define enums inside of methods.
Declaring Constructor,Method and Variables in Enums
enum Car { AUDI(250),MERCEDES(300),BMW(350); private int maxSpeed = 0; Car(int maxSpeed){ this.maxSpeed = maxSpeed; } public int getMaxSpeed(){ return maxSpeed; } } |
You cannot call an enum constructor directly.
You can define more than one argument in constructor.
You can overload enum constructors.
And you can override enum methods for each enumerated value.
enum Car { AUDI(250), MERCEDES(300), BMW(350), FERRARI(400){ public String getCountry(){ return "Italy"; } }; private int maxSpeed = 0; Car(int maxSpeed){ this.maxSpeed = maxSpeed; } public int getMaxSpeed(){ return maxSpeed; } public String getCountry(){ return "Germany"; } } |