Chapter 1: Introduction to Computers, Programs, and Java

Chapter 1: Introduction to Computers, Programs, and Java

Objectives

  • Understand computer basics, programs, and operating systems.

  • Describe the relationship between Java and the World Wide Web.

  • Understand Java language specification, API, JDK, and IDE.

  • Write a simple Java program and display output on the console.

  • Explain the basic syntax of a Java program.

  • Create, compile, and run Java programs.

  • Understand and apply sound Java programming style and documentation.

  • Explain the differences between syntax errors, runtime errors, and logic errors.

  • Develop Java programs using NetBeans and Eclipse.

What is a Computer?

A computer is composed of several key components:

  • Central Processing Unit (CPU)

  • Memory

  • Hard Disk

  • Floppy Disk

  • Monitor

  • Printer

  • Communication Devices

CPU (Central Processing Unit)

  • Often referred to as the "brain" of a computer.

  • Its primary function is to retrieve instructions from memory and execute them.

  • CPU speed is measured in megahertz (MHz), where 11 megahertz equals 11 million pulses per second.

  • CPU speeds have continuously improved; for example, an Intel Pentium 44 Processor can operate at 33 gigahertz (11 gigahertz is 10001000 megahertz).

Memory

  • Memory is used to store data and program instructions that the CPU needs to execute.

  • A memory unit is an ordered sequence of bytes, with each byte holding eight bits.

  • For a program or its data to be executed, they must first be loaded into memory.

  • A memory byte is never truly empty, though its initial content might be meaningless to a program.

  • The existing content of a memory byte is overwritten and lost when new information is stored in it.

  • Memory is volatile, meaning all information stored in it is lost when the power is turned off.

How Data is Stored?

  • Various types of data, such as numbers, characters, and strings, are encoded as a series of bits (zeros and ones).

  • Computers use zeros and ones because digital devices have two stable states, which are conventionally represented as zero and one.

  • Programmers typically do not need to be concerned with the encoding and decoding process, as it is handled automatically by the system based on the chosen encoding scheme.

  • Encoding schemes can vary.

    • For example, the character 'J' might be represented by 01001010 in one byte.

  • Small numbers, like 3, can be stored in a single byte.

  • Larger numbers that exceed a single byte's capacity are stored across several adjacent bytes.

  • No two data items can share or split a single byte; a byte is the minimum storage unit.

Storage Devices

  • Unlike volatile memory, storage devices provide permanent storage for programs and data.

  • Data is moved from storage devices to memory only when the computer actively uses it.

  • Three main types of storage devices include:

    • Disk drives (e.g., hard disks and floppy disks)

    • CD drives (e.g., CD-R and CD-RW)

    • Tape drives

Output Devices: Monitor

  • The monitor serves to display information, including text and graphics.

  • The quality of a display is determined by its resolution and dot pitch.

Monitor Resolution and Dot Pitch
  • Resolution specifies the number of pixels in the horizontal and vertical dimensions of the display.

    • Pixels (short for "picture elements") are tiny dots that compose an image on the screen.

    • A common resolution for a 1717-inch screen, for instance, is 1,0241,024 pixels wide by 768768 pixels high.

    • Resolution can often be adjusted manually.

    • Higher resolution generally leads to sharper and clearer images.

  • Dot pitch is the physical spacing between individual pixels, measured in millimeters.

    • A smaller dot pitch indicates a sharper display.

Communication Devices

These devices facilitate data transfer and networking:

  • Regular Modem: Uses a phone line, capable of transferring data up to 56,00056,000 bps (bits per second).

  • DSL (Digital Subscriber Line): Also uses a phone line but can transfer data up to 2020 times faster than a regular modem.

  • Cable Modem: Utilizes the TV cable line, offering speeds comparable to DSL.

  • Network Interface Card (NIC): A device that connects a computer to a local area network (LAN).

    • LANs are common in businesses, universities, and government organizations.

    • A typical 1010BaseT NIC can transfer data at 1010 mbps (million bits per second).

Programs

  • Computer programs, also known as software, are sets of instructions that tell a computer what tasks to perform.

  • A computer is an empty machine without programs.

  • Since computers do not understand human languages, programming languages are used to communicate instructions to them.

Programming Languages

Programming languages are categorized into three main levels:

1. Machine Language
  • Comprises a set of primitive instructions directly built into every computer.

  • These instructions are in binary code.

  • Programming in native machine language is a tedious process, and programs are largely unreadable and difficult to modify.

  • Example: To add two numbers, an instruction might look like 1101101010011010.

2. Assembly Language
  • Developed to simplify programming compared to machine language.

  • Uses mnemonic abbreviations (e.g., ADDF3 R1, R2, R3 for adding numbers) instead of binary codes.

  • Because computers cannot directly understand assembly language, an assembler program is required to translate assembly language programs into machine code.

3. High-Level Language
  • Characterized by being English-like and easy to learn and program.

  • Example: Calculating the area of a circle with a radius of 55 could be area = 5 * 5 * 3.1415;.

  • Popular High-Level Languages:

    • Ada: Named for Ada Lovelace, developed for the Department of Defense, used mainly in defense projects.

    • BASIC: Beginner's All-purpose Symbolic Instruction Code, designed for easy learning by beginners.

    • C: Developed at Bell Laboratories, combines power of assembly language with portability and ease of use of high-level languages.

    • C++: Object-oriented language based on C.

    • C# (C Sharp): A hybrid of Java and C++, developed by Microsoft.

    • COBOL: Common Business Oriented Language, used for business applications.

    • FORTRAN: FORmula TRANslation, popular for scientific and mathematical applications.

    • Java: Developed by Sun Microsystems (now Oracle), widely used for developing platform-independent Internet applications.

    • Pascal: Named for Blaise Pascal, a simple, structured, general-purpose language primarily for teaching programming.

    • Python: A simple general-purpose scripting language, well-suited for short programs.

    • Visual Basic: Developed by Microsoft, enables rapid development of graphical user interfaces.

Interpreting/Compiling Source Code

  • A program written in a high-level language is called a source program or source code.

  • Computers cannot directly understand source programs; they must be translated into machine code for execution.

  • This translation is done using either an interpreter or a compiler.

Interpreting Source Code
  • An interpreter reads one statement of the source code at a time.

  • Translates that statement into machine code or virtual machine code.

  • Executes the translated statement immediately.

  • A single source code statement might translate into multiple machine instructions.

Compiling Source Code
  • A compiler translates the entire source code into a machine-code file.

  • The generated machine-code file is then executed.

Operating Systems (OS)

  • The operating system is a program responsible for managing and controlling a computer's activities.

  • Application programs (e.g., web browsers, word processors) require an OS to be installed and running to function.

  • Popular operating systems for general-purpose computers include Microsoft Windows, Mac OS, and Linux.

Why Java?

  • Java's primary strength is its ability to develop and deploy applications over the Internet across servers, desktop computers, and small hand-held devices.

  • Java is considered the Internet programming language and a general-purpose language, playing a significant role in the Internet's influence on computing.

Java, Web, and Beyond

Java's versatility allows it to develop various types of applications:

  • Standalone applications (programs that run independently).

  • Applications running from a browser (e.g., applets).

  • Applications for hand-held devices.

  • Applications for Web servers.

Java's History

  • Java was conceived by James Gosling and developed by Sun Microsystems.

  • It was originally named "Oak."

  • Java was officially announced on May 2020, 19951995, at Sun World.

  • HotJava was the first Web browser to be enabled with Java technology.

Characteristics of Java

Java possesses several key characteristics that contribute to its popularity:

  • Java Is Simple

    • It is partially modeled on C++ but significantly simplified and improved.

    • Sometimes referred to as "C++--" due to its enhanced functionality and fewer problematic aspects compared to C++.

  • Java Is Object-Oriented

    • Designed from its inception to be inherently object-oriented.

    • Object-Oriented Programming (OOP) is a modern approach that focuses on code reuse.

    • OOP provides flexibility, modularity, clarity, and reusability through core concepts like encapsulation, inheritance, and polymorphism.

  • Java Is Distributed

    • Facilitates distributed computing, where multiple computers collaborate over a network.

    • Networking capability is deeply integrated into Java, making network programming straightforward (similar to file operations).

  • Java Is Interpreted

    • Java programs are compiled into bytecode, which is a machine-independent virtual machine code.

    • These bytecode programs require a Java interpreter, which is part of the Java Virtual Machine (JVM), to run on any machine.

  • Java Is Robust

    • Java compilers can proactively detect many potential problems that might only manifest at execution time in other languages.

    • It has removed certain error-prone programming constructs found in other languages.

    • Java supports robustness through features like runtime exception handling.

  • Java Is Secure

    • Implements various security mechanisms to protect systems from harm caused by unintended or malicious programs.

  • Java Is Architecture-Neutral

    • Enables the "Write Once, Run Anywhere" (WORA) principle.

    • With a JVM, a single Java program can run on any platform without needing recompilation.

  • Java Is Portable

    • Directly results from its architecture-neutral nature, allowing Java programs to be executed on any platform without recompilation.

  • Java's Performance

    • While inherently architecture-neutral and portable, the performance characteristic is often discussed in relation to the JVM's optimization strategies, such as Just-In-Time (JIT) compilation.

  • Java Is Multithreaded

    • Multithreaded programming is seamlessly integrated into Java.

    • Unlike other languages that might require calling operating system-specific procedures for multithreading, Java provides built-in support.

  • Java Is Dynamic

    • Designed to adapt to evolving environments, allowing new code to be loaded on the fly without recompilation.

    • This eliminates the need for developers and users to install major new software versions, allowing new features to be incorporated transparently.

JDK Versions and Editions

JDK (Java Development Kit) Versions (as of 20142014)
  • JDK 1.021.02 (19951995)

  • JDK 1.11.1 (19961996)

  • JDK 1.21.2 (19981998)

  • JDK 1.31.3 (20002000)

  • JDK 1.41.4 (20022002)

  • JDK 1.51.5 (20042004), also known as JDK 55 or Java 55

  • JDK 1.61.6 (20062006), also known as JDK 66 or Java 66

  • JDK 1.71.7 (20112011), also known as JDK 77 or Java 77

  • JDK 1.81.8 (20142014), also known as JDK 88 or Java 88

JDK Editions
  • Java Standard Edition (J2SE):

    • Used for developing client-side standalone applications or applets.

    • This book primarily uses J2SE to introduce Java concepts.

  • Java Enterprise Edition (J2EE):

    • Used for developing server-side applications, such as Java servlets, Java ServerPages (JSP), and Java ServerFaces (JSF).

  • Java Micro Edition (J2ME):

    • Used for developing applications for mobile devices like cell phones.

Popular Java IDEs (Integrated Development Environments)

  • NetBeans

  • Eclipse

A Simple Java Program

// This program prints Welcome to Java!
public class Welcome {
 public static void main(String[] args) {
  System.out.println("Welcome to Java!");
 }
}
Anatomy of a Java Program
  • Class Name: Every Java program must contain at least one class. Class names conventionally start with an uppercase letter (e.g., Welcome).

  • Main Method: The public static void main(String[] args) method is the entry point for program execution. A class must have a main method to be runnable.

  • Statement: A statement represents a specific action or sequence of actions. For example, System.out.println("Welcome to Java!"); is a statement that displays the greeting "Welcome to Java!".

  • Statement Terminator: Every statement in Java must end with a semicolon (;).

  • Reserved Words (Keywords): These words have special, predefined meanings to the Java compiler and cannot be used for other purposes (e.g., public, class, static, void).

  • Comments: Used for explaining code; they are ignored by the compiler. Single-line comments start with //.

  • Blocks: A pair of curly braces ({ }) defines a block, which groups related components or statements of a program.

Special Symbols in Java
  • { }: Opening and closing braces; denote a block to enclose statements.

  • ( ): Opening and closing parentheses; used with methods.

  • [ ]: Opening and closing brackets; denote an array.

  • //: Double slashes; precedes a comment line.

  • " ": Opening and closing quotation marks; enclose a string (sequence of characters).

  • ;: Semicolon; marks the end of a statement.

Creating, Compiling, and Running Programs

Creating and Editing
  • Simple text editors like NotePad (notepad Welcome.java from DOS prompt) or WordPad (write Welcome.java from DOS prompt) can be used.

Compiling Java Source Code
  • A source program can be ported to any machine with appropriate compilers, but it must be recompiled for that specific machine to run as an object program.

  • Java aims for WORA (Write Once, Run Anywhere) by compiling source code into a special type of object code called bytecode.

  • This bytecode can then be executed on any computer that has a Java Virtual Machine (JVM), which interprets the bytecode.

  • From the command window, compilation is done using javac Welcome.java.

Running Java Programs
  • Program execution begins from the main method.

  • From the command window, running is done using java Welcome.

Command Window Configuration for Java
  • Set path to JDK bin directory: set path=c: Program Files java jdk1.8.0 bin

  • Set classpath to include the current directory: set classpath=.

Programming Style and Documentation

Adhering to good programming style generally improves code readability and maintainability.

Appropriate Comments
  • Begin the program with a summary explaining its purpose, key features, data structures, and unique techniques.

  • Include essential information at the start of the program, such as your name, class section, instructor, date, and a brief description.

Naming Conventions
  • Choose names that are meaningful and descriptive.

  • Class Names: Capitalize the first letter of each word in the name (e.g., ComputeExpression).

Proper Indentation and Spacing Lines
  • Indentation: Code within blocks should typically be indented by two spaces.

  • Spacing Lines: Use blank lines to logically separate different segments of code, enhancing readability.

Block Styles
  • Use the end-of-line style for placing opening braces ({).

Programming Errors

Program errors generally fall into three categories:

1. Syntax Errors
  • These are errors detected by the compiler. They are often due to violations of Java's grammatical rules.

  • Example: Forgetting a semicolon at the end of a statement or forgetting to close quotation marks (e.g., System.out.println("Welcome to Java); is a syntax error because of the missing closing quote and semicolon).

2. Runtime Errors
  • These errors occur during the execution of a program and cause the program to terminate unexpectedly.

  • Example: Division by zero (e.g., System.out.println(1 / 0); will cause a runtime error).

3. Logic Errors
  • These errors do not prevent the program from compiling or running, but they produce incorrect or unintended results.

  • Example: In the formula to convert Celsius to Fahrenheit, (Cimesrac95)+32(C imes rac{9}{5}) + 32, if you write (9/5)35+32;</code>inJavawithintegerdivision,<code>(9 / 5) * 35 + 32;</code> in Java with integer division, <code>(9 / 5)</code>wouldevaluateto</code> would evaluate to1insteadoftheexpectedinstead of the expected1.8,leadingtoanincorrectresult(, leading to an incorrect result ((1 imes 35) + 32 = 67insteadofinstead of(1.8 imes 35) + 32 = 95$$).

Displaying Text in a Message Dialog Box

  • Another way to display output is by using the showMessageDialog method from the JOptionPane class.

  • JOptionPane is a predefined class in the Java system that can be reused, avoiding the need to "reinvent the wheel."

The showMessageDialog Method
  • The full invocation: JOptionPane.showMessageDialog(null, "Welcome to Java!", "Display Message", JOptionPane.INFORMATION_MESSAGE);

  • There are two primary ways to invoke this method:

    • JOptionPane.showMessageDialog(null, x, y, JOptionPane.INFORMATION_MESSAGE);

      • x: A string containing the text to be displayed.

      • y: A string for the title of the message dialog box.

    • JOptionPane.showMessageDialog(null, x);

      • x: A string containing the text to be displayed (title will be default).

Implicit Import and Explicit Import
  • Implicit Import: Importing all classes from a package, e.g., java.util.*;

  • Explicit Import: Importing a specific class, e.g., java.util.JOptionPane;

  • There is no performance difference between implicit and explicit imports.