java syntax
Basic conception
First, every line of the code must be in the class.
Second, a java file can have more than one class. However, there can only be one public class per java file and the name of public class must be the same name as its file name.
Variables
A class can contain any of the following variable types.
- Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
- Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
- Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.
float
The
floatdata type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value with an “f”.static
In the example above, we created a
staticmethod, which means that it can be accessed without creating an object of the class, unlikepublic, which can only be accessed by objects.This instance method cannot override the static method from A
1
2
3
4
5
6
7
8
9
10
11
12class A{
static int m;
static void f() {
m=20;
}
}
class B extends A{
void f() { //wrong
m=222;
}
}
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to objects.
- Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for
String). - Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
- A primitive type has always a value, while non-primitive types can be
null. - A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
- The size of a primitive type depends on the data type, while non-primitive types have all the same size.
- Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for
Type Casting
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger type size
byte->short->char->int->long->float->doubleNarrowing Casting (manually) - converting a larger type to a smaller size type
double->float->long->int->char->short->byte
1
2
3
4float n=1.1f;
double m =1.1;
m=n; //Widening Casting(automatically)
n=(float)m; //Narrowing Casting(manually)special character
The backslash (
\) escape character turns special characters into string characters:Escape character Result Description \'‘ Single quote \"“ Double quote \\\ Backslash Loop the Array
1
2
3
4
5
6
7
8for (type variable : arrayname) {
...
}
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}constructor
Note that the constructor name must match the class name, and it cannot have a return type (like
void).Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
Overload the method
After we overloaded a method, there will be two method that have the same name but have the differences that are the numbers or the type of the parameters.
1 | class A{ |
Packages
A package in Java is used to group related classes. Think of it as a folder in a file directory.
We use packages to avoid name conflicts.
1 | import package.name.Class; // Import a single class |
Inheritance
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of the extends keyword, the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
To inherit from a class, use the extends keyword.
We can inherit attributes and methods from one class to another
1 |
|
- If we create a reference variable to the superclass, it can only access the members of the superclass, so to access the members of both classes it is recommend to always create reference variables to the subclass.
Note − A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. (How do we invoke it? we just use the super keyword)
The super keyword
The super keyword is similar to this keyword. Following are the scenarios where the super keyword is used.
It is used to differentiate the members of superclass from the members of subclass, if they have same names.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28class Super_class{
int num=20;
public void display() {
System.out.println("This is the display method of the super class");
}
}
public class Sub_class extends Super_class{
int num=10;
public void display() {
System.out.println("This is the display method of the sub class");
}
public void method() {
Sub_class sub=new Sub_class();
sub.display();
super.display();
System.out.println("value of the variable named num in sub class: "+num);
System.out.println("value of the variable named num in super class: "+ super.num);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Sub_class obj=new Sub_class();
obj.method();
}
}It is used to invoke the superclass constructor from subclass.
If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword
As the following example, we use
super(val)to call the parameterized constructor.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class SuperClass {
int age;
SuperClass(int age){
this.age=age;
}
public void getAge() {
System.out.println("The value of varible named age in the super class name is "+ age);
}
}
public class SubClass extends SuperClass{
SubClass(int age) {
super(age);
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SubClass s=new SubClass(19);
s.getAge();
}
}
instanceof
Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal.
(obj name) instanceof (class name)
1 | interface Animal{ |
Output
1 | true |
Override the method
After we override, the method in the subclass covers the method in the superclass that has the same name. Note that the method in the subclass must have the same name, the same numbers and same type of parameters as the superclass.
1 | class A{ |
Even though b is a type of Animal it runs the move method in the Dog class
In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.
As an example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class T {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}If we call the method only exists in the Animal but not in the Dog, the error will occur. This program will throw a compile time error since b’s reference type Animal doesn’t have a method by the name of bark.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29package a;
class Animal{
public void move() {
System.out.println("The animals move");
}
}
class Dog extends Animal{
public void move() {
System.out.println("The dog moves");
}
public void bark() {
System.out.println("The dog barks");
}
}
public class TestDog {
public static void main(String[] args) {
// TODO Auto-generated method stub
Animal d=new Dog(); // Animal reference but Dog object
d.move(); //output: The dog moves
d.bark(); //error
}
}
Certainly, it is possible to invoke the method that has been overridden. Just use the super keyword
1 | class Dog extends Animal{ |
Output
1 | The animals move |
Polymorphism
Polymorphism in Java is a concept by which we can perform a single action in different ways.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.
runtime polymorphism
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30class Animal{
void cry() {
}
}
class Dog extends Animal{
void cry() {
System.out.println("wang wang");
}
}
class Cat extends Animal{
void cry() {
System.out.println("miao miao");
}
}
public class E {
public static void main(String[] args) {
Animal a;
a =new Dog();
a.cry();
a=new Cat();
a.cry();
}
}output
1
2wang wang
miao miao
Inner Classes
To access the inner class, create an object of the outer class, and then create an object of the inner class.
1 | class OuterClass{ |
Abstract
Abstract class
Abstraction can be achieved with either abstract classes or interface.
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
1 | //abstract class |
Interface
An interface is a completely “abstract class“ that is used to group related methods with empty bodies. There are not variables in the interface only constants.
To access the interface methods, the interface must be “implemented” by another class with the implements keyword (instead of extends).The body of the interface method is provided by the “implement” class:
1 | interface A{ |
1 | interface Animal{ |
Multiple Interfaces
To implement multiple Interfaces, separate them with a comma:
1 |
|
Inner Class
Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.
1 | class Outer_Demo{ |
To instantiate a inner class, initially we have to instantiate the outer class.
We need to instantiate inside the outer class and new the object inside the outer object.
1 | Outer_Demo outer = new Outer_Demo(); |
File Handing
Create a file
The File class from the java.io package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory name:
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):
1 | import java.io.*; |
Write to a file
In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. If the file isn’t exists, it will be created.
Note that when you are done writing to the file, you should close it with the close() method:
1 | try { |
Read Files
In the following example, we use the Scanner class to read the contents of the text file we created,
After we read the file, we should close the reader myReader.close();
1 | try { |
Delete Files
To delete a file in Java, use the delete() method:
1 | File myObj=new File("Filename.txt"); |
Java Exceptions
When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
1 | public class Excpetions { |
