You are on page 1of 59

Java History Basic Java Program Components Data Types Variables Operators Expressions Input / Output Escape Sequences

Program Style and Form

Relational Operators Logical / Boolean Operators Control Structures

Developed by James Gosling at Sun Microsystems. Introduced in 1995. Derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Originally named Oak after a tree outside the office of its developer. Used for general purpose business programs and interactive Web and Internet applications.

All source code is written in plain text files ending with the .java extension Source files are compiled into .class files by the javac compiler A .class file does not contain code that is native to your processor: contains bytecodes
Bytecodes: the machine language of the Java

Virtual Machine (JVM)

The java launcher tool then runs your application with an instance of the JVM.

JVM is available on many different operating systems.


The same .class files are capable of running on

Microsoft Windows, the Solaris Operating System (Solaris OS), Linux, or Mac OS.

Some Java Editors


JCreator LE / Pro NetBeans

Analyze the Problem Develop an Algorithm


Algorithm step-by-step problem solving process

in which a solution is arrived at in a finite amount of time.


Document the Program Write Code for the Program Run the Program Test the Results

Algorithm to find the perimeter and area of a rectangle:


Get the length of the rectangle. Get the width of the rectangle. Find the perimeter using the equation: perimeter = 2 * (length + width) Find the area using the equation: area = length * width

Define a class HelloWorld and store it into a file: HelloWorld.java:


public class HelloWorld { public static void main (String[] args) { System.out.println(Hello, World); } }

Compile HelloWorld.java
Output: HelloWorld.class

Run
Output: Hello, World

The word public is an access modifier. It defines as the circumstance under which a class can be accessed. class keyword means youre defining a class. All classes are enclosed with curly brackets {}. A class can contain any number of data items and methods. Public in the method header is an access modifier.

static means that that every member created for the class will have identical, unchanging main() method. void means that the method returns nothing. String [] args is an argument passed to main(). The String represents a java class that can be used to represent character strings. The variable args is used to hold any string that might be sent to the main(). All statements end with a semicolon.

JDK: C:\Program Files\Java\jdk1.6.0_17 Program: D:\Folder\ HelloWorld.java In command window:

C:\Documents and Settings\students>d: D:\>cd Folder D:\Folder>set path=C:\Program Files\Java\jdk1.6.0_17\bin; D:\Folder>set classpath=C:\Program Files\Java\jdk1.6.0_17\lib; D:\Folder>javac HelloWorld.java D:\Folder>java HelloWorld

File menu New Project Category: Java Project: Java Application Set name and location of the project Finish

File menu New Project Project Template: Basic Java Application Set Project Paths
Select Create new workspace

Finish

System.out
Standard output object Print to command window (i.e., MS-DOS prompt)

Displays line of text and advances cursor to the next line Argument inside parenthesis

Displays line of text with cursor remaining on printed line Argument inside parenthesis

Class JOptionPane allows us to use dialog boxes JOptionPane is in the javax.swing package
import javax.swing.JOptionPane;

or import javax.swing.*;

Call method showMessageDialog of class JOptionPane


Requires two arguments Multiple arguments separated by commas (,) For now, first argument always null Second argument is string to display

Example:

JOptionPane.showMessageDialog(null, "Welcome\nto\nJava\nProgramming!" );

Reads String from the user using JOptionPane.showInputDialog()

Example: JOptionPane.showInputDialog( "Enter first integer" );

import java.util.Scanner; Scanner input = new Scanner(System.in); int a; double x; String word; String line; System.out.print("Enter int, double, word, line: "); a = input.nextInt(); x = input.nextDouble(); word = input.next(); // returns a String up to next whitespace line = input.nextLine(); // returns rest of line & eats the '\n' System.out.println(a + ":" + x + ":" + word + ":" + line);

import java.io.DataInputStream; Methods: readChar() readDouble() readFloat() readInt() readLine()

Converts String argument into an integer (type int) Example:

String firstNumber; int number1; firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); number1 = Integer.parseInt( firstNumber );

Use showMessageDialog to display results "The sum is " + sum


Uses the operator + to "add" the string literal "The

sum is" and sum Concatenation of a String and another type Results in a new string

Example:

JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE );

Message dialog type JOptionPane.ERROR_MESSAGE

Icon

Description Displays a dialog that indicates an error to the user. Displays a dialog with an informational message to the user. The user can simply dismiss the dialog. Displays a dialog that warns the user of a potential problem. Displays a dialog that poses a question to the user. This dialog normally requires a response, such as clicking on a Yes or a No button.

JOptionPane.INFORMATION_MESSAGE

JOptionPane.WARNING_MESSAGE JOptionPane.QUESTION_MESSAGE

JOptionPane.PLAIN_MESSAGE

no icon

Displays a dialog that simply contains a message, with no icon.

can be downloaded from a Web server. run on your computer by Java-compatible Web browser, such as Microsoft Internet Explorer or Mozilla Firefox.

Define the kind or type of data values being stored or manipulated. Simple data types:
int float double char

A location in your computers memory in which you can store a value and from which you can later retrieve that value. Setting Aside Memory: When you define a variable in Java, you must specify what kind of variable it is. Defining a Variable: define its type, specify the variable name, followed by a semicolon

Could be combination of letters Cannot contain spaces Tell you what the variables are for Case sensitive Could not be reserved words

Assign a value to a variable by using the assignment operator (=).


Example: int number; number = 5;

Initialize variable at creation.


Example:
int length = 10, width = 8;

These operators manipulate integral and floating-point data types.


+ * / %

we want to modify the value of a variable by performing an operation on the value currently stored in that variable

Expression

Equivalent to

a+=10

a=a+10

a-=10
a*=10 a/=10 a%=10

a=a-10
a=a*10 a=a/10 a=a%10

+= -= *= /= %=

Pre-increment: ++variable Post-increment: variable++ Pre-decrement: --variable Post-decrement: variable-Example: x = 5; y = ++x;

x = 5; y = x++;

\n newline \t tab \b backspace \r return \\ - backslash \ single quotation \ double quotation

Anything that evaluates a value.


Example: 2 + 3 * 5 (integral expression) 3 + 12.8 * 17.5 - 34.50 (floating point expression)

Mixed Expressions: has operands of different data types.


Example: 2 + 3.5 6 / 4 + 3.9 5.4 * 2 13.6 + 18 / 2

Logical / Boolean Expressions: has a value of either true or false. Example: I>J 5.9 <= 7.5

Syntax tells what is legal and what is not legal. Errors in syntax are detected during compilation
Example: int x; int y double z; y = w + x;

Use of Semicolons, Braces and Commas Semantics set of rules that gives meaning to a language. Example: 2 + 3* 5 and (2+3)*5

Form and Style Documentation


Comments explain the purpose of the program,

identify who wrote it and explain the purpose of particular statements. 2 Types:
Line Comment (//) Multiline / Block Comment (/* */)

Operators used for comparison of numbers or values of variables.


== is equal to <

is less than > is greater than <= is less than or equal to >= is greater than or equal to != is not equal to

Expression

Value

8 < 15
6 != 6 7 == 7 4 < (3 + 2)

True
False True True

= (assignment operator) assigns the value to a variable. Example: number = 10; == (equality operator) determines whether two expressions are equal. Example: a == b;

Combines logical expressions. Operator ! && || Description Not And Or

Expression True False


Example: Expression ! (A > B) ! (6 <= 7)

!(Expression) False True


Value True False

Expression1

Expression2

Expression1&& Expression2

True True False False

True False True False

True False False False

Expression (14 >= 5) && (A < B) (24 >= 35) && (A < B)

Value True False

Expression1

Expression2

Expression1|| Expression2

True True False False

True False True False

True True True False

Expression (14 >= 5) || (A < B) (24 >= 35) || (A > B) (A <= a) || (7 !=7)

Value True False True

Controls flow of program.


Selection if, switch Repetition / Loop for, while, do-while

One-way selection Example: if(score >=90) { System.out.println(grade is A); }

Two-way selection: if-else Example: if (score>=60) { System.out.println(Passed.); } else { System.out.println(Failed.); }

Multiple Selections: Nested if Example: if (score>=90) { System.out.println(grade is A.); } else { if(score>=80) { System.out.println(grade is B.); } else { System.out.println(grade is below 80.); } }

Multiple Selections: Extended if Example: if (score>=90) { System.out.println(grade is A.); } else if(score>=80) { System.out.println(grade is B.); } else { System.out.println (grade is below 80.); }

Example: switch(num) { case 1: {

System.out.println(The number is 1.);


break;
} case 2: {

System.out.println(The number is 2.);


break;
} default: {

System.out.println(Invalid.);
} }

Pretest Loop while, for Posttest Loop do-while

Example: //Prints the sum of numbers less than 10. a = 0; while (a < 10) { a = a + 1; } System.out.println(a);

Example: a=1; while(a<0) { num=5; System.out.println(num); a=a+10; } System.out.println(a);

Example: //Prints first 10 positive integers for (i=1; i<=10; i++) { System.out.println(i); }

Example: i=0; do { System.out.println(i); i=i+5; } while(i<=20);

You might also like