This is not the document you are looking for? Use the search form below to find more!

Report home > Computer / Internet

Java

2.33 (6 votes)
Document Description
This handout introduces the basics of Java, OOP style, classes, objects, messages, methods, constructors, and "this", arrays, static, and collections. See also, the many Java links off the course page.
File Details
Submitter
  • Username: feli
  • Name: feli
  • Documents: 15
Embed Code:

Add New Comment




Showing 1 comment

by mea on July 15th, 2010 at 02:56 am
i really like to make some programs using java but its not easy
hope you give me some example in stack!!!
Related Documents

Java 3D Programming

by: dutcher, 352 pages

Java 3D is a client-side Java application programming interface (API) developed at Sun Microsystems for rendering interactive 3D graphics using Java. Using Java 3D you will be able to develop richly ...

Essentials of the Java Programming Language

by: dutcher, 137 pages

Programming a computer is both a creative activity and a process structured by rules. Computers are programmed or given instruction, through the use of programming languages, so to program a ...

Programming in Java

by: dutcher, 375 pages

Java includes a huge number of built-in classes and interfaces. The programmer can use already existing class as is, create subclasses to modify existing classes, or implement interfaces to augment ...

Java Lecture 1

by: feli, 9 pages

Java Lecture 1 History and Overview Some Basics Running J++ as an Application Running J++ as an Applet

A Quick, Painless Introduction to the Java Programming Language

by: feli, 22 pages

Contents Why All This Hype over Java? Learning Java A 30-Minute Example Exception Handling in Java I/O in Java Strings in Java Debugging Java Programs ...

Introduction to Java programming

by: feli, 69 pages

Skill Level: Introductory The goal of this tutorial is to introduce you to the Java syntax you're most likely to encounter professionally, and to expose you to idioms that will help you avoid ...

Java for Python Programmers

by: feli, 37 pages

This short ebook is an ongoing project to help Computer Science students who have had one or two semesters of Python learn the Java programming language. If you are not a part of that audience you ...

Java vs. C/C++ - Efficiency and Speed Differences

by: jjbladester, 3 pages

Comparing Java vs. C/C++ Efficiency Differences to Interpersonal Differences

Java

by: bckurera, 13 pages

his is about the basics of java installation to running.

The Java Generic Programming System

by: bizmana, 14 pages

In this paper, we explore how to implement support for generic programming in Java using a combination of the compile time type system, the runtime type system, and the reflection features of Java ...

Content Preview
CS193i, Stanford University
Handout #20
Spring, 2004
Ron B. Yeh
Java
This handout introduces the basics of Java, OOP style, classes, objects, messages, methods,
constructors, and “this”, arrays, static, and collections. See also, the many Java links off the
course page.
Java – All The Modern Buzzwords
Java brings together a bunch of excellent computer language ideas, and as a result it is
fantastically popular. From the original Sun Java whitepaper: “Java is a simple, object-oriented,
distributed, interpreted, robust, secure, architecture-neutral, portable, high performance, multi-
threaded, and dynamic language.” By law, any introductory Java lecture must mention the
original buzzwords.
Simple
Simpler than C++ – no operator overloading
Mimics C/C++ syntax, operators, etc. where possible
To the programmer, Java's garbage collector (GC) memory model is much simpler than C/C++.
On the other hand, the libraries that accompany Java are not simple – they are enormous. But
you can ignore them when you don't want to use them.
Object-Oriented
Java is fundamentally based on the OOP notions of classes and objects
Java uses a formal OOP type system that must be obeyed at compile-time and run-time. This is
helpful for larger projects, where the structure helps keep the various parts consistent. Contrast to
Perl, which has more of a quick-n-dirty feel.
Distributed / Network Oriented
Java is network friendly – both in its portable, threaded nature, and because common networking
operations are built-in to the Java libraries. This will make our homeworks much simpler (than if
we had decided to use C++).
Robust / Secure / Safe
Java is very robust – both vs. unintentional memory errors and vs. malicious code such as
viruses. Java makes a tradeoff of robustness vs. performance.
1. The JVM uses a verifier on each class at runtime to verify that it has the correct structure
2. The JVM checks certain runtime operations, such as pointer and array access, to make
sure they are touching only the memory they should. Memory is managed automatically
by the garbage collector (GC). This prevents the common “buffer overflow” security
problems suffered by C++ code. This also makes it easy to find many common bugs,
since they are caught by the runtime checker.
3. The Security Manager can check which operations a particular piece of code is allowed to
do at runtime

2
Architecture Neutral / Portable
Java is designed to “Write Once Run Anywhere”, and for the most part this works. Not even a
recompile is required – a Java executable can work, without change, on any Java enabled
platform.
High-performance
Java performance has gotten a lot better with aggressive just-in-time-compiler (JIT) techniques
(the HotSpot project). Java performance is often similar to the speed of C , and is faster than C in
some cases. However memory use and startup time are both significantly worse than C.
Multi-Threaded
Java has a notion of concurrency (running multiple programs or threads of execution at the same
time) wired right in to the language itself. This works out more cleanly than languages where
concurrency is bolted on after the fact.
Dynamic
Class and type information is kept around at runtime. This enables runtime loading and
inspection of code in a very flexible way.
Java Compiler & Runtime
Java Compiler Structure
The source code for each class is in a .java file. Compile each class to produce a .class file.
Sometimes, multiple .class files are packaged together in a .zip or .jar file. On unix, the java
compiler is called “javac”. To compile all the .java files in a directory use "javac *.java".
Bytecode
A compiled class stored in a .class files or .jar file
Represent a computation in a portable way – as PDF is to text and images
Java Virtual Machine (JVM)
Loads and runs the bytecode for a program + the library classes
The JVM runs the code with the various robustness/safety checks in place -robustness vs.
performance tradeoff
On Unix, the JVM is called "java". Suppose there is a class MyClass with a main() in it. Run that
main with “java MyClass”.
JITs and Hotspot
Just In Time compiler – the JVM may compile the bytecode to native code at runtime (with the
robustness checks still in). (This is one reason why Java programs have slow startup times.) The
"hotspot" project tries to do a sophisticated job of which parts of the program to compile. In
some cases, hotspot can do a better job of optimization than a C++ compiler, since hotpsot is
playing with the code at runtime and so has more information. Java performance is now similar
to C performance – faster in some cases, slower in others. Memory use and startup time are
worse than C.

3
Java Lang + Its Libraries
The core Java language is not that big
However, it is packaged with an enormous number of standard "library" or "off the shelf" classes
that solve common problems for you
e.g. String, ArrayList, HashMap, StringTokenizer, HTTPConnection, Date, ...
Java programmers are more productive in part because they have access to a large set of
standard, well documented library classes.
Java: Programmer Efficient
Faster Development
IMHO, building an application in Java takes about 30% less time than in C or C++
Faster time to market
Java is said to be "programmer efficient"
OOP
Java is thoroughly OOP
Robust memory system
Memory errors largely disappear because of the safe pointers and garbage collector. I
suspect the lack of memory errors accounts for much of the increased programmer
productivity.
Libraries
Code re-use at last – String, ArrayList, Date, ... available and documented
in a standard way
Microsoft vs. Java
Microsoft hates Java, since a Java program is not tied to any particular operating system. If Java
is popular, then programs written in Java might promote non-Microsoft operating systems. For
basically the same reason, all the non-Microsoft vendors think Java is a great idea. Microsoft's
C# is very similar to Java, but with some improvements, and some questionable features added
in, and it is not portable in the way Java is. I think C# will be successful in the way that Visual
Basic is: a nice tool to build Microsoft-only software. Microsoft has used its power to try to
derail Java somewhat, but Java remains very popular on its merits.
Java Is For Real
Java has a lot of hype, but much of it is deserved. Java is very well matched for many modern
problems
Using more memory and CPU time but less programmer time is an increasingly
appealing tradeoff.
Robustness and portability can be very useful features
I suspect we will be using some version of the Java language for the next 10 or 20 years.

4
Procedural vs. OOP
Nouns and Verbs
Nouns – data
Verbs – operations
Procedural Structure
C/Pascal/etc. ...
Verb oriented
decomposition around the verbs – dividing the big operation into a series of smaller and
smaller operations.
Nouns/Verb structure is not formal
The programmer can group the verbs and nouns together (ADTs), but it's just a
convention and the compiler does not especially help out.
OOP Structure
Objects
Storage
Objects store state at runtime in the form of instance variables (aka ivars)
Behavior
Objects will also in some sense take an active role. Each object has a set of operations
(aka methods) that it can perform, usually on itself.
Class
Every object belongs to a class that defines its storage and behavior. An object always
remembers its class (in Java).
"Instance" is another word for object – an "instance" of a class.
Anthropomorphic – self-contained
Procedural variables are passive – they just sit there. A procedure is called and it changes
the variable.
Objects are anthropomorphic-- the object has both storage and behavior to operate on that
state.
String example
Could have a couple String objects, each of which stores a sequence of characters. The objects
belong to the String class. The String class defines the storage and operations for the String
objects...
Sending the length() message to a String object...
length()
String Class
“hello”
length() {
……
String
5
}
“hi”
reverse() {
String
……
}

5
Class
Exists once – there is one copy of the class in memory.
Defines the storage and behavior of its objects
Storage
Define the storage that objects of this class will have. "instance variables" – the variables
that each object will use for its own storage. Instance variables are sometimes just called
"ivars".
Behavior
Define the behaviors that objects of this class can execute (usually called “methods”).
String example
The String class defines the storage structure used by all String objects – probably an
array of chars of some sort
The String class also defines the operations that String objects can perform on
themselves: length(), reverse(), ...
Message / Receiver
Suppose we have Student objects, each of which has a current number of units. The message
getUnits() requests the units from a student.
Java syntax:
a.getUnits()
send the "getUnits()" message to the receiver "a"
Receiver
The "receiver" is the object receiving the message. Typically, the operation uses the
receiver's memory.
Method (code)
A “method” is executable code defined in a class.
The objects of a class use the methods defined in their class.
The String class defines the code for length() and reverse() methods. The methods are run by
sending the "length()" or "reverse()" message to a String object.
Message ‡ Method resolution
Suppose a message is sent to an object – x.reverse();
1. The receiver, x, is of some class – suppose x is of the String class
2. Look in that class of the receiver for a matching reverse() method (code)
3. Execute that code “against” the receiver – using its memory (instance variables)
In Java this is “dynamic” – the message/method resolution uses the true, runtime class of the
receiver.

6
OOP Design – Anthropomorphic, Modular
1. Objects responsible for their own state – as much as possible, object's do not reach in to
read or write the state of other objects.
2. Objects can send messages to each other – requests
3. The object/message paradigm makes the program more modular internally. Each class
deals with its own implementation details, but can be largely independent of the details of
the other classes. They just exchange messages.
OOP Design Rule #1 – Encapsulation
Objects “protect” their own state from direct access by other objects – "encapsulation". Other
objects can send requests, but only the receiver actually changes its own state. This allows more
reliable software – once a class is correct and debugged, putting it in a new context should not
create new bugs.
Abstraction vs. Implementation
This is the old Abstract Data Type (ADT) style of separating the abstraction from the
implementation, but structured as messages (abstraction) vs. methods (implementation)
OOP Design Process
Think about the objects that make up an application
Think about the behaviors or capabilities (code) those objects should have
Endow the objects with those abilities as methods – the code is in the class that contains the data
it uses.
If a capability does not occur to you in the initial design, that's OK. Add it to the appropriate
class when needed – it's most important that the code is defined in the appropriate class.
Co-operation
Objects send each other messages to co-operate
Tidy style
Experience shows that having each object operate on its own state is a pretty intuitive and
modular way to organize things.

7
Student Java Example
As a first example of a java class, we'll look at a simple "Student" class. Each Student object
stores an integer number of units and responds to messages like getUnits() and getStress(). The
stress of a student is defined to be units * 10.
Implementation vs. Interface
In OOP, every class has two sides...
1. The implementation of the class – the data structures and code that implement its
features.
2. The public interface that the class exposes for use by other classes. With a good OOP
design, the interface is smaller and simpler than the implementation. The public interface
is as simple and logical as possible – exposing only aspects that the clients care about.
We’ll use the word “client” to refer to code that uses the public interface of a class and
“implementation” when talking about the guts of a class. This is not to be confused with
“client” of “client/server”, although an analogy can be made.
Student Client Side
First we'll look at some client code of the Student class.
Client code will typically allocate objects and send them messages.
With good OOP design, being a client should be easy.
Client code plan
Allocate objects with “new” – calls constructor
Objects are always accessed through pointers – shallow, pointer semantics
Send messages – methods execute against the receiver
Can access public, but not private/protected from client side
Object Pointers
The declaration “Student x;” declares a pointer “x” to a Student object, but does not allocate the
object yet.
Java has a very simple and uniform memory system. Objects and arrays are allocated in the heap
and accessed through pointers.
There is no "&" operator to make a pointer to something in the stack and there is no pointer
arithmetic. The only pointers that exist in Java point to objects and arrays in the heap – simple.
Objects and arrays are allocated with the "new" operator (below).
Using = on an object pointer just copies the pointer, so there are multiple pointers to the
one object (aka "shallow" or "sharing").
Likewise, using == does a shallow comparison of the two pointers – true if the two
pointers point to the same object. For some classes, the equals() method will do a "deep"
comparison of two objects.
new Student() / Constructor
The "new" operator allocates a new object in the heap, runs a constructor to initialize it, and
returns a pointer to it.
x = new Student(12) ;

8
Classes define "constructors" that initialize objects at the time new is called.
Constructors are similar to methods, but they cannot be called at will. Instead, they are
run automatically by the JVM when a new object is created.
The word “constructor” can be written as “ctor”
The constructor has the same name as the class. e.g. the constructor for the "Student" class is
named "Student".
There can be multiple constructors. They are distinguished at compile time by having different
arguments – this is called "overloading".
e.g. The Student class defines one ctor that takes an int argument, and one ctor that takes
no arguments.
The ctor that take no arguments is called the "default" ctor. If it is defined, the system
uses it by default when no other ctor is specified.
Message send
Send a message to an object.
a.getUnits();
b.getStress();
Finds the matching method in the class of the receiver, executes that method against the receiver
and returns.
The Java compiler checks the names and types of all message sends at compile time, and only
allows message sends that the receiver responds to.
Object Lifecycle
The client allocates objects and they are initialized by the class ctor code
The client then sends messages which run class method code on the objects.
The client essentially makes requests – all the code that actually operates on the objects is
defined by the class, not the client.
As a result, if the class is written correctly, the client should not be able to introduce new bugs in
the class and visa-versa.
This is the benefit of using public/private to keep the client and the implementation separate.
Student Client Side Code
// Make two students
Student a = new Student(12); // new 12 unit student
Student b = new Student(); // new 15 unit student (default ctor)
// They respond to getUnits() and getStress()
System.out.println("a units:" + a.getUnits() + " stress:" +
a.getStress());
System.out.println("b units:" + b.getUnits() + " stress:" +
b.getStress());
a.dropClass(3); // a drops a class
System.out.println("a units:" + a.getUnits() + " stress:" +
a.getStress());

9
// Now "b" points to the same object as "a" (pointer copy)
b = a;
b.setUnits(10);
// So the "a" units have been changed
System.out.println("a units:" + a.getUnits() + " stress:" +
a.getStress());
// NOTE: public vs. private
// A statement like "b.units = 10;" will not compile in a client
// of the Student class when units is declared protected or
// private
/* OUTPUT...
a units:12 stress:120
b units:15 stress:150
a units:9 stress:90
a units:10 stress:100
*/
Student Implementation Side
Now we'll look at the implementation of the Student class. The complete code listing for Student
is given at the end of this section…
Class Definition
A class defines the instance variables and methods used by its objects.
Each variable and method may be declared as "public" if it may be used by clients, or "private"
or "protected" if it is part of the implementation and not for use by clients.
The compiler and JVM enforce the public/private scheme.
Public Interface
The most common public/private scheme is...
All ivars are declared private
Methods to be used by clients are declared public – these make up the interface that the class
exposes to clients.
Utility methods for the internal use of the class are declared private.
Java Class
The convention is that Java classes have upper case names like “Student” and the code is in a file
named “Student.java”.
By default, Java classes have the special class "Object" as a superclass. We'll look at what that
means later when we study superclasses.
Inside the Student.java file, the class definition looks like...
public class Student extends Object {
... <definition of the Student ivars and methods> ....
}

10
The “extends Object” part can be omitted, since Java classes extend Object by default if no
“extends” clause is specified.
There are not separate .h and .c files to keep in synch – the class is defined in one place.
This is a nice example of the "never have two copies of anything" rule. Keeping duplicate
info in the .h and .c files in synch was a bore – better to just have one copy.
Instance Variables (ivars)
Instance variables are declared like ordinary variables – a type followed by a name.
protected int units;
An ivar defines a variable that each object of this class will have – allocates a slot inside each
object. In this case, every Student object has an int ivar called “units” in it.
The object itself is allocated in the heap, and its ivars are stored inside it. The ivars may be
primitive types, such as int, or they may be pointers to other objects or arrays.
The Heap
Foo Instance:
bar: 4
myGoo: *
Goo Instance: amt: 99
Foo Instance:
bar: 13
myGoo: *
Goo Instance: amt: 99
public/private/protected
An ivar or other element declared private is not accessible to client code. The element is only
accessible to the implementation inside the class.
Suppose on the client side we have a pointer "s" to a Student object. The statement "s.units =
13;" in client code will not compile if "units" is private or protected.
"protected" is similar to private, but allows access by subclasses or other classes in the same
package (we will not worry about those cases)
"public" makes something accessible everywhere
There is also a "default" protection level that you get when no public, private, or protected is
specified. In that case, the element is accessible to all other classes in the same package as the
compiled class. This is an odd case, and I recommend against using it.

Download
Java

 

 

Your download will begin in a moment.
If it doesn't, click here to try again.

Share Java to:

Insert your wordpress URL:

example:

http://myblog.wordpress.com/
or
http://myblog.com/

Share Java as:

From:

To:

Share Java.

Enter two words as shown below. If you cannot read the words, click the refresh icon.

loading

Share Java as:

Copy html code above and paste to your web page.

loading