Basics Java
Basics Java
Features of OOP:
Inheritance: a subclass extends a superclass; the objects of a subclass
inherit features of the superclass and can redefine them or add new
features.
Event-driven programs: the program simulates asynchronous handling of
events; methods are called automatically in response to events.
OOP Benefits
• Facilitates team development
• Easier to reuse software components and
write reusable software
• Easier GUI (Graphical User Interface) and
multimedia programming
Java systems contain
Environment
Language
APIs
Class libraries
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
Prog ram is c reated in
Pha se 1 Editor the editor and sto red
Disk
on d isk.
Compiler c rea te s
Pha se 2 bytec odes and stores
Compiler Disk the m on disk.
Primary
Memory
Pha se 3 Class Lo ad er
Primary
Memory
Pha se 4 Bytec ode Ve rifier Byte code verifier
confirms that a ll
bytec odes are valid
and do not violate
J ava ’s sec urity
restrictions.
..
..
..
Primary
Memory Interpreter read s
Pha se 5 Interp reter bytec odes and
translates them into a
la nguag e that the
computer can
und ersta nd, possib ly
storing d ata values a s
.. the program executes.
..
..
A Java compiler converts Java source code into instructions for the
Java Virtual Machine.
These instructions, called bytecodes, are the same for any
computer / operating system.
A CPU-specific Java interpreter interprets bytecodes on a particular
computer.
Editor Compiler
Hello.java Hello.class
Interpreter Interpreter
Hello,
World!
Benefits of two phase execution:
• Platform-independent
Ramesh Tendulkar
GUI Applications
Menus
Clickable
panel
Buttons Slider
HelloGui.java
import java.awt.*;
import javax.swing.*;
GUI libraries
// Welcome1.java
// A first program in Java.
• Reserved Words
– In Java a number of words are reserved for a special
purpose.
– Reserved words use only lowercase letters.
– Reserved words include:
• primitive data types: int, double, char, boolean, etc.
• storage modifiers: public, private, static, final, etc.
• control statements: if, else, switch, while, for, etc.
• built-in constants: true, false, null
– There are about 50 reserved words total.
Programmer-Defined Names
int count;
double x, y; Name(s)
Type JButton go;
Walker amy;
String firstName;
Variables (cont’d)
count = 5;
x = 0;
go = new JButton("Go");
firstName = args[0];
Variables (cont’d)
int count = 5;
JButton go = new JButton("Go");
String firstName = args[0];
Variables: Scope
{
Local variable declared
}
}
...
}
Variables (cont’d)
• Common mistakes:
• int • byte
• double • short
• char • long
• boolean • float
Used in
Java Methods
Strings
new line
tab
• Operators: +, -, /, * , %
• The precedence of operators and parentheses is the
same as in algebra
• m % n means the remainder when m is divided by
n (for example, 17 % 5 is 2; 2 % 8 is 2)
• % has the same rank as / and *
• Same-rank binary operators are performed in order
from left to right
Displaying Multiple Lines of Text with a Single Statement
Escape characters
– Backslash ( \ )
– Indicates special characters be output
• Display
– Most Java applications use windows or a dialog box
• We have used command window
– Class JOptionPane allows us to use dialog boxes
• Packages
– Set of predefined classes for us to use
– Groups of related classes called packages
• Group of all packages known as Java class library or Java
applications programming interface (Java API)
– JOptionPane is in the javax.swing package
• Package has classes for using Graphical User Interfaces
(GUIs)
1 1 // Fig.
Welcome4.java
2.6: Welcome4.java
2 // Printing multiple lines in a dialog box
3 2 // Printing multiple lines in a dialog box
4 3 // Javajavax.swing.JOptionPane;
import extension packages // import class JOptionPane
5 import javax.swing.JOptionPane; // import class JOptionPane
6 4
7 public class Welcome4 {
8 5 public class Welcome4 {
9 // main method begins execution of Java application
6 public static void main( String args] )
10 public static void main( String args[] )
11 7 {
{
12 JOptionPane.showMessageDialog(
13 8 JOptionPane.showMessageDialog(
null, "Welcome\nto\nJava\nProgramming!" );
14
15 9 null, "Welcome\nto\nJava\nProgramming!"
System.exit( 0 ); // terminate application);
1610
17 } // end method main
1811 System.exit( 0 ); // terminate the program
19 } // end class Welcome4
12 }
1 // Fig. 2.9: Addition.java
2 // An addition program.
3
4 // Java extension packages
5 import javax.swing.JOptionPane; // import class JOptionPane
6
7 public class Addition {
8
Declare variables: name and data type.
Input first integer as a String, assign
9 // main method begins execution of Java application
10 to firstNumber.
public static void main( String args[] )
11 {
12 String firstNumber; // first string entered by user
13 String secondNumber; // second string entered by user
14 int number1; // first number to add
15 int number2; // second number to add
16 int sum; // sum of number1 and number2
17
18 // read in first number from user as a String
19 firstNumber =
20 JOptionPane.showInputDialog( "Enter first integer" );
21
22 // read in second number from user as a String
23 secondNumber = Convert strings to integers.
24 JOptionPane.showInputDialog( "Enter second integer" );
25
26 Add,
// convert numbers from type String to place
type result
int in sum.
27 number1 = Integer.parseInt( firstNumber );
28 number2 = Integer.parseInt( secondNumber );
29
30 // add the numbers
31 sum = number1 + number2;
32
33 // display the results
34 JOptionPane.showMessageDialog(
35 null, "The sum is " + sum, "Results",
36 JOptionPane.PLAIN_MESSAGE );
37
38 System.exit( 0 ); // terminate application
39
40 } // end method main
41
42 } // end class Addition
34 JOptionPane.showMessageDialog(
35 null, "The sum is " + sum, "Results",
36 JOptionPane.PLAIN_MESSAGE );
JOptionPane.PLAIN_MESSAGE no icon
Displays a dialog that simply contains a
message, with no icon.
Fig. 2.12 JOptionPane constants for message dialogs.
Primitive Data Types (size)
Type Size in bits Values Standard
boolean 8 true or false
char 16 ’\u0000’ to ’\uFFFF’ (ISO Unicode character set)
(0 to 65535)
byte 8 –128 to +127
(–27 to 27 – 1)
short 16 –32,768 to +32,767
(–215 to 215 – 1)
int 32 –2,147,483,648 to +2,147,483,647
(–231 to 231 – 1)
long 64 –9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
(–263 to 263 – 1)
float 32 Negative range: (IEEE 754 floating point)
–3.4028234663852886E+38 to
–1.40129846432481707e–45
Positive range:
1.40129846432481707e–45 to
3.4028234663852886E+38
double 64 Negative range: (IEEE 754 floating point)
–1.7976931348623157E+308 to
–4.94065645841246544e–324
Positive range:
4.94065645841246544e–324 to
1.7976931348623157E+308
Fig. 4.16 The Java primitive data types.
Reading Data from Keyboard
• Console input is by using Scanner that is attached to System.in
/**
@Author ………
*/
import java.util.*;
public class InputTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// get first input
System.out.print("What is your name? ");
String name = in.nextLine();
// get second input
System.out.print("How old are you? ");
int age = in.nextInt();
// display output on console
System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
}
}
Functions Defined in Scanner
• java.util.Scanner
– Scanner(InputStream in)
– String nextLine()
– String next()
– int nextInt, double nextDouble()
– boolean hasNext()
– boolean hasNextInt()
– boolean hasNextDouble()
• System.out.printf();
Control Statements
if ( <condition> ) if ( <condition> )
{ {
< statements > < statements >
} }
else
{
< other statements > else clause
} is optional
boolean Data Type
is equal to
is NOT
equal to
Relational Operators (cont’d)
May be
false!
Logical Operators
&&, ||, !
and
or
not
Logical Operators (cont’d)
! (p && q) == ( !p || !q )
! (p || q) == ( !p && !q )
• Example:
if ( ! ( x => -10 && x <= 10 ) ) ...
if ( x < -10 || x > 10 ) ...
Easier to read
Ranks of Operators
Highest
! -(unary) ++ -- (cast)
* / %
+ -
< <= > >= == !=
&&
||
Lowest Easier to read
if ("forward".equals(cmd))
{
if (slide >= numSlides)
beep.play();
else
slide++;
}
else
{
if (slide <= 1)
beep.play();
else
slide--;
}
if-else-if
if (drinkSize.equals(”Large"))
{
price += 1.39;
}
else if (drinkSize.equals("Medium"))
{
price += 1.19;
}
else // if "Small" drink size
{
price += 0.99;
}
The switch
switch (expression)
Statement {
case value1:
...
break;
switch
case case value2:
default ... Don’t
break break; forget
...
... breaks!
Reserved words default:
...
break;
}
The switch Statement (cont’d)
switch (num)
{
case 1:
case 2:
System.out.println (“Is Java technology Better");
break;
case 3:
...
}
enum Data Types
• Example:
while (input.hasNext())
System.out.println (input.next());
Changes the
state of input
Loop Invariants
int n = 0, p = 1;
while (p < x) Loop invariant:
{ p = 2n
p *= 2;
n++;
}
...
The for Loop
• Example:
• Example: n! = 1 * 2 * ... * n
/**
* Returns 1 * 2 * ... * n, if n >= 1 (and 1 otherwise)
*/
public static long factorial (int n)
{
long f = 1;
return f;
}
The do-while Loop
String str;
do
{
str = file.readLine();
...
} while (str != null);
The do-while Loop (cont’d)
• Example:
int d = n - 1;
while (d > 0)
{
if (n % d == 0)
break;
d--;
}
return -1;
}
// Class average program with counter-controlled repetition.
import javax.swing.JOptionPane;
public class Average1 {
public static void main( String args[] )
{
int total, gradeCounter, gradeValue, average;
String grade;
// Initialization Phase
total = 0; // clear total
gradeCounter = 1; // prepare to loop
while ( gradeCounter <= 10 ) { // loop 10 times
// prompt for input and read grade from user
grade = JOptionPane.showInputDialog("Enter integer grade: " );
// convert grade from a String to an integer
gradeValue = Integer.parseInt( grade );
total = total + gradeValue;
gradeCounter = gradeCounter + 1;
}
// Termination Phase
average = total / 10; // perform integer division
// display average of exam grades
JOptionPane.showMessageDialog( null,
• "Class average is " + average, "Class Average",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 ); // terminate the program
} // end method main
} // end class Average1
Lab Assignment
To find the first four perfect numbers.
• A perfect number is a positive integer equal to the sum of all its divisors (including 1 but
excluding the number itself). For example:
28 = 1 + 2 + 4 + 7 + 14