Java Programming Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

JAVA Programming

INTRODUCTION TO JAVA PROGRAMMING


Software Engineering
Level: 200
Academic year 2020-2021

Objectives
This course offers an introduction to the Java programming language for students who have had little
background in programming. Toward this goal students will learn how to:
- Write programs using the Java language. Basic topics considered are the following: java program
structure, Java syntax, data types, flow of control, classes, arrays, exception handling, recursion,
Database connectivity (JDBC), Basic Socket Programming and graphical user interfaces (GUIs).
- Compile and execute them under the Sun Microsystems, Inc. Java 2 Platform, Standard Edition, or
other Integrated Development Environments (IDEs) such as NetBeans.

Contents
I. Introduction ........................................................................................................................................................................................... 1
1.1. What is java? .............................................................................................................................................................................. 2
1.2. Java features ............................................................................................................................................................................... 2
1.3. Types of java programs ............................................................................................................................................................. 2
1.4. Java development tools .............................................................................................................................................................. 3
a) The Java Development Kit (JDK) ............................................................................................................................................... 3
b) Java development environments ................................................................................................................................................. 3
II. Basic Java Language Elements ....................................................................................................................................................... 3
2.1. Comments ................................................................................................................................................................................... 3
2.2. Standard primitive types in Java .............................................................................................................................................. 3
2.3. Operators .................................................................................................................................................................................... 3
2.4. Variable declarations ................................................................................................................................................................. 3
2.5. Constants .................................................................................................................................................................................... 3
2.6. Arrays ......................................................................................................................................................................................... 3
2.7. Flow control ................................................................................................................................................................................ 4
2.8. Standard input and output ........................................................................................................................................................ 4
2.9. Java Exception Handling ........................................................................................................................................................... 4
III. Object Oriented Programming (OOP) ........................................................................................................................................... 5
3.1. Classes and objects ..................................................................................................................................................................... 5
3.1.1. Some java OOP terminalogies ........................................................................................................................................ 6
3.1.2. Access modifiers .............................................................................................................................................................. 6
3.2. Inheritance .................................................................................................................................................................................. 6
3.2.1. Constructor Chaining...................................................................................................................................................... 7
3.3. Polymorphism............................................................................................................................................................................. 7
3.4. Abstract Methods And Classes .................................................................................................................................................. 7
3.5. Interfaces .................................................................................................................................................................................... 8
3.5.1. Differences Between Interfaces and Abstract Classes................................................................................................... 8
3.5.2. Why Are Interfaces Important? ..................................................................................................................................... 8
3.6. Packages and import statement ................................................................................................................................................. 8
IV. Files (Tutorial)
V. JDBC (Tutorial)
VI. Basic Socket Programming (Tutorial)
VII. GUI Programming (Tutorial)
I. Introduction

1
JAVA Programming
1.1. What is java? Garbage collection means that there is an automatic
Java is an Object-Oriented Programming Language functionality that regularly goes throughthe object space and
developed by Sun Microsystems, similar to C and C++, checks which objects are still referenced and which are not.
except without some of the confusing, poorly understood Those which are no longer referenced are unusable for the
features of C++ (operator overloading, pointers …). program, so it is safe to liberate the space they use. In Java,
At its first release, Java primarily was used as a there is no “delete” keyword, since a garbage collector in
language for writing applications tobe embedded in the JVM takes care of allocating and reclaiming memory.
browsers (known as applets), but it has grown into many  Several drawbacks of C and C ++ eliminated
other areas (Applications for server and enterprise - No accessible memory pointers, no
computers, desktop computers, mobile phones …). Today, preprocessor.
thousands of programmers, Internet developers, Web - Array limits automatically checked.
publishers, and software houses are making use of Java. - No operator overloading in Java.
Java includes three main platforms:  Multiple inheritance replaced by interfaces
 Java Standard Edition (JSE): for desktop computers (Eliminates complexities of multiple inheritance)
 Java Mobile Edition (JME): it is the Java platform  Object-oriented
for consumer and embedded devices such as mobile - Object-oriented programming (OOP)
phones and personal organizers. throughout – no coding outside of class
 Java Enterprise Edition (JEE):for servers and definitions.
enterprise computers.  Robustness
Java encompasses several distinct components: - Exception handling built-in, strong type
- A high-levellanguage: source code at a glance looks checking (that is, all variables must beassigned
very similar to C and C ++ but is unique in many ways. an explicit data type), local variables must be
(The source file extension is “.java”) initialized.
- Java byte-code: A compiler transforms the Java  Platform independence
language source code to files of binary instructions and - The byte-code runs on any platform with a
data called byte-code that run in the Java Virtual compatible JVM.
Machine. - The “Write Once Run Anywhere” ideal has not
- Java Virtual Machine (JVM): It is a program that been achieved (tuning for differentplatforms
takes byte-code as input and interprets the instructions usually required), but is closer than with other
just as if it were a physical processor executing languages
machine code. The figure below illustrates how a java - Portable: Write Once, Run Anywhere
program is compiled and run. These features provide a number of benefits
compared to program development in other languages. For
example, C/C++ programs are beset by bugs resulting from
direct memory pointers, which are eliminated in Java.
Similarly, the array limit checking prevents another common
source of bugs. The garbage collectorrelieves the
programmer of the big job of memory management. It’s
often saidthat these features lead to a significant speedup in
program development anddebugging compared to working
with C/C ++.
1.3. Types of java programs
 Application: Standalone Java program that can run
1.2. Java features independent of any Web browser
 Compiler/interpreter combination  Applet: Java program that runs within a Java-
The source code is compiled to byte-code, which is enabled Web browser
interpreted by a Java Virtual Machine (JVM).This provides  Servlet: Java software that is loaded into a Web
portability and security to any base operating system server to provide additional server
platform for which a virtual machine has been written. functionalityalike CGI programs. (CGI=Common
 Garbage collection Gateway Interface. It’s a technique that allows a
client to run a specific program on a server)
2
JAVA Programming
1.4. Java development tools *@param width the length of one
*@param height the length
a) The Java Development Kit (JDK)
*@return the area of the rectangle
The Java Development Kit (JDK) is the minimal file */
you need to develop in Java. The version that is meant for
the Windows environment contains an automatic installer 2.2. Standard primitive types in Java
that takes care of the installation. Only setting up the boolean true or false
Windows PATH may require some manual intervention. char 16 bit character, coded using Unicode 1.1.5
The JDK contains many base tools: byte 8 bit signed integer ( -128 to +127)
javac: The Java Language Compiler that used to compile short 16 bit signed integer (-32,768 to 32,767)
programs written in the Java Programming Language into int 32 bit signed integer (-2.15E+9 to +2.15E+9)
byte-codes. long 64 bit signed integer (-4.61E+18 to +4.61E+18)
java: The Java Interpreter used to run programs written in
float floating point real number (1.0E-38 to
Java.
1.0E+38)
jre: The Java Runtime Interpreter that can be used to run
double floating point real number (-1.0E-308 to 1.0E+308)
Java applications. The jre tool is similar to the java tool, but
is intended primarily for end users who do not require all the
2.3. Operators
development-related options available with the java tool.
They are similar to C++ operator. However they are few
appletviewer: It is used to run applets without a web
differences:
browser.
 “+” can be usedto concatenate strings
jar: Combines multiple files into a single Java Archive
 “instanceof” returns true or false depending on
(JAR) file.
whether the left side object is an instance of the
right side object
b) Java development environments
 “>>>” shifts bits right, filling with zeros
There are many java development environments: Netbeans,
2.4. Variable declarations
Eclipse, JBuilder, JDeveloper…
Variable declarations consist of three parts: modifiers,
Example of java program
followed by a type , followed by a list of identifiers. The
o Create source file (on any text editor): Hello.java
modifiers are optional, but the type and list of identifiers is
o Type the code below and save:
not.
public class Hello {
Example :public int a, b, c; // "public" is a modifier
public static void main (String args[]) {
System.out.println("Hello World!");
} 2.5. Constants
} In C++, constants are defined using const or #define. In
java they are defined throught the combination of “final”
o Compile: javac Hello.java
and “static”.
o Run: java Hello (This last command will start up
Syntax: public final <static><datatype><name> =
the JVM)
<value>;
Example: public final static double PI = 3.14;
II. Basic Java Language Elements
public final static int NumStudents = 60;
Java syntax is very close to that of "C" and C++. This
is true for Comments, variable names and declarations and
2.6. Arrays
initialisations, control flow (if, else, for, while) etc.
Arrays are objects in Java .Creating an array involves
three steps: declaration, creation andinitialization
2.1. Comments
o Declaration: int [] tab; or int tab [];
Type of comments Examples
This means that tab is a reference (compare with reference
//Single line comment
Line comment and pointer in "C" and C++) to an array of integers.
int cpt = 1//Counter
o Creation: tab = new tab[4];
/* First line comment
Block comment o Initialization: tab[0] = 12;
Second line comment*/
o Declaration, creation and initialization can be
/**
Automatic documentation combined:
*This subroutine computes the
comment *area of a rectangle int [] tab = {1, 2, 3, 4}

3
JAVA Programming
o Matrices <statements-2> break;
int a[][] = new int [10][3]; break; case 1:
println(a.length); // prints 10 . case 2:
println(a[0].length); // prints 3 . // (more cases) System.out.println("The
. number is 1or 2.");
2.7. Flow control case<constant-N>: break;
 If statement <statements-N> case 3:
Example: break; case 4:
if (x < y && x < z) {//Assume x, y and z are intergers default: // optional System.out.println("The
System.out.println (“followed by y and z in their correct order”); default case number is 3or 4.");
}
<statements-(N+1)> break;
else if (x > y && x > z) {
System.out.println (“output y and z in their correct order, followed by x”);
} // end of switch default:
} statement System.out.println(" N>= 5.");
else { }
System.out.println (“output x in between y and z in their correct order”);
}
2.8. Standard input and output
The global class "System" contains the fields "in","out"
 The for stament and "err", which correspond tostandard input, standard
Syntax Example output and standard error. Using these is illustrated by the
class ForDemo { followingexample:
public static void main(String[]
for (initialization; args){ classStdioExample
termination; increment) { for(int i=1; i<11; i++){ {
<statement(s)> System.out.println("Count is: " + i); public static void main(String args[]) throws IOException{
} } int n;
} BufferedReaderstdin = new BufferedReader(new
} InputStreamReader(System.in));
System.out.print("Enter an integer: ");
 The while and do-while statements n = Integer.parseInt(stdin.readLine());
System.out.println("Square: " + n*n + " Cube: " + n*n*n);
Statement Example
}
class WhileDemo {
}
public static void main(String[] args){
int count = 1;
while (count < 11) {
Data Conversion Functions
While System.out.println("Count is: " + count);
count++; Java contains a robust set of classes to convert from one data
} type to another
} Classes Example of conversion
} Long String str1 = “488890001”;
class DoWhileDemo { long l = Long.parseLon(str1) ; // l=488890001 ;
public static void main(String[] args){ Interger String str2 = “32776”;
int count = 1; int n = Interger.parseIn(str2) ; // n=32776
do { Float String str3 = “12.3”;
Do-while System.out.println("Count is: "+ count); float f = Float.parseFloat(str3); // f=12.3
count++; Double String str4 = “1.5”;
} while (count < 11); double d = Double.parseDouble(str4) ; // d = 1.5
}
Boolean String str5 = “true”
}
Boolean bool = Boolean.parseBoolean(str5); //
bool = true
 Switch
Syntax Example 2.9. Java Exception Handling
switch (<expression>) { switch ( N ) { An exception is an object that defines an unusual or
case <constant-1>: // Assume N is an integer erroneous situation. It is thrown by a program or a runtime
<statements-1> case 0: environment and can be caught and handled appropriately.
break; System.out.println("The Java supports user-defined and predefined exceptions
case<constant-2>: number is 1.");

4
JAVA Programming
(ArithmeticException, ArrayIndexOutOfBoundsException, System.out.println("Level3 ending");
}
FileNotFoundException, InstantiationException).
public void L2 ( ) {
Exception handling allows a programmer to divide a System.out.println("Level2 beginning");
program into a normal execution flow and an exception L3( );
execution flow. If an exception is not handled the program System.out.println("Level2 ending");
}
will terminate (abnormally) and produce a message.
public void L1 ( ) {
Example: System.out.println("Level1 beginning");
public class DivideBy0 { try { L2 ();
public static void main (String[] args) { } catch (ArithmeticException problem) {
System.out.println(problem.getMessage( ));
System.out.println(10 / 0);
System.out.println();
}
problem.printStackTrace ( );
} }
Outpout: System.out.println("Level1 ending");
(Java.lang.ArithmeticException: / by zero }
at DivdeBy0.main(DivdeBy0:3)) }
class Demo {
public static void main (String[] args) {
Try and Catch statements Exception_Scope demo = new Exception_Scope();
System.out.println("Program beginning");
Syntaxe Exemple
demo.L1( );
public class ExceptionExample {
System.out.println("Program ending");
public static void main(String arg []){
}
int n; }
BufferedReader stdin = new [Give the output after running this speudo code]
BufferedReader(new
try { Throwing an Exception
InputStreamReader(System.in));
statement-list1
System.out.println("Enter an integer: "); Example of method solving quadratic equation(A*x*x + B*x + C = 0)
}
try{ static public double root( double A, double B, double C )
catch (exception- throwsIllegalArgumentException {
n = Integer.parseInt(stdin.readLine());
class1 variable1) if (A == 0) {
System.out.println("You enter: "+n); throw new IllegalArgumentException("A can’t be zero.");
{
} }
statement-list2 else {
catch(IOException e1){
} double disc = B*B - 4*A*C;
System.out.println("IOException
catch (exception-
occurs"); if (disc < 0)
class2 variable2)
}
{ throw new IllegalArgumentException("Discriminant <
catch(NumberFormatException e2){
statement-list3 zero.");
System.out.println("You must enter an
} catch ….
interger"); return (-B + Math.sqrt(disc)) / (2*A);
e2.printStackTrace(); Finally clause
} A try statement} may have a finally clause. The finally
} clause defines
} a section of code that is executed regardless
} of how the try block in executed.
try {
If an exception is thrown in statement-list1, control is statement-list1
transferred to the appropriate catch handler.After executing } catch (exception-class1 variable1) {
the statements in the catch clause, control transfers to the statement-list2
….
statement after the entire try statement.
} catch{ statement-listN}
} finally {
Exception Propagation statement-list //Always execute this code.
If an exception is not caught and handled where it }
occurs, it propagates to the calling method.
Exemple III. Object Oriented concepts and JAVA
class Exception_Scope {
3.1.1. Classes and objects
public void L3 ( ) {
System.out.println("Level3 beginning");
System.out.println(10/0);

5
JAVA Programming
A class is a collection of data (attributes) and methods - Private:
that operate onthat data.“In Java, everything is a class”( that This modifier indicates that attributs and methods are
is classes provided by java and those that you write). accessible only from within the class where they are
 All classes are derived from a single rootclass declared.It is used for the internal operations of the
called Object. object. This is called encapsulation in OOP.
 Every class (except Object) has exactly one - Protected:
immediate super class. When protected is applied as an access modifier to a
 Only single inheritance is supported member in a class, that member can be used in
Objects are instances of a class. They are created with the subclasses of the class in which it is defined, but it
“new” keyword, which returns a reference to an object that cannot be used in non-subclasses. There is an exception:
represents an instance of the class. A protected member can also be accessed by any class
in the same package as the class that contains the
3.1.2. Some java OOP terminalogies protected member.
- Member: either an attribute or a method of a class - Unspecified:
- Constructor: method that performs object If none of modifiers given above are used, the
initialization (not creation!) memberhas the default visibility or "package"visibility.
- Object Reference: variable that holds a reference to
(really the memory address of) an object
- Instance Variable: attribute for which each object
(instance) has its own copy
- Class Variable: attribute for which there is only
one copy for the class. Each object (instance) 3.2. Inheritance
shares this copy. It is also called static variable The terminheritance refers to the fact that one class can
- Instance Method: method which operates on the inherit part or all of its structure and behavior from another
attributes of an object (instance) class(This mecanism ensures scalability and re-usability of
- Class Method: method which does not operate on a the code). Java supports single inheritance using the
particular object, but performs some utility function “extends” keyword as follow: public class B extends
or operates on static variables. it is also called A.Here,“A” is called the subclass and “B” the superclass.
static method. • A subclass can override a method in its superclass by
- Method Signature: the number, type and order of providing anew definition for a method with the same name,
arguments of a method return type andsignature.
- Method Overloading: defining a method with the • All classes implicitly extend the Object class.
same name but different signature(number and type • A protected member of a class can be accessed by any
of parameter) as another method in the same class method in the same class or a subclass. (It can also be
Method overloading
access by any method in a class in the same package)
class Adder • Inside a method, the keyword “this” represents the
{
current object, while “super” is a variable that contains a
int add(int i, int j) {
return i + j; reference of the current object’s super class.
} Inheritance example
double add(double i, double j) { // A is the superclass public class ABTest {
return i + j; public class A { public static void
} protected int aData; main(String[] argv) {
} public A(int aData) //Polymorphism
{this.aData =aData;} A a = new A();
B b = new B();
3.1.3. Access modifiers public A() {aData = 0;}
a.f(); // Invokes A's f()
There are three access modifiers which can define the protected void f() { b.f();// Invokes B's f()
System.out.println("This is A's A a1 = b;
visibility of attributs, methods and classes: public, private, f"); a1.f(); // Invokes B's f()
protected. } // Up Casting
} A a2 = (A) b; // Ok
- Public: // B is the subclass
It indicates that a member or class is accessible public class B extends A { // Down Casting
protected int bData; //B b1 = a; // Illegal at
anywhere by anyone.(In the philophdy of OOP, attributs public B(int bData) //compile time,
{this.bData = bData;} // explicit cast needed
should not be declared public. It is preferable to use //B b2 = (B) a; // Ok at
public B() {this(0);}
“getter” and “setter”) protected void f() { //compile time,

6
JAVA Programming
System.out.println("This is B's // exception at run time on the object that it is acting upon. The three types of
f"); // Other stuff
} int i = a.aData; /* Ok, same polymorphism are: method overloading, method overriding,
protected void g() { package*/ and dynamic method binding.
System.out.println("This is B's //i = a.bData; /* Illegal at
g"); compile time */ Overloaded methods are methods with the same name
} //bData not defined in A
} //a.g(); but either a different number of parameters or different types
// Illegal at compile time, in the parameter list.
// g() not found in A
} Overridden methods are methods that are redefined
}
within an inherited or subclass. They have the same
signature and the subclass definition is used.
3.2.1. Constructor Chaining
Dynamic (or late) methodbinding is the ability of a
Java always invokes a superclass constructor when a
program to resolve references to subclass methods at
subclass object is created (since the superclass object is
runtime. An example of dynamic binding is given below.
“part of” the subclass object). It is possible to explicitly call
public class Poly
a superclass constructor using a call to super(…) as the first { public static void main (String
line of a subclass constructor: args[])
{
public B(int bData) {
System.out.println(“First Test”);
super(); // Explicit call of superclass constructor class Point
Point p = new Point (3, 5) ;
this.bData = bData; {
p. display() ;
} public Point (int x, int y)
// calls display() of Point
{
Pointcol pc = new
this.x = x ; this.y = y ;
Pointcol (4, 8, (byte)2) ;
If the superclass constructor isn’t explicitly invoked, }
p = pc ; // p references an
then the no-arguments superclass constructor is implicitly public void move(int dx, int
// instance of Pointcol
dy)
called for you. That is, Java inserts the call to "super()" p. display() ;
{
automatically. // calls display() of Pointcol
x += dx ; y += dy ;
p = new Point (5, 7) ;
But, if the superclass constructors is defined while the }
// p now references an
no-argument one is not given, then it is necessary to call public void display()
//instance of Point
{
the superclass constructor in the first line of the subclass p.display() ;
System.out.println("my
constructor. // calls display() of Point
position is " + x + " " + y) ;
System.out.println(“Second Test”);
Superclass display Subclass }
class Pointcol extends Point Point [] tabPts = new Point [4] ;
class Point private int x, y ;
{ tabPts [0] = new Point (0, 2) ;
{ public Point (int x, int y) }
public Pointcol (int x, int y, tabPts [1] = new
{
byte color) Pointcol (1, 5, (byte)3) ;
this.x = x ; this.y = y ; class Pointcol extends Point
{ super (x, y) ; // must be the tabPts [2] = new
} {
//first Pointcol (2, 8, (byte)9) ;
public void move(int dx, int dy) public Pointcol (int x, int y,
instruction tabPts [3] = new Point (1, 2) ;
{ x += dx ; y += dy ; byte color)
this.color = color ; for (int i=0 ;
} {
} i< tabPts.length ; i++)
public void display() super (x, y) ; /* must be the
public void display() tabPts[i].display() ;
{ System.out.println (" first instruction*/
{ super. display() ; }
my position is " + x + " " + y) this.color = color ;
System.out.println ("and my }
; }
color is: " + color) ; Output
} public void display()
} First Test
private int x, y ; {
private byte color ; my position is 3 5
} super. display() ;
} my position is 4 8
System.out.print ("and my
However, If the first line of a constructor uses the and my color is: 2
color is: " + color) ;
my position is 5 7
"this(…)" syntax to invoke another constructor of the class, }
Second Test
then Java does not automatically insert the call to "super()" private byte color ;
my position is 0 2
}
in the constructor: my position is 1 5
public B() { and my color is: 3
this(0); // Call to super() not automatically inserted here. my position is 2 8
} and my color is: 9
my position is 1 2
3.3. Polymorphism
In programming languages, polymorphism is the 3.4. Abstract Methods And Classes
capability of an action or method to perform an action based

7
JAVA Programming
An abstract method has no body. It is like a pure virtual 3.5.2. Why Are Interfaces Important?
function in C++. The abstract method is expected to be An object's type essentially refers to the OO
overridden in a subclass with an actual implementation. interface of its class. Then in Java, an object of a class that
Any class with an abstract method is an abstract class implements several interfaces has many types. Also, objects
and must be declared abstract. An abstract class can not be from many different classes can have the same type. This
instantiated. Also, if a subclass of an abstract class does not allows to write methods that can work on objects from many
provide implementations for all of the abstract methods of different classes which can even be in different inheritance
its superclass, then the subclass itself is abstract. hierarchies.

// Class Shape is an abstract base class for a geometric shape.


public abstract class Shape {
public abstract double area(); //area() has no body
} public void renderScreen(Drawable d) {
// Class Rectangle is a concrete implementation of a Shape. // Render this Drawable on the screen.
public class Rectangle extends Shape { // It does not matter whether this is DrawableRectangle,
protected double w;
// DrawableCircle, etc. Since the object is a Drawable, it
protected double h;
public Rectangle(double w, double h) { // MUST implement the Draw method.
this.w = w; d.Draw();
this.h = h; } Packages and import statement
} 3.6.
public double area() { return (w * h); } Java classes can be grouped together into a package.
}
Packages have several advantages:
- related classes can be grouped together (implies
3.5. Interfaces modularity)
In Java, an interface is a specification of a set of - members can be accessible only to methods of
abstract methods. classes in the same package
 A class that implements the interface must provide Rules
an implementation for all of the abstract methods in - The package statement must appear as the first
the interface. statement of theJava source file:
 A class can implement many interfaces, but a packagein3;
class can only extend one class (If no package statement is present, the code is made part of
// Interface Drawable provides the specification for a drawable theunnamed default package)
// graphics object.
public interface Drawable {
public void Draw(); - A fully qualified Java name for a class is:
} <Package Name>.<Class Name>
// Class DrawableRectangle implements the Drawable interface.
public class DrawableRectangle extends Rectangle implements Drawable {
Example:in3.Polymorphism.Point
// Other code here.
public void Draw() {
The import statement allows the use of abbreviated
// Body of Draw()
} class names in a Java source file
} Classes are always available via their fully-qualified names:
in3.Polymorphism.Point p = new in3.Polymorphism.Point();
3.5.1. Differences Between Interfaces and By using the “import” statement, the previous code is
Abstract Classes abbreviated as follow:
- An abstract class can have non-abstract methods, in3.Polymorphism.Point;
while all methods of an interface are implicitly (or Point p = new Point();
explicitly) abstract. It is possible to import all of the classes of a package using
- An abstract class can declare instance variables; an the following form of the import statement:
interface can not import java.util.*;
- An abstract class can have a user-defined (This imports all of the classes in the java.util package)
constructor, while an interface has no constructors
- Every method of an interface is implicitly (or
explicitly) public; an abstract class can have non-
public methods.

You might also like