Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
109 views

Chapter2 IntroductionToJava

This document provides an introduction to Java programming including: - Java can be used to create both standalone applications and applets for web browsers. It is object-oriented, cross-platform, and secure. - The basics of a Java program include classes, methods, and packages. A Java application contains a main method while an applet extends the JApplet class. - To create a Java program, code is written in a text editor and saved as a .java file. It is then compiled to bytecode and executed. Proper syntax, style, and program structure are important.

Uploaded by

Jiale Phan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views

Chapter2 IntroductionToJava

This document provides an introduction to Java programming including: - Java can be used to create both standalone applications and applets for web browsers. It is object-oriented, cross-platform, and secure. - The basics of a Java program include classes, methods, and packages. A Java application contains a main method while an applet extends the JApplet class. - To create a Java program, code is written in a text editor and saved as a .java file. It is then compiled to bytecode and executed. Proper syntax, style, and program structure are important.

Uploaded by

Jiale Phan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 62

Week 1

Introduction to Java

STIA1014 : Introduction To
Programming
Lecture Outlines

• Java Application
• Java Applet
• Java API packages
• Java Compiler and Interpreter
Learning Objectives

• To explain characteristics of Java program


• To identify types of Java programs
• To write simple Java programs
• To describe Java platform
• To differentiate between Java application,
Applet and Java API
Introduction

• Java is the Internet programming language


• It also can be used to develop standalone
applications
• Java is cross-platform, object-
oriented,network-based, and multimedia-
ready.
The History of Java
• 1991 - developed by James Gosling and
colleagues at Sun Microsystems. The
language, initially called Oak. Designed for
use in embedded consumer electronic
applications and intended to replace C++
• 1995- renamed Java designed for Internet
applications.
Characteristics of Java

–Simple – Architecture
–Object Oriented neutral
–Distributed – High-
–Interpreted performance
–Robust – Multithreaded
– Secure – Dynamic
– Portable
The Basics of Java Program

There are 2 types of Java programs:


• Applications
– Standalone programs
• Applets
– Programs designed to run on a Web
browser
The Basics of Java Program

• Applications
– single plain-looking terminal window
or
– with a graphical user interface (GUI) use
one or more windows filled with user
interface components such as buttons, text
input fields, and menus
The Basics of Java Program

GUI Application Single plain-looking Application


The Basics of Java Program

• Basic unit of a Java program – class


– Therefore application is a collection of one
or more classes.
– A class is a collection of methods and data
members
• One of the classes in a Java application
program must have only one method main.
Packages, Classes, Methods

• Package: A collection of related classes.

• Class: Consists of methods.

• Method: Designed to accomplish a specific


task.
Import Statement

• Used to import the components of a package


into a program.
• Reserved word.
• import java.io.*;
Imports the (components of the) package
java.io into the program.
• Primitive data types and the class String:
– Part of the Java language.
– Don’t need to be imported.
Creating a Java Application
Program
• Syntax of a class:

• Syntax of the main method:


Programming Style

• Know common syntax errors and rules.

• Use blanks appropriately.

• Use a semicolon as a statement terminator.

• Important to have well-documented code.

• Good practice to follow traditional rules for


naming identifiers.
Skeleton of Java Program

import statements if any


public class ClassName
{
declare named constants and/or stream objects

public static void main(String[] args) throws


IOException
{
variable declaration
executable statements
}
}
Skeleton of Java Program
import java.io.*; Example #1
/*This class is created to manipulate arithmetic operations*/
public class ArithmeticProgram {
static final int NUMBER = 12;
static Scanner in = new Scanner (System.in);
public static void main(String[] args) throws IOException {
int firstNum, secondNum;
firstNum=18;
System.out.println(“Enter an integer:”);
secondNum = in.nextInt();
System.out.println(“Value of firstNum:”+firstNum);
System.out.println(“Value of secondNum:”+secondNum);
firstNum=firstNum+NUMBER+2*secondNum;
System.out.println(“New value of firstNum:”+firstNum);
}
}
Skeleton of Java Program
/*This class is created to perform arithmetic operation*/
public class Count{ Example #2
private int num1,num2,addResult,multiplyResult; //list of attributes
public void setData(int n1, int n2){ //to assign a value to num1 and num2
num1 = n1;
num2 = n2;
}
//to perform addition between num1 and num2
public void performAddOperation(){
addResult = num1 + num2;
}
//to perform multiplication between num1 and num2
public void performMultiplyOperation(){
multiplyResult = num1 * num2;
}
//to display the result of addition and multiplication
public void displayResult(){
System.out.println(num1 + " * " + num2 + " = " + multiplyResult);
System.out.println(num1 + " +" + num2 + " = " + addResult);
}
}//end class
Skeleton of Java Program
/*This class is created to test/manipulate the Count class
Example #2
public class TestCount{
public static void main(String[]args){
Count count=new Count();//create an instance of the Count class
count.setData(12, 6);
count.performAddOperation();
count.performMultiplyOperation();
count.displayResult();
}//end main
}//end class

Output:

12 * 6 = 72
12 +6 = 18
How to use Java?

• Understand files and folders/directories


• Locate the Java compiler/ Install J2SE
• Set path & Java class path
• Write a simple program (later)
• Save your work
• Compile & run
• Use Dos Command Prompt or IDE
Creating a Java Program

1. Use any text editor to create or edit a Java


source code.
2. Save the file. Use the same class name.
For example class name: Count, file name
should be Count.java
3. Compile the program to translate the source
code into bytecode. If no syntax errors,
compiler will generate file named
Count.class
4. Execute the program.
DOS Command Window
An Integrated Development
Environment
Creating a Java Program
• Basic elements of a Java program include:
– The main method
– Reserved words
– Special symbols
– Identifiers
– Data types
– Expressions
– Input
– Output
– Statements
Creating a Java Program

• To create a Java application, it is important


to understand:
– Syntax rules.
– Semantic rules.
– How to manipulate strings and numbers.
– How to declare variables and named
constants.
– How to receive input and display output.
– Good programming style and form.
File Hello.java
1 public class Hello
2{
3 public static void main(String[] args)
4 {
5 // display a greeting in the console window
6 System.out.println("Hello, World!");
7 }
8}
Java Program Elements
• A Java program is made up of class
definitions.
• A class definition must contains a header
and a body.
• A class contains zero or more methods
• A method is a named section of code that
also has a header & body
– A method contains program statements
• Single-line (starts with //) and multi-line
(enclosed by /* and */) comments are used to
document the code
Java Program Structure
// comments about the class
public class Hello
{
class header

class body

//Comments can be placed almost anywhere

} 27
Java Program Structure
// comments about the class
public class MyProgram
{
// comments about the method

public static void main (String[] args)


{
method header
method body

} 28
Compiling and Running

 Type program into text editor


 Save (file name must be similar to class
name)
 Open Dos Window
 Change directory to saved file directory
 Compile into byte codes
javac Hello.java
 Execute byte codes
java Hello
Creating a Java Program
Create/modify source code

Source code

Compile source code


Syntax errors

Byte code

JVM Run byte code


Runtime errors or
Output
incorrect results
Applets
• Applet: a Java program that is embedded within a
Web page and executed by a Web browser
• is a program written in the JavaTM programming
language that can be included in an HTML page.
When you use a Java technology-enabled
browser to view a page that contains an applet,
the applet's code is transferred to your system
and executed by the browser's Java Virtual
Machine (JVM).
• Create an applet by extending the class JApplet.
• class JApplet is contained in package
javax.swing.
Applets
• A Java application is a stand-alone program with
a main method (like the ones we've seen so far)
• A Java applet is a program that is intended to be
transported over the Web and executed using a
web browser
• An applet also can be executed using the
appletviewer tool of the Java SDK
• An applet doesn't have a main method
• Instead, there are several special methods that
serve specific purposes
Applet Methods

• init method:

– Initializes variables.

– Gets data from user.

– Places various GUI components.

• paint method:

– Performs output.
Applets
• The paint method is executed automatically
whenever the applet’s contents are drawn
• The paint method accepts a parameter that is an
object of the Graphics class
• A Graphics object defines a graphics context on
which we can draw shapes and text
• The Graphics class has several methods for
drawing shapes
//********************************************************************
// Einstein.java Author: Lewis/Loftus
//
// Demonstrates a basic applet.
//********************************************************************

import javax.swing.JApplet;
import java.awt.*;

public class Einstein extends JApplet


{
//-----------------------------------------------------------------
// Draws a quotation by Albert Einstein among some shapes.
//-----------------------------------------------------------------
public void paint (Graphics page)
{
page.drawRect (50, 50, 40, 40); // square
page.drawRect (60, 80, 225, 30); // rectangle
page.drawOval (75, 65, 20, 20); // circle
page.drawLine (35, 60, 100, 120); // line

page.drawString ("Out of clutter, find simplicity.", 110, 70);


page.drawString ("-- Albert Einstein", 130, 100);
}
}
//********************************************************************
// Einstein.java Author: Lewis/Loftus
//
// Demonstrates a basic applet.
//********************************************************************

import javax.swing.JApplet;
import java.awt.*;

public class Einstein extends JApplet


{
//-----------------------------------------------------------------
// Draws a quotation by Albert Einstein among some shapes.
//-----------------------------------------------------------------
public void paint (Graphics page)
{
page.drawRect (50, 50, 40, 40); // square
page.drawRect (60, 80, 225, 30); // rectangle
page.drawOval (75, 65, 20, 20); // circle
page.drawLine (35, 60, 100, 120); // line

page.drawString ("Out of clutter, find simplicity.", 110, 70);


page.drawString ("-- Albert Einstein", 130, 100);
}
}
The HTML applet tag
• An applet is embedded into an HTML file using a tag that
references the bytecode file of the applet
• The bytecode version of the program is transported
across the web and executed by a Java interpreter that is
part of the browser

<html>
<head>
<title>The Einstein Applet</title>
</head>
<body>
<applet code="Einstein.class" width=350 height=175>
</applet>
</body>
</html>
Skeleton of a Java Applet

import java.awt.Graphics;
import javax.swing.JApplet;

public class WelcomeApplet extends JApplet


{

}
import java.awt.*;
import javax.swing.JApplet;
public class GrandWelcome extends JApplet{
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
g.setFont(new Font("Courier",Font.BOLD, 24));
g.drawString("Welcome to Hava
Programming",30,30);
}
}

<HTML>
<HEAD>
<TITLE>WELCOME</TITLE>
</HEAD>
<BODY>
<APPLET code = "GrandWelcome.class" width="440" height="50">
</APPLET>
</BODY>
</HTML>
Java Platform
• Platform is a hardware or software
environment to execute a program.
• It also can be defined as a combination of
operating system and hardware.
• The popular platform are Windows 2000,
Linux, Solaris, and MacOS.
• Java platform is different with other platform
because it is only a software to execute an
application on different hardware platform .
Java Platform
• It has 2 components :
– Java Virtual Machine (JVM)
– Java Application Programming Interface
(Java API)
• (source : Website http://java.sun.com).
Java Virtual Machine (JVM)
• Also called a "Java Interpreter"- Converts bytecode into
OS specific commands. In addition to governing the
execution of an application's bytecodes, JVM handles
related tasks such as managing the system's memory,
providing security against malicious code, and managing
multiple threads of program execution. JVM sits on top of
a native environment (OS) and allows for portability of
applications across various hardware as long as the
hardware has the JVM on it.
• JVM executes instructions that a Java compiler generates.
This run time environment, is embedded in various
products, such as web browsers, servers, and operating
systems.
java.sun.com/developer/onlineTraining/new2java/program
ming/learn/unravelingjava.html
Java Application Programming
Interface (API)
• The Java Application Programming Interface
(API) is prewritten code (predefined classes),
organized into packages of similar topics. For
instance, the Applet and AWT packages include
classes for creating fonts, menus, and buttons.
• There are 3 editions of the Java API:
– Java 2 Standard Edition (J2SE) : to develop client-
side standalone applications or applets.
– Java 2 Enterprise Edition (J2EE) : to develop
server-side applications. E.g. Java servlets and
JSP.
– Java 2 Micro Edition (J2ME) : to develop
applications for mobile devices.
Characters String
• A string literal is represented by putting
double quotes around the text
• Examples:
"This is a string literal."
"123 Main Street"
"X"

• Every character string is an object in Java,


defined by the String class
• Every string literal represents a String
object
The println() Method

• The System.out object represents a


destination (the monitor screen) to which we
can send output

System.out.println ("Whatever you are, be a good one.");

object method
name information provided to the method
(parameters)
The print() Method
• The System.out object provides another service
as well

• The print method is similar to the println


method, except that it does not advance to the
next line

• Therefore anything printed after a print


statement will appear on the same line

• See Countdown.java
//********************************************************************
// Countdown.java Author: Lewis/Loftus
//
// Demonstrates the difference between print and println.
//********************************************************************

public class Countdown


{
//-----------------------------------------------------------------
// Prints two lines of output representing a rocket countdown.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.print ("Three... ");
System.out.print ("Two... ");
System.out.print ("One... ");
System.out.print ("Zero... ");
System.out.println ("Liftoff!"); // appears on first output line
System.out.println ("Houston, we have a problem.");
}
}
Output
//********************************************************************
// Countdown.java Author: Lewis/Loftus
// Three... Two... One... Zero... Liftoff!
Houston,
// Demonstrates the we have between
difference a problem.
print and println.
//********************************************************************

public class Countdown


{
//-----------------------------------------------------------------
// Prints two lines of output representing a rocket countdown.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.print ("Three... ");
System.out.print ("Two... ");
System.out.print ("One... ");
System.out.print ("Zero... ");
System.out.println ("Liftoff!"); // appears on first output line
System.out.println ("Houston, we have a problem.");
}
}
The printf() Method

- To format output

- Usage (Syntax):
System.out.printf(formatString , items);

where
-formatString: a string with format specifiers
- items: list of data/variables to be displayed

Use printf() method in order to use the above


format. printf() method is only supported in JDK 5
and higher version.
Formatting Output
• Output of floating point values can look strange:
Price per liter: 1.21997
• To control the output appearance of numeric variables,
use formatted output tools such as:
a) System.out.printf(“%.2f”, price);
Price per liter: 1.22
b) System.out.printf(“%10.2f”, price);
Price per liter: 1.22

– The %10.2f is called a format specifier


Formatting Output
-Format specifier specifies how item should be displayed
-Frequently used format type specifiers
specifier output example
%d decimal integer 200
%f a float number 35.3404
%s a string “Java”
%c a character ‘T’
%b a boolean value true
%n line separator
%e exponential 1.23e+1
Formatting Output – E.g
String Concatenation
• The string concatenation operator (+) is used to
append one string to the end of another
"Peanut butter " + "and jelly"
• It can also be used to append a number to a
string
• A string literal cannot be broken across two lines
in a program
• See Facts.java
//********************************************************************
// Facts.java Author: Lewis/Loftus
//
// Demonstrates the use of the string concatenation operator and the
// automatic conversion of an integer to a string.
//********************************************************************

public class Facts


{
//-----------------------------------------------------------------
// Prints various facts.
//-----------------------------------------------------------------
public static void main (String[] args)
{
// Strings can be concatenated into one long string
System.out.println ("We present the following facts for your "
+ "extracurricular edification:");

System.out.println ();

// A string can contain numeric digits


System.out.println ("Letters in the Hawaiian alphabet: 12");

continue
continue

// A numeric value can be concatenated to a string


System.out.println ("Dialing code for Antarctica: " + 672);

System.out.println ("Year in which Leonardo da Vinci invented "


+ "the parachute: " + 1515);

System.out.println ("Speed of ketchup: " + 40 + " km per year");


}
}
Output
continue
We present the following facts for your extracurricular edification:
// A numeric value can be concatenated to a string
Letters in the Hawaiian alphabet:
System.out.println ("Dialing 12code for Antarctica: " + 672);
Dialing code for Antarctica: 672
Year in which Leonardo da
System.out.println Vinci in
("Year invented the parachute:
which Leonardo 1515
da Vinci invented "
Speed of ketchup: 40 km per year
+ "the parachute: " + 1515);

System.out.println ("Speed of ketchup: " + 40 + " km per year");


}
}
String Concatenation
• The + operator is also used for arithmetic addition
• The function that it performs depends on the type of the
information on which it operates
• If both operands are strings, or if one is a string and one
is a number, it performs string concatenation
• If both operands are numeric, it adds them
• The + operator is evaluated left to right, but parentheses
can be used to force the order
• See Addition.java
//********************************************************************
// Addition.java Author: Lewis/Loftus
//
// Demonstrates the difference between the addition and string
// concatenation operators.
//********************************************************************

public class Addition


{
//-----------------------------------------------------------------
// Concatenates and adds two numbers and prints the results.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("24 and 45 concatenated: " + 24 + 45);

System.out.println ("24 and 45 added: " + (24 + 45));


}
}
Output
//********************************************************************
// Addition.java Author: Lewis/Loftus
// 24 and 45 concatenated: 2445
24the
// Demonstrates and 45 added:
difference between69
the addition and string
// concatenation operators.
//********************************************************************

public class Addition


{
//-----------------------------------------------------------------
// Concatenates and adds two numbers and prints the results.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("24 and 45 concatenated: " + 24 + 45);

System.out.println ("24 and 45 added: " + (24 + 45));


}
}
Quick Check
What output is produced by the following?
System.out.println ("X: " + 25);
System.out.println ("Y: " + (15 + 50));
System.out.println ("Z: " + 300 + 50);
Quick Check
What output is produced by the following?
System.out.println ("X: " + 25);
System.out.println ("Y: " + (15 + 50));
System.out.println ("Z: " + 300 + 50);

X: 25
Y: 65
Z: 30050
Conclusion

Q & A Session

You might also like