0% found this document useful (0 votes)
4 views

Java Unit i Batu

The document provides an overview of Object-Oriented Programming using Java, covering fundamental concepts such as computer organization, data hierarchy, programming languages, and the principles of object technology. It discusses the evolution of programming languages from machine languages to high-level languages, emphasizing the importance of structured programming and Java's role in modern software development. Additionally, it highlights the characteristics and advantages of object-oriented programming, including encapsulation, inheritance, and polymorphism.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Unit i Batu

The document provides an overview of Object-Oriented Programming using Java, covering fundamental concepts such as computer organization, data hierarchy, programming languages, and the principles of object technology. It discusses the evolution of programming languages from machine languages to high-level languages, emphasizing the importance of structured programming and Java's role in modern software development. Additionally, it highlights the characteristics and advantages of object-oriented programming, including encapsulation, inheritance, and polymorphism.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 82

BT-COE404

Object-Oriented Programming using Java


Unit 1 6 hrs

Introduction to Computers and Java: Computers: Hardware and Software, Data


Hierarchy, Computer Organization, Machine Languages, Assembly Languages and
High-Level Languages, Introduction to Object Technology, Operating Systems,
Programming Languages, Java and a Typical Java Development Environment, Your First
Program in Java: Printing a Line of Text, Modifying Your First Java Program,
Displaying Text with printf, Another Application: Adding Integers, Memory Concepts,
Arithmetic, Decision Making: Equality and Relational Operators.
• Reference Book:
1.Paul Deitel and Harvey Detail, Java: How to Program, Pearson's Publication,
9th Edition, 2012.
2.Joel Murach and Michael Urban, Murach’s Beginning Java with Eclipse,
Murach's Publication, 1st Edition, 2016.
3.Doug Lowe, Java All-in-One For Dummies, Wiley Publication, 4th Edition, 2014.
4.Herbert Schildt, Java The Complete Reference, McGraw-Hill Publication, 9th
Edition, 2014.
5.Patrick Niemeyer, Daniel Leuck, Learning Java, O'Reilly Media, 4th Edition,
2013.
Computers: Hardware and Software
• What Is a Computer?
• A computer is a device capable of performing computations and making logical
decisions at speeds millions (even billions) of times faster than human beings can.
• Computers process data under the control of sets of instructions called computer
programs.
• These programs guide the computer through orderly sets of actions specified by
people called computer programmers.
• A computer consists of various devices referred to as hardware (e.g., the keyboard,
screen, mouse, disks, memory, DVD, CD-ROM and processing units). The programs
that run on a computer are referred to as software.
What Is a Computer?

• Computer
– Performs computations and makes logical decisions
– Millions / billions times faster than human beings
• Computer programs
– Sets of instructions for which computer processes data
• Hardware
– Physical devices of computer system
• Software
– Programs that run on computers

 2002 Prentice Hall. All rights reserved.


Data Hierarchy
• Data Hierarchy
Data hierarchy refers to the systematic organization of data, often in a hierarchical form. Data organization
involves characters, fields, records, files and so on
Following are the components of data hierarchy (ascending order of complexity) in an information system:
1.Bit
• The term bit is short form for binary digit. It can assume either of two possible states and, therefore, can
represent either 0 or 1. In secondary storage, a bit is used to represent data through positive or negative
polarity of an electrical charge on a magnetic recording medium, such as tape or disk. Semi conductor storage
is usually used for primary storage. In semiconductor storage, a bit is represented by an electrical circuit that is
either conducting or not conducting electricity.
2.Byte

cific entity. For example, a payrol


• An ability to represent only binary digits in a computer system is not sufficient for business information
processing. Numeric and alphabetic characters as well as a wide variety of special characters (such as, dollar
signs, question marks and quotation marks) should be stored. In a computer system, a character of information

ployee.
is called a byte. A byte of information is stored by using several bits in specified combination called bit
patterns. A widely used bit pattern for personal computers and data communication is the American Standard
Code for Information Interchange (ASCII).ASCII uses seven bits to represent one character. Each 1 or 0
corresponds to a single bit.
3.Data Field or Item
• The next level in data hierarchy is a field or item of data. A field or item of data is one or
more bytes containing data about the attribute of an entity in an information system. An
entity in a payroll system is an individual employee. Attributes are the employees name,
pay rate and so on. The basic pay is a field or item of data
4.Data Record
• A record is a collection of fields relating to a specific entity. For example, a payroll record
contains fields of data relating to a specific employee.
• An analogy can be made between a computer-based record and an individual folder in a
manual file.
• A folder in a payroll file may contain almost the same information as a record in a
computer-based payroll file.
• The field that identifies a record from all other records in a file is the record key. For
example, the record key in a payroll record is usually an employees provident fund
number or social security number because it is different for each employee.
5.File
• A file is a collection of related records.
6.Database
• A database consists of all the files of an organization. It is structured and integrated
to facilitate update of the files and retrieval of information from them.
• The term has often been used rather loosely.
• Technically, a database consists of those files that are a part of data base
management system. However, a database is often used to refer to all the files of an
organization. Now, all this is called as data hierarchy because databases are
composed of files, files are composed of records, records are composed of filed,
fields composed of data bytes and finally, data bytes are a group of bits.
• This is very well a hierarchical structure.
Computer Organization

• Six logical units of computer system


– Input unit
• Mouse, keyboard
– Output unit
• Printer, monitor, audio speakers
– Memory unit
• RAM
– Arithmetic and logic unit (ALU)
• Performs calculations
– Central processing unit (CPU)
• Supervises operation of other devices
– Secondary storage unit
• Hard drives, floppy drives

 2002 Prentice Hall. All rights reserved.


Computer Organization
• computer may be envisioned as divided into six logical units or sections:
1. Input unit.
- This “receiving” section obtains information (data and computer programs)
from input devices and places this information at the disposal of the other units so that it can be
processed. Most information is entered into computers through keyboards and mouse devices.
Information also can be entered in many other ways, including by speaking to your computer, by
scanning images and by having your computer receive information from a network, such as the
Internet.
2. Output unit.
- This takes information that the computer has
• processed and places it on various output devices to make the information available
for use outside the computer.
• Most information output from computers today is displayed on screens, printed on paper or used
to control other devices.
• Computers also can output their information to networks, such as the Internet.
3. Memory unit.
-This rapid-access, relatively low-capacity “warehouse” section retains
information that has been entered through the input unit, so that it will be
immediately available for processing when needed. The memory unit also retains
processed information until it can be placed on output devices by the output
unit.
• Information in the memory unit is typically lost when the computer’s power is
turned off. The memory unit is often called either memory or primary memory.
4. Arithmetic and logic unit (ALU).
This “manufacturing” section is responsible for
• performing calculations, such as addition, subtraction, multiplication and
division.
• It contains the decision mechanisms that allow the computer, for example,
to compare two items from the memory unit to determine whether they are
equal.
5. Central processing unit (CPU).
-This “administrative” section coordinates and supervises the operation of the other sections.
The CPU tells the input unit when information should be read into the memory unit, tells the
ALU when information from the memory unit should be used in calculations and tells the
output unit when to send information from the memory unit to certain output devices. Many
of today’s computers have multiple CPUs and, hence, can perform many operations
simultaneously—such computers are called multiprocessors.
6. Secondary storage unit.
-This is the long-term, high-capacity “warehousing” section.
• Programs or data not actively being used by the other units normally are placed on
secondary storage devices (e.g., your hard drive) until they are again needed, possibly
hours, days, months or even years later. Information in secondary storage takes much longer
to access than information in primary memory, but the cost per unit of secondary storage is
much less than that of primary memory.
• Examples of secondary storage devices include CDs and DVDs, which can hold up to
hundreds of millions of characters and billions of characters, respectively.
Machine Languages, Assembly Languages and
High-Level Languages
• Machine language
– “Natural language” of computer component
– Machine dependent
• Assembly language
– English-like abbreviations represent computer operations
– Translator programs convert to machine language
• High-level language
– Allows for writing more “English-like” instructions
• Contains commonly used mathematical operations
– Compiler convert to machine language
• Interpreter
– Execute high-level language programs without compilation

 2002 Prentice Hall. All rights reserved.


Programming Languages
Machine Languages, Assembly Languages and High-Level Languages

• Programmers write instructions in various programming languages, some directly


understandable by computers and others requiring intermediate translation steps.
Hundreds of computer languages are in use today. These may be divided into three
general types:
1. Machine languages
2. Assembly languages
3. High-level languages
• Any computer can directly understand only its own machine language. Machine
language is the “natural language” of a computer and as such is defined by its hardware
design.
• Machine languages generally consist of strings of numbers (ultimately reduced to 1s and
0s) that instruct computers to perform their most elementary operations one at a time.
• Machine languages are machine dependent (i.e., a particular machine language can be
used on only one type of computer). Such languages are cumbersome for humans
• A programming language is a formal language, which comprises a set of
instructions used to produce various kinds of output. Programming languages are
used in computer programming to create programs that implement specific
algorithms.
• Most programming languages consist of instructions for computers, although
there are programmable machines that use a limited set of specific instructions,
rather than the general programming languages of modern computers.
• A machine language consists of the numeric codes for the operations that a
particular computer can execute directly. The codes are strings of 0s and 1s, or
binary digits (“bits”), which are frequently converted both from and to
hexadecimal (base 16) for human viewing and modification. Machine language
instructions typically use some bits to represent operations, such as addition, and
some to represent operands, or perhaps the location of the next instruction.
Machine language is difficult to read and write, since it does not resemble
conventional mathematical notation or human language, and its codes vary from
computer to computer.
• Machine-language programming was simply too slow and tedious for most
programmers. Instead of using the strings of numbers that computers could
directly understand, programmers began using English-like abbreviations to
represent elementary operations. These abbreviations formed the basis of
assembly languages. Translator programs called assemblers were developed to
convert early assembly-language programs to machine language at computer
speeds.
• Assembly language is one level above machine language. It uses short
mnemonic codes for instructions and allows the programmer to introduce
names for blocks of memory that hold data. One might thus write “add pay,
total” instead of “0110101100101000” for an instruction that adds two
numbers.
• high-level languages were developed in which single statements could be
written to accomplish substantial tasks. Translator programs called compilers
convert high-level language programs into machine language. High-level
languages allow programmers to write instructions that look almost like
everyday English and contain commonly used mathematical notations.
• high-level languages are preferable to machine and assembly language from
the programmer’s standpoint. C, C++, Microsoft’s .NET languages (e.g., Visual
Basic .NET, Visual C++ .NET and C#) are among the most widely used high-level
programming languages; Java is the most widely used.
• The process of compiling a high-level language program into machine
language can take a considerable amount of computer time. Interpreter
programs were developed to execute high-level language programs directly,
although more slowly. Interpreters are popular in program-development
environments in which new features are being added and errors corrected.
• Hierarchy of Computer language –

• Most Popular Programming Languages –


• C
• Python
• C++
• Java
• SCALA
• C#
• R
• Ruby
• Go
• Swift
• JavaScript
History of C++

• C++
– Evolved from C
• Evolved from BCPL and B
– Provides object-oriented programming capabilities
• Objects
– Reusable software components that model real-world items

 2002 Prentice Hall. All rights reserved.


History of Java

• Java
– Originally for intelligent consumer-electronic devices
– Then used for creating Web pages with dynamic content
– Now also used for:
• Develop large-scale enterprise applications
• Enhance WWW server functionality
• Provide applications for consumer devices (cell phones, etc.)

 2002 Prentice Hall. All rights reserved.


Java Class Libraries

• Classes
– Contain methods that perform tasks
• Return information after task completion
– Used to build Java programs
• Java contains class libraries
– Known as Java APIs (Application Programming Interfaces)

 2002 Prentice Hall. All rights reserved.


Other High-Level Languages

• Fortran
– FORmula TRANslator
• COBOL
– COmmon Business Oriented Language
• Pascal
• Basic

 2002 Prentice Hall. All rights reserved.


Structured Programming

• Structured Programming
– Structured programs
• Clearer than unstructured programs
• Easier to test, debug and modify
– Pascal designed for teaching structured programming
– ADA
• Multitasking
– C

 2002 Prentice Hall. All rights reserved.


The Internet and the World Wide Web

• Internet
– Developed over three decades ago with DOD funding
– Originally for connecting few main computer systems
– Now accessible by hundreds of millions of computers
• World Wide Web (WWW)
– Allows for locating/viewing multimedia-based documents

 2002 Prentice Hall. All rights reserved.


• Characteristics of a programming Language –

• A programming language must be simple, easy to learn and use, have good readability
and human recognizable.
• Abstraction is a must-have Characteristics for a programming language in which ability to
define the complex structure and then its degree of usability comes.
• A portable programming language is always preferred.
• Programming language’s efficiency must be high so that it can be easily converted into a
machine code and executed consumes little space in memory.
• A programming language should be well structured and documented so that it is suitable
for application development.
• Necessary tools for development, debugging, testing, maintenance of a program must
be provided by a programming language.
• A programming language should provide single environment known as Integrated
Development Environment(IDE).
• A programming language must be consistent in terms of syntax and semantics.
Introduction to Object Technology

• Object-orientation is what’s referred to as a programming paradigm. It’s not a language itself


but a set of concepts that is supported by many languages.
• In computer programming, Objects, or more precisely, the classes used to construct objects,
are intended to be reusable software components.

• There are string objects, output objects, input objects, graphics objects, date objects, time
objects, audio objects, video objects, etc.

• a software object in terms of attributes (e.g., name, color and size) and behaviors (e.g.,
calculating, moving and communicating).

• Using a modular, object-oriented design and implementation approach can make software-
development more productive. Object-oriented programs are often easier to understand,
correct and modify.
• Object-oriented programming organizes a program around its data (that is,
objects) and a set of well-defined interfaces to that data. An object-oriented
program can be characterized as data controlling access to code
• All object-oriented programming languages provide mechanisms that help
you implement the object-oriented model. They are encapsulation,
inheritance, and polymorphism
• Object orientation
• Unified Modeling Language (UML)
– Graphical language that uses common notation
– Allows developers to represent object-oriented designs

 2002 Prentice Hall. All rights reserved.


Thinking About Objects (cont.)

• Objects
– Reusable software components that model real-world items
– Look all around you
• People, animals, plants, cars, etc.
– Attributes
• Size, shape, color, weight, etc.
– Behaviors
• Babies cry, crawl, sleep, etc.

 2002 Prentice Hall. All rights reserved.


Thinking About Objects (cont.)

• Object-oriented design (OOD)


– Models real-world objects
– Models communication among objects
– Encapsulates data (attributes) and functions (behaviors)
• Information hiding
• Communication through well-defined interfaces
• Object-oriented language
– Programming is called object-oriented programming (OOP)
– Java

 2002 Prentice Hall. All rights reserved.


Thinking About Objects (cont.)

• Object-Oriented Analysis and Design (OOAD)


– Essential for large programs
– Analyze program requirements, then develop solution
– We begin OOAD in Chapter 2
• Elevator-simulation case study

 2002 Prentice Hall. All rights reserved.


Thinking About Objects (cont.)

• History of the UML


– Need developed for process with which to approach OOAD
– Brainchild of Booch, Rumbaugh and Jacobson
– Object Management Group (OMG) supervised
– Version 1.4 is current version
• Version 2.0 scheduled tentatively for release in 2002

 2002 Prentice Hall. All rights reserved.


Thinking About Objects (cont.)

• UML
– Graphical representation scheme
– Enables developers to model object-oriented systems
– Flexible and extendible

 2002 Prentice Hall. All rights reserved.


1.16 Discovering Design Patterns: Introduction

• Effective design crucial for large programs


• Design patterns
– Proven architectures for developing object-oriented software
• Architectures created from accumulated industry experience
– Reduce design-process complexity
– Promotes design reuse in future systems
– Helps identify common design mistakes and pitfalls
– Helps design independently of implementation language
– Establishes common design “vocabulary”
– Shortens design phase in software-development process

 2002 Prentice Hall. All rights reserved.


Evolution of Operating Systems

• Batch processing
– One job (task) at a time
– Operating systems developed
• Programs to make computers more convenient to use
• Switch jobs easier
• Multiprogramming
– “Simultaneous” jobs
– Timesharing operating systems

 2002 Prentice Hall. All rights reserved.


1.5 Personal, Distributed and Client/Server
Computing
• Personal computing
– Computers for personal use
• Distributed computing
– Computing performed among several computers
• Client/server computing
– Servers offer common store of programs and data
– Clients access programs and data from server

 2002 Prentice Hall. All rights reserved.


Operating Systems

• An operating system (OS), is software that allows a user to run other


applications on a computing device. While it is possible for a software
application to interface directly with hardware, the vast majority of
applications are written for an OS, which allows them to take advantage of
common libraries and not worry about specific hardware details.
• The operating system manages a computer's hardware resources, including:
Input devices such as a keyboard and mouse,Output devices such as display
monitors, printers and scanners
• Network devices such as modems, routers and network connections
• Storage devices such as internal and external drives
• The OS also provides services to facilitate the efficient execution and
management of, and memory allocations for, any additional installed
software application programs.
• Early computers could perform only one job or task at a time. This is often called single user
batch processing. The computer runs a single program at a time while processing data in
groups or batches.
• In these early systems, users generally submitted their jobs to a computer center on decks
of punched cards and often had to wait hours or even days before printouts were returned
to their desks. Software systems called operating systems were developed to make using
computers more convenient.
• Early operating systems smoothed and speeded up the transition between jobs, increasing
the amount of work, or throughput, computers could process. As computers became more
powerful, it became evident that single-user batch processing was inefficient, because so
much time was spent waiting for slow input/output devices to complete their tasks.
• It was thought that many jobs or tasks could share the resources of the computer to
achieve better utilization. This is called multiprogramming. Multiprogramming involves the
simultaneous operation of many jobs that are competing to share the computer’s
resources. With early multiprogramming operating systems, users still submitted jobs on
decks of punched cards and waited hours or days for results.
• Examples of computer operating systems

1.Microsoft Windows 10 - PC and IBM compatible operating system.


Microsoft Windows is the most common and used operating system.
2.Apple macOS - Apple Mac operating system. Today, the only Apple
computer operating system is macOS.
3.Ubuntu Linux - A popular variant of Linux used with PC and IBM
compatible computers.
4.Google Android - Operating system used with Android compatible phones
and tablets.
5.iOS - Operating system used with the Apple iPhone and iPads.
6.Chromium - Google operating system used with Chromebooks.
1.13 Basics of a Typical Java Environment

• Java systems contain


– Environment
– Language
– APIs
– Class libraries

 2002 Prentice Hall. All rights reserved.


1.13 Basics of a Typical Java Environment (cont.)

• Java programs normally undergo five phases


– Edit
• Programmer writes program (and stores program on disk)
– Compile
• Compiler creates bytecodes from program
– Load
• Class loader stores bytecodes in memory
– Verify
• Verifier ensures bytecodes do not violate security requirements
– Execute
• Interpreter translates bytecodes into machine language

 2002 Prentice Hall. All rights reserved.


Fig. 1.1 A typical Java environment.

Prog ram is c reated in


Pha se 1 Editor the editor and sto red
Disk
on d isk.

Compiler c rea te s
bytec odes and stores
Pha se 2 Compiler Disk the m on disk.

Primary
Memory
Pha se 3 Class Lo ad er

Class loa de r p uts


bytec o des in memory.
Disk ..
..
..

Primary
Memory
Pha se 4 Bytec ode Ve rifier Byte c ode verifier
c onfirms that a ll
bytec odes are valid
and do not violate
J ava ’s sec urity
restric tions.
..
..
..

Primary
Memory Interpreter read s
Pha se 5 Interp reter bytec odes and
translates them into a
la nguag e that the
c omputer c an
und ersta nd, possib ly
storing d ata values a s
.. the program exec utes.
..
..

 2002 Prentice Hall. All rights reserved.


 2002 Prentice Hall. All rights reserved.
Java and a Typical Java Development Environment
• Java: Sun Microsystems in 1991 funded an internal corporate research project led by
James Gosling, which resulted in a C++-based object-oriented programming language
Sun called Java. A key goal of Java is to be able to write programs that will run on a
great variety of computer systems and computer-control devices. This is sometimes
called “write once, run anywhere.”
• Java is now used to develop large-scale enterprise applications, to enhance the
functionality of web servers (the computers that provide the content we see in our web
browsers), to provide applications for consumer devices (e.g., cell phones, smartphones,
television set-top boxes and more) and for many other purposes. Sun Microsystems was
acquired by Oracle in 2009. At the JavaOne 2010 conference,Oracle announced that 97%
of enterprise desktops, three billion handsets, and 80 million television devices run Java.
There are currently over 9 million Java developers, up from 4.5 million in 2005.8 Java is
now the most widely used software development language in the world.
• Java programs normally go through five phases—edit, compile, load, verify and execute.
• We discuss these phases in the context of the Java SE Development Kit (JDK). You can download the most
up-to-date JDK and its documentation from www.oracle.com/technetwork/java/ javase/downloads/index.html
Phase 1: Creating a Program
• Phase 1 consists of editing a file with an editor program, normally known simply as an editor
• You type a Java program (typically referred to as source code) using the editor,
• make any necessary corrections and save the program on a secondary storage device, such as your hard drive. A
file name ending with the .java extension indicates that the file contains Java source code.

• integrated development environments (IDEs) are available from many major software suppliers.
• IDEs provide tools that support the software development process, including editors for writing and
editing programs
• Popular IDEs include Eclipse (www.eclipse.org) and NetBeans (www.netbeans.org).
Phase 2: Compiling a Java Program into Bytecodes
• use the command javac (the Java compiler) to compile a program
• For example, to compile a program called Welcome.java, you’d type in the command window of your
system (i.e., the Command Prompt in Windows, the shell prompt in Linux or the Terminal application
in Mac OS X). If the program compiles, the compiler produces a .class file called Welcome.class that
contains the compiled version of the program.
• The Java compiler translates Java source code into bytecodes that represent the tasks to execute in
the execution phase.Bytecodes are executed by the Java Virtual Machine (JVM)—a part of the JDK
and the foundation of the Java platform.
• Virtual machine (VM) is a software application that simulates a computer but hides the underlying
operating system and hardware from the programs that interact with it. If the same VM is
implemented on many computer platforms, applications that it executes can be used on all those
platforms.
• Java’s bytecodes are portable—without recompiling the source code, the same bytecodes can
execute on any platform containing a JVM that understands the version of Java in which the
bytecodes were compiled.
• The JVM is invoked by the java command.
• For example, to execute a Java application called Welcome, you’d type the command in a command
window to invoke the JVM as java Welcome
Phase 3: Loading a Program into Memory
• JVM places the program in memory to execute it—this is known as loading
• The JVM’s class loader takes the .class files containing the program’s bytecodes and transfers them to
primary memory. The .class files can be loaded from a disk on your system or over a network (e.g., your local
college or company network, or the Internet).
Phase 4: Bytecode Verification
• as the classes are loaded, the bytecode verifier examines their bytecodes to
ensure that they’re valid and do not violate Java’s security restrictions
Phase 5: Execution
• the JVM executes the program’s bytecodes, thus performing the actions specified by
the program .
• JVMs typically execute bytecodes using a combination of interpretation and so-called
just-in-time (JIT) compilation. In this process, the JVM analyzes the bytecodes as
they’re interpreted, searching for hot spots—parts of the bytecodes that execute
frequently. For these parts, a just-in-time (JIT) compiler— known as the Java HotSpot
compiler—translates the bytecodes into the underlying computer’s machine language.
• When the JVM encounters these compiled parts again, the faster machine-language
code executes. Thus Java programs actually go through two compilation phases—one
in which source code is translated into bytecodes (for portability across JVMs on
different computer platforms) and a second in which, during execute the bytecodes are
translated into machine language for the actual computer on which the program
executes.
Your First Program in Java:
Printing a Line of Text, Modifying Your First Java Program
54
1 // Fig. 2.1: Welcome1.java Outline
2 // A first program in Java.
3
4 public class Welcome1 {
5
6 // main method begins execution of Java application
7 public static void main( String args[] )
8 {
9 System.out.println( "Welcome to Java Programming!" );
10
11 } // end method main
12
13 } // end class Welcome1 Welcome1.java

Program Output
Welcome to Java Programming!
 2002 Prentice Hall.
All rights reserved.
55

2.2 A Simple Program: Printing a Line of Text

1 // Fig. 2.1: Welcome1.java

– Comments start with: //


• Comments ignored during program execution
• Document and describe code
• Provides code readability
– Multiple line comments: /* ... */
/* This is a multiple
line comment. It can
be split over many lines */

2 // A first program in Java.


– Another line of comments
– Note: line numbers not part of program, added for reference

 2002 Prentice Hall. All rights reserved.


56

2.2 A Simple Program: Printing a Line of Text

– Blank line
• Makes program more readable
• Blank lines, spaces, and tabs are white-space characters
– Ignored by compiler

4 public class Welcome1 {

– Begins class definition for class Welcome1


• Every Java program has at least one user-defined class
• Keyword: words reserved for use by Java
– class keyword followed by class name
• Naming classes: capitalize every word
– SampleClassName

 2002 Prentice Hall. All rights reserved.


57

2.2 A Simple Program: Printing a Line of Text

4 public class Welcome1 {

– Name of class called identifier


• Series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ( $ )
• Does not begin with a digit, has no spaces
• Examples: Welcome1, $value, _value, button7
– 7button is invalid
• Java is case sensitive (capitalization matters)
– a1 and A1 are different
– For chapters 2 to 7, use public keyword
• Certain details not important now
• Mimic certain features, discussions later

 2002 Prentice Hall. All rights reserved.


58

2.2 A Simple Program: Printing a Line of Text

4 public class Welcome1 {

– Saving files
• File name must be class name with .java extension
• Welcome1.java
– Left brace {
• Begins body of every class
• Right brace ends definition (line 13)

7 public static void main( String args[] )


– Part of every Java application
• Applications begin executing at main
– Parenthesis indicate main is a method (ch. 6)
– Java applications contain one or more methods

 2002 Prentice Hall. All rights reserved.


59

2.2 A Simple Program: Printing a Line of Text

7 public static void main( String args[] )

• Exactly one method must be called main


– Methods can perform tasks and return information
• void means main returns no information
• For now, mimic main's first line

8 {

– Left brace begins body of method definition


• Ended by right brace } (line 11)

 2002 Prentice Hall. All rights reserved.


60

2.2 A Simple Program: Printing a Line of Text

9 System.out.println( "Welcome to Java Programming!" );

– Instructs computer to perform an action


• Prints string of characters
– String - series characters inside double quotes
• White-spaces in strings are not ignored by compiler
– System.out
• Standard output object
• Print to command window (i.e., MS-DOS prompt)
– Method System.out.println
• Displays line of text
• Argument inside parenthesis
– This line known as a statement
• Statements must end with semicolon ;

 2002 Prentice Hall. All rights reserved.


61

2.2 A Simple Program: Printing a Line of Text

11 } // end method main

– Ends method definition

13 } // end class Welcome1

– Ends class definition


– Can add comments to keep track of ending braces
– Lines 8 and 9 could be rewritten as:
– Remember, compiler ignores comments
– Comments can start on same line after code

 2002 Prentice Hall. All rights reserved.


62
2.2.1 Compiling and Executing your First Java
Application
• Compiling a program
– Open a command prompt window, go to directory where program is stored
– Type javac Welcome1.java
– If no errors, Welcome1.class created
• Has bytecodes that represent application
• Bytecodes passed to Java interpreter

 2002 Prentice Hall. All rights reserved.


63
2.2.1 Compiling and Executing your First Java
Application
• Executing a program
– Type java Welcome1
• Interpreter loads .class file for class Welcome1
• .class extension omitted from command
– Interpreter calls method main

Fig. 2.2 Executing Welcome1 in a Microsoft Windows 2000 Command Prompt.

 2002 Prentice Hall. All rights reserved.


64

2.3 Modifying Our First Java Program

• Modify example in Fig. 2.1 to print same contents using different


code

 2002 Prentice Hall. All rights reserved.


65
2.3.1 Displaying a Single Text with Multiple
Statements
• Modifying programs
– Welcome2.java (Fig. 2.3) produces same output as Welcome1.java (Fig. 2.1)
– Using different code

9 System.out.print( "Welcome to " );


10 System.out.println( "Java Programming!" );

– Line 9 displays “Welcome to ” with cursor remaining on printed line


– Line 10 displays “Java Programming! ” on same line with cursor on next line

 2002 Prentice Hall. All rights reserved.


66
1 // Fig. 2.3: Welcome2.java Outline
2 // Printing a line of text with multiple statements.
3
4 public class Welcome2 {
5 Welcome2.java
6 // main method begins execution of Java application
7 public static void main( String args[] ) 1. Comments
8 {
9 System.out.print( "Welcome to " );
10 System.out.println( "Java Programming!" ); 2. Blank line
11
12 } // end method main
13 3. Begin class Welcome2
14 } // end class Welcome2
System.out.print keeps the cursor on 3.1 Method main
the same line, so System.out.println
continues on the same line. 4. Method
System.out.print

4.1 Method
System.out.println

5. end main, Welcome2

Program Output

Welcome to Java Programming!

 2002 Prentice Hall.


All rights reserved.
67
2.3.2 Displaying Multiple Lines of Text with a
Single Statement
• Newline characters (\n)
– Interpreted as “special characters” by methods System.out.print and
System.out.println
– Indicates cursor should be on next line
– Welcome3.java (Fig. 2.4)
9 System.out.println( "Welcome\nto\nJava\nProgramming!" );

– Line breaks at \n
• Usage
– Can use in System.out.println or System.out.print to create new
lines
• System.out.println( "Welcome\nto\nJava\nProgramming!" );

 2002 Prentice Hall. All rights reserved.


68
Outline
1 // Fig. 2.4: Welcome3.java
2 // Printing multiple lines of text with a single statement.
3 Welcome3.java
4 public class Welcome1 {
1. main
5
6 // main method begins execution of Java application 2. System.out.println
7 public static void main( String args[] ) (uses \n for new line)
8 {
9 System.out.println( "Welcome\nto\nJava\nProgramming!"
);
10
11 } // end method main Program Output
12
13 } // end class Welcome3

Welcome
to
Java
Programming!
Notice how a new line is output for each \n
escape sequence.
 2002 Prentice Hall.
All rights reserved.
69
2.3.2 Displaying Multiple Lines of Text with a
Single Statement
Escape characters
– Backslash ( \ )
– Indicates special characters be output
Esc ape sequenc e Description
\n Newline. Position the screen cursor to the beginning of the next
line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning of the
current line; do not advance to the next line. Any characters
output after the carriage return overwrite the characters previously
output on that line.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double-quote character. For
example,
System.out.println( "\"in quotes\"" );
displays
"in quotes"
Fig. 2.5 Some common esc ape sequences.

 2002 Prentice Hall. All rights reserved.


Displaying Text with printf
• Java SE 5.0 added the System.out.printf method for displaying formatted data—the` f ‘ in the name printf stands for
“formatted.” below code outputs the strings "Welcome to“ and "Java Programming!" with System.out.printf.

System.out.printf ( "%s\n%s\n","Welcome to", "Java Programming!" );

• Method printf’s first argument is a format string that may consist of fixed text and format specifiers.
public class Welcome4
{
public static void main( String args[] )
{
System.out.printf( "%s\n%s\n","Welcome to", "Java Programming!" );
}
}
Output: Welcome to
Java Programming!
Another Java Application: Adding Integers
• Application reads (or inputs) two integers (whole numbers, like –22, 7, 0 and 1024) typed by
a user at the keyboard, computes the sum of the values and displays the result.
import java.util.Scanner; // program uses class declaration
• Scanner is an import declaration that helps the compiler locate a class that is used in
this program
Scanner input = new Scanner( System.in );
is a variable declaration statement (also called a declaration) that specifies the name
(input) and type (Scanner) of a variable that is used in this program.
• A Scanner enables a program to read data
• new Scanner( System.in ) expression creates a Scanner object that reads data typed
by the user at the keyboard.
• standard input object, System.in, enables Java applications to read information
typed by the user.
Memory Concepts
• Variable names such as number1, number2 and sum actually correspond to
locations in the computer’s memory. Every variable has a name, a type, a size and a
value.
• In the addition program, when the following statement executes
number1 = input.nextInt(); // read first number from user

the number typed by the user is placed into a memory location to which the compiler
assigned the name number1.
• Suppose that the user enters 45. The computer places that integer value into location
number1. Whenever a value is placed in a memory location, the value replaces the
previous value in that location. The previous value is lost.
Arithmetic
• Most programs perform arithmetic calculations.
Arithmetic Expressions in Straight-Line Form
• Arithmetic expressions in Java must be written in straight-line form to facilitate entering
programs into the computer. Thus, expressions such as “a divided by b” must be written as
a / b, so that all constants, variables and operators appear in a straight line.
Parentheses for Grouping Subexpressions
• Parentheses are used to group terms in Java expressions in the same manner as in
algebraic expressions. For example, to multiply a times the quantity b + c, we write
a*(b+c)
• If an expression contains nested parentheses, such as ( ( a + b ) * c )
• the expression in the innermost set of parentheses (a + b in this case) is evaluated first.
Rules of Operator Precedence
• Java applies the operators in arithmetic expressions in a precise sequence determined by
the following rules of operator precedence, which are generally the same as those followed in
algebra:
1. Multiplication, division and remainder operations are applied first. If an expression contains
several such operations, the operators are applied from left to right. Multiplication, division and
remainder operators have the same level of precedence.
2. Addition and subtraction operations are applied next. If an expression contains several such
operations, the operators are applied from left to right. Addition and subtraction operators have the
same level of precedence.
Sample Algebraic and Java Expressions
The following is an example of an arithmetic mean (average) of five terms:
• Algebra:
a+b+c+d+e
m = ---------------------------
5
• Java: m = ( a + b + c + d + e ) / 5;
Decision Making: Equality and Relational Operators
• A condition is an expression that can be either true or false.
• Conditions in if statements can be formed by using the equality operators (== and !=) and relational
operators (>, <, >= and <=) summarized in Fig.
• The equality operators associate from left to right. The relational operators all have the same level of
precedence and also associate from left to right.

You might also like