You are on page 1of 41

Java Programming

History of Java
Java was designed by Sun Microsystems in the early 1990s to solve the problem of connecting many household machines together. This project failed because no one wanted to use it. Then it was redesigned to work with cable TV. This project also failed because the cable companies decided to choose a competing system.

When the World Wide Web became popular in 1994, Sun realized that Java was the perfect programming language for the Web. Early in 1996 (late 1995?) they released Java (previously named Oak) and it was an instant success! It was a success, not because of marketing, but because there was a great need for a language with its characteristics.

Most compilers produce code for a real machine. The Java compiler produces code for a virtual machine.

Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine, perform additional steps at runtime to give your application a performance boost. This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.

Javas Compiler + Interpreter


Editor Compiler

7 K

Hello.java

:
Hello.class

Interpreter

Interpreter

:
Hello, World!

2-8

Why Bytecode?
Platform-independent Loads from the Internet faster than source code Interpreter is faster and smaller than it would be for Java source Source code is not revealed to end users Interpreter performs additional security checks, screens out malicious code
2-9

The Java Platform


The Java platform has two components:
The Java Virtual Machine The Java Application Programming Interface (API)

The API is a large collection of readymade software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages

JDK Java Development Kit


javac
Java compiler

javadoc
generates HTML documentation (docs) from source

java
Java interpreter

appletviewer
tests applets without a browser

jar
packs classes into jar files (packages)

All these are command-line tools, no GUI

2-12

JDK (contd)
Developed by Sun Microsystems (now Oracle); free download
http://www.oracle.com/technetwork/java/javase/downloads/

All documentation is online Many additional Java resources on the Internet

2-13

Java IDE
GUI front end for JDK Integrates editor, javac, java, appletviewer, debugger, other tools:
specialized Java editor with syntax highlighting, autoindent, tab setting, etc. clicking on a compiler error message takes you to the offending source code line

Usually JDK is installed separately and an IDE is installed on top of it.


2-14

Types of Programs
Console applications GUI applications

Applets

2-15

Console Applications
Simple text dialog:
prompt input, prompt input ... result
C:\javamethods\Ch02> path=%PATH%;C:\Program Files\Java\jdk 1.5.0_07\bin C:\javamethods\Ch02> javac Greetings2.java C:\javamethods\Ch02> java Greetings2 Enter your first name: Josephine Enter your last name: Jaworski Hello, Josephine Jaworski Press any key to continue...

2-16

Command-Line Arguments
C:\javamethods\Ch02> javac Greetings.java C:\javamethods\Ch02> java Greetings Josephine Jaworski

Hello, Josephine Jaworski

public class Greetings { public static void main(String[ ] args) { String firstName = args[ 0 ]; String lastName = args[ 1 ]; System.out.println("Hello, " + firstName + " " + lastName); } }

Command-line arguments are passed to main as an array of Strings.

2-17

Command-Line Args (contd)


Can be used in GUI applications, too IDEs provide ways to set them (or prompt for them)

Josephine Jaworski

2-18

Greetings2.java
import java.util.Scanner;

public class Greetings2 { public static void main(String[ ] args) { Scanner kboard = new Scanner(System.in); System.out.print("Enter your first name: "); String firstName = kboard.nextLine( ); System.out.print("Enter your last name: "); String lastName = kboard.nextLine( ); System.out.println("Hello, " + firstName + " " + lastName); System.out.println("Welcome to Java!"); } }

Prompts

2-19

GUI Applications
Menus

Clickable panel

Buttons

Slider

2-20

HelloGui.java
import java.awt.*; import javax.swing.*;
GUI libraries

public class HelloGui extends JFrame { < ... other code > public static void main(String[ ] args) { HelloGui window = new HelloGui( ); // Set this window's location and size: // upper-left corner at 300, 300; width 200, height 100 window.setBounds(300, 300, 200, 100); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } }
2-21

The Java Programming Language


The Java programming language is a high-level language that can be characterized by all of the following buzzwords:
Simple Architecture neutral Object oriented Portable Distributed High performance Multithreaded Robust Dynamic Secure

OOP
An OO program models the application as a world of interacting objects. An object can create other objects. An object can call another objects (and its own) methods (that is, send messages). An object has data fields, which hold values that can change while the program is running.
3-23

Objects
Can model real-world objects Can represent GUI (Graphical User Interface) components Can represent software entities (events, files, images, etc.) Can represent abstract concepts (for example, rules of a game, a location on a grid, etc.)
3-24

Objects in the Bug Runner program


GridWorld window Menu bar, menus Grid Message display Scroll bar

Locations (in the grid) Colors

Bugs, flowers, and rocks

Control panel Buttons, slider


3-25

Classes and Objects


A class is a piece of the programs source code that describes a particular type of objects. OO programmers write class definitions. An object is called an instance of a class. A program can create and use more than one object (instance) of the same class.
3-26

Class
A blueprint for objects of a particular type Defines the structure (number, types) of the attributes Defines available behaviors of its

Object
Attributes

Behaviors

3-27

Class: Car

Object: a car

Attributes: String model Color color int numPassengers double amountOfGas Behaviors: Add/remove a passenger Get the tank filled Report when out of gas

Attributes: model = "Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5 Behaviors:

3-28

Class
A piece of the programs source code Written by a programmer

vs.

Object

An entity in a running program Created when the program is running (by the main method or a constructor or another method)

3-29

Class
Specifies the structure (the number and types) of its objects attributes the same for all of its objects Specifies the possible behaviors of its objects

vs.

Object

Holds specific values of attributes; these values can change while the program is running

Behaves appropriately when called upon


3-30

Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

Software objects provides a number of benefits

Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

Classes combine data and methods. A class defines a data type. Advantage: Classes correspond to concepts in the problem domain. Advantage: Classes reduce complexity by increasing coherence and reducing coupling.

Introduce classes to store data in value objects.

Classes and Source Files


Each class is stored in a separate file The name of the file must be the same as the name of the class, with the By convention, the name extension .java Car.java
public class Car { ... } of a class (and its source file) always starts with a capital letter.

(In Java, all names are case-sensitive.)


3-34

The class definition


class notifies the interpreter that a new class will be defined. helloWorld is the unique name for this new class. The curly braces signal the beginning and end of the class body

The main method


Every Java application program has any number of unique methods, but must also contain at least one and only one main method.

public is known as a 'global', a signal to the interpreter that this method can be used in other parts of the program. The private keyword prevents the rest of the program from calling anything inside a method. static tells the interpreter that the main method applies to everything in the helloWorld class, rather than just one element. Breathing and daily activities work as analogies for static and instance methods; daily activities vary but breathing is required. void indicates that this method finishes operating without returning any results. main is the unique identifier for this method and is a reserved word because all Java applications have one and only one main method. The parentheses indicate that parameters can be passed to this method.

Variables (contd)
A variable must be declared before it can be used:
int count;

double
Type JButton

x, y;
go;

Name(s)

Bug bob; String firstName;

6-37

Variables (contd)
The assignment operator = sets the variables value:
count = 5; x = 0; go = new JButton("Go"); firstName = args[0];

6-38

Primitive Data Types


int double char boolean byte short long float

Used in Java Methods

6-39

Strings
String is not a primitive data type Strings work like any other objects, with two exceptions:
Strings in double quotes are recognized as literal constants + and += concatenate strings (or a string and a number or an object, which is converted into a string) "Catch " + 22 "Catch 22"
6-40

Data Types and Data Structures

You might also like