You are on page 1of 39

INTRODUCTION TO JAVA

History of Java

 Java, having been developed in  1991, is a relatively new


programming language.   At that time, James Gosling from
Sun Microsystems and his team began designing the first
version of Java aimed at programming home appliances which
are controlled by a wide variety of computer processors.
     Gosling's new language needed to be accessible by a variety
of computer processors.  In 1994, he realized that such a
language would be ideal for use with web browsers and Java's
connection to the internet began.  In 1995, Netscape
Incorporated released its latest version of the Netscape
browser which was capable of running Java programs.
Object-Oriented

OO is ubiquitous!
 Lots of commercially produced code in C++ (and Java,
Smalltalk, etc.)
Focus on data, not procedures
Encapsulates data and functions
More “natural”
Exploits inheritance
(Almost) Everything in Java is an object!
First Java Program: Hello, World!

// This is a comment
// The file is named HelloWorld.java
public class HelloWorld {
public static void main(String args[]) {
System.out.println(“Hello World!”);
}
}
Note: If the class is public, the name of the class
(i.e., HelloWorld) must be the same as the name of
the file plus the .java extension (i.e.,
HelloWorld.java)
println explained

What exactly is System.out.println(“...”)?

System is a class.
It has a class variable named out.
out refers to an object of type PrintStream.
PrintStream objects have an instance method
named println.
Java: The Programming Language
How to Compile and Run

Compile a source code file by typing


javac <filename>.java (e.g., javac HelloWorld.java)

 If no compile-time error appears, a .class file is produced.

Run an application by typing

java <class name> (e.g., java HelloWorld)

Not java HelloWorld.class


Features Similar to C/C++’s

Same comment styles


 new: /** to be processed by javadoc … */
Same literals and data types
 new: true and false for the boolean data type
 new: strings not null terminated, not mutable
 new: numeric sizes and their machine independence
Same operators
Same control structures
Java’s Basic Constructs

Comments
 // comment on one line
 /* comment on one or more lines */
 /** documenting comments */
Statements
 int x; // statement ends with a semicolon (;)
 x = 1 + 2;
Primitive Data Types

There are 8 primitive data types in Java


 All the numeric types (integer and floating point types) are
signed (meaning they can be positive or negative). No
unsigned numeric types in Java (unlike C/C++).
Three categories of data types:
 Primitive data types
 Class data types (coming later)
 Interface data types (coming later)
Basic Data Types

Integers Floats

 byte (8 bits)
 float (32 bits)
 short (16 bits)
 double (64 bits)
Boolean
 int (32 bits)
 long (64 bits)  boolean (1 bit)
Characters
 char (16 bits Unicode) Strings
 String (an example of class
data type)
Primitive data types
capital case (because it is a class, not a primitive)
Identifiers and Literals

Identifiers
 case sensitive
 have no maximum length
 start with a letter, underscore, or dollar sign
 e.g., user_name, _file, $money
Literals
 numeric: 2 (int), 3L (long), 2.0f (float) 3.14 (double), 077
(octal), 0xDC (hex)
 character: ‘a’, ‘t’
 boolean: true, false
 string: “hello”

Watch out for these!


Booleans

Has value true or false (different from numeric type)


Returned by relational operators
Required for conditional statements
E.g.,
 // if x is an int
 C/C++: if (x) { ...} // OK in C/C++, not OK in Java
 Java: if (x == 1) { ...}
Strings

String is a “built-in” class provided by Java


 e.g., String s1 = “Hi there!”;
The ‘+’ operator is used for String concatenation
 e.g., String s1 = “abc”;
 String s2 = s1 + “ ” + s1;
String objects represent constant strings (content
cannot be altered)
Many methods supported in the String class.
Operators

Partial list (in order of precedence):


 ++, -- ++ (Preincrement, Postincrement) // increments a variable by 1
e.g., x = 1; System.out.println(x++); // displays 1
 !, (type) System.out.println(x); // displays 2
e.g., x = 1; System.out.println(++x); // displays 2
 *, /, % System.out.println(x); // displays 2
-- (Predecrement, Postdecrement) // decrements a variable by 1
 +, - e.g., x = 1; System.out.println(x--); // displays 1
System.out.println(x); // displays 0
 <, >, <=, >=, instanceof e.g., x = 1; System.out.println(--x); // displays 0
System.out.println(x); // displays 0
 ==, != (equal to and not equal to operators, respectively)
 && (this is the logical AND operator)
 || (this is the logical OR operator)
 =, *=, /=, +=, ...
Looping Structures
Syntax (for):

for (initial expr; boolean expr; update expr) {


  
statements;
}

Example:
for (int k = 0; k < 10; k++)
{
System.out.println(k);
}
Arrays

 Arrays are objects


 Like C/C++, subscripts start from 0
 No pointers in Java => no pointer arithmetic
 To create an array,
 use “new”
 e.g., int a[] = new int[5]; // creates an array of 5 ints
 same as: int [] a = new int[5];
 or array initializer
 int a[] = {1, 2, 3, 4, 5};
 To access an array element, use a[i] where 0 <= i <
arraySize
 Array boundaries are checked at runtime
Arrays (cont’d)

The following will throw an exception (can be


caught and handled)
 e.g., int a[] = new int[5];

a[5] = 123; // array out of bound exception


Can use length to determine array size
 e.g., public void doSomething ( int a[] ) {

for (int i = 0; i < a.length; i++)


a[i] = 0;
}
Passing an int array into a method
Object-Oriented Programming
with Java
Classes

A class is a template (i.e., blueprint) for creating


objects
A class extends another class (inheritance
relationship)
 e.g., public class className extends superclassName {
...
}
By default, all classes are derived from a single root
class called Object
All classes except Object have one immediate
superclass
Classes (2)

// Student.java
public class Student {
private String name; // name is a field, attribute, or an instance variable
public Student(String n) { // This is a constructor. Note that it has the
name = n; // same name as the class name. More on this later.
}
public void setName (String n) {
name = n; The getter and setter methods. Typically, get
} and set methods are defined for each field.
public String getName () { If a field is named, say, workAddr, then a get
return name; method named getWorkAddr() and a set method
} named setWorkAddr(…) are created.
public void print () {
System.out.println(“Name is “+name);
}
}
Classes (3)

// TestStudent.java (a dummy class to test the functionality of the Student


class)
public class TestStudent {
public static void main (String argv[]) {
Student s1 = new Student("Lee");
Student s2 = new Student("John");
s2.setName("John Jr.");
s1.print();
System.out.println(s2.getName()); // can also use print() here
}
}

 Note: The Student and TestStudent classes need to be in the same


directory for the above to work properly.
Objects

Objects/instances of classes are created using “new”


 e.g., Student s = new Student(“John”);
A variable of non-primitive type actually holds
“handle” for the actual object. It is called an object
reference.
Assigning objects copies the handle, not the object.
Objects (3)

Example:
Student s1; // s1 has the value null
s1 = new Student(“A”); s1
s1 = new Student(“B”); A

s1
A
A will be garbage collected

s1 = null; // what is the effect of this?


Methods

Methods
 defined the behaviors of a class (called member
functions in C++)
 can only be implemented in classes (no standalone
code)
 must have a return type unless they are constructors
(which have no return type)
 must have a comma separated list of pairs of parameter
types and names (if takes no parameter, the list is
empty)
Method Definition

Syntax: optional
[accessType] [modifier(s)] returnType methodName (parameter list) {
… // method body
}
Examples:
public static void main(String[] args) {

}
private int myMethod(int j, String s) {

}
String myMethod2( ) {

}
Constructors

Special methods that have the same names as their


classes
Are invoked during the creation of an object by “new”
Constructors do not have a return type
Constructors (and methods in general) can be
overloaded by varying the number of types of
parameters
Constructors (2)

Default constructor
 A default constructor is automatically provided for you in every
class
 Format: public MyClass() { // assume class name is MyClass
}
 Allows you to do:
MyClass mc = new MyClass( );
 Will be invalidated if you add a constructor declaration with
arguments
Access Specifiers

As with C++, components of classes can have


associated access specifiers
 public Accessible by all
 protected Only accessible from this class, its
subclasses, and package.
 private Only accessible from this class
 “friendly” Accessible from the package; Default
access (no specific declaration)
Access Specifiers (2)

Accessibility Criteria

Modifier Same Class Same Package Subclass All


public Yes Yes Yes Yes
protected Yes Yes Yes
Default Yes Yes
private Yes
Access Specifiers (3)

Examine the classes Employee.java and


TestAccess.java in your source disk.
Compile the class TestAccess.java and observe the
output. (Should see an error message.)
Now change the name and salary fields to public
and re-compile and run TestAccess.java.
Lesson: Keep instance variables/fields private!
Access Specifiers (3)

Examine the classes Employee.java and


TestAccess.java in your source disk.
Compile the class TestAccess.java and observe the
output. (Should see an error message.)
Now change the name and salary fields to public
and re-compile and run TestAccess.java.
Lesson: Keep instance variables/fields private!
Inheritance (1)

Fields: Methods:
Superclass All the fields and
f1, f2, and f3 m1,m2, m3, m4, m5, and m6 methods are inherited
by the subclass

Fields: Methods: A subclass may add


additional fields (f4-
f4 and f5 Subclass m6,m7, m8, and m9 f5) and/or methods
(m7-m9) and/or
override an existing
one (m6)

An object of Superclass: An object of Subclass:

Has 3 “slots” and understand Has 5 “slots” and understand


messages m1-m6 messages m1-m5, m6 (as defined
in the subclass) and m7-m9
Inheritance (2)

// Person.java // Student2.java
public class Person { public class Student2 extends Person {
private String name; private float gpa;
public Person (String n) { public Student2 (String n, float g) {
name = n; super (n); // calls superclass constructor
} gpa = g;
public void setName (String n) { }
name = n; public void setGpa (float g) {
} gpa = g;
public String getName () { }
return name; public float getGpa () {
} return gpa;
}
public void print () {
public void print () { // overriding
System.out.println(“Name is super.print(); // calls superclass print()
“+name); System.out.println("gpa is” +gpa);
} }
} }
Overriding vs. Overloading

Overriding
 Subclass can specialize the methods of the superclass by changing
the operation of a method declared by the superclass without
changing the interface.
 Overridden method can be invoked using super
 Same method name, same parameter list, same return type,
different body
Overloading
 A class can enhance its functionality by providing a means for the
user to call a method with a different number of arguments or type.
 Same method name, same or different return type, different
parameter list, different body
Overloading: Example

class Person { public class TestPerson {


private String name;
public static void main (String argv[]) {
// overloaded constructor with no
parameter Person p1 = new Person();
public Person () { p1.print();
name = “ ”; Person p2 = new Person(“John”);
}
p2.print();
// overloaded constructor with 1
parameter }
public Person (String n) { }
name = n;
}
public void setName (String n) { … }
public String getName () { … }
public void print () { … }
}
Polymorphism

In Greek it means “many forms”


In OO/Java it means
 “one interface, multiple implementations” (e.g., a print
interface with multiple implementations from the Person
and Student classes)
 “One object reference, possibly referring multiple forms of
objects” (e.g., Person x; Here x can be a Person, Student,
etc.)
 Note: an object has only one form but an object reference can be of
multiple forms (we say the object reference variable is
polymorphic).
Interfaces

 Definition (of an interface):


 a collection of method signatures (without implementations, always
public and abstract) and/or constants (always public, static, and final)
that can be added to a class to provide additional behaviors not defined in the
class itself or inherited from its superclasses
 Syntax:
 // To create an interface:
public interface MyInterface [extends Interface1, Interface2, ...] {
// all methods here are defaulted to public and abstract.
// all variables here are defaulted to final, static, and public.
}
 // To use an interface:
public class MyClass implements MyInterface {
// must implements all the methods specified in the interface MyInterface
}

You might also like