Document #2: Prepared by: Dr. Khalid A. Darabkeh Sun Certified Programmer for Java 2 Platform Oracle Java Developer Certified Trainer Oracle Database Administrator Certified Associate

How to create, compile, and run a Java class? Class members: 9 Data (variables, fields, or attributes) 9 Methods (functions, or operations) Comments in Java (like C/C++): 9 // : for a line 9 /* */: for multi-lines Don’t forget: Java is a case-sensitive language Programm#1: public class MainClass { public static void main (String [] args) { System.out.println("Welcome to Java Programming"); } } Compilation command: javac MainClass.java Run-time command: java MainClass Output: Welcome to Java Programming Programm#2: public class MainClass { public static void main (String [] args) { System.out.println(args[0]); 1

} } Compilation command: javac MainClass.java Run-time command: java MainClass Welcome to Java Programming Output: Welcome

Programm#3: public class MainClass { public static void main (String [] args) { System.out.print(args[0]+ " "); System.out.print(args[1] + " "); System.out.print(args[2] + " "); System.out.println(args[3]); } } Compilation command: javac MainClass.java Run-time command: java MainClass Welcome to Java Programming Output: Welcome to Java Programming Programm#4: public class MainClass { public static void main (String [] args) { System.out.print(args[0]); } } Compilation command: javac MainClass.java Run-time command: java MainClass "Welcome to Java Programming" Output: Welcome to Java Programming

2

How to create an object? The object is an instance of a class Object members: 9 States 9 Behaviors

Programm#5: public class MainClass { public static void main (String [] args) { Demo1 ref; ref = new Demo1(); // or Demo1 ref= new Demo1(); in a line System.out.println(ref.i); System.out.println(ref.method1(2,3)); int h = ref.method1(5,6); System.out.println(h); ref.method2(5); // System.out.println(ref.method2(3)); ERROR } } class Demo1 { int i =5; int method1(int m, int k) { k = i+ (m*k); return k; // or return i+ (m*k); without declaring variable k } void method2(int m) { int p = m*i; System.out.println(p); }

3

}

Programm#6: public class MainClass { public static void main (String [] args) { Demo2 ref2=new Demo2(); int k=ref2.ref1.i+(ref2.ref1.i*4); System.out.println("The value of k is "+k); } } class Demo1 { int i=33; int j=12; } class Demo2 { int i=14; int j=66; Demo1 ref1=new Demo1(); } Compilation command: javac MainClass.java Run-time command: java MainClass Output: The value of k is 165

Source Files: All java source files must end with the .java extension. A source file must contain at most one top-level public class definition (i.e. no more than a public class in a certain

4

source file). If a public class is present, the class name should match the unextended filename. There are three top-level elements that may appear in a file. None of these elements is required. If they are presented, then they must appear in the following order: 9 Package declaration 9 Import statements 9 Class definitions Programm#7: public class MainClass { } class Demo1 { public static void main (String [] args) { System.out.println("Welcome to Java Programming"); } } Compilation command: javac MainClass.java Run-time command: java MainClass Output: java.lang.NoSuchMethodError: main (Exception in thread "main") Programm#8: public class MainClass { public static void main (String [] args) { System.out.println("Welcome to Java Programming"); } } public class Demo1 {

}

5

Compilation command: javac MainClass.java class Demo1 is public, should be declared in a file named Demo1.java Run-time command: Output: Programm#9 (No definition for a public class) class MainClass { public static void main (String [] args) { System.out.println("Welcome to Java Programming"); } } class Demo1 {

} Compilation command: javac MainClass.java Run-time command: java MainClass Output: Welcome to Java Programming

Java Syntax and semantic: A programming language is a set of rules, symbols, and special words used to construct a program. A language is defined by both syntax (grammar or valid statements) and semantic (meaning)

Identifiers: An identifier is a word used by a programmer to name a package, class, method, field (variable), or label. Notes: 9 Keywords and reserved words can not be used as identifiers 9 An identifier must begin with a letter, a dollar sign ($), or an underscore (_) 9 Subsequent characters can be letters, dollar signs, underscores, or digits.

6

Examples: 9 9 9 9 9 9 9 9 9

30seconds : invalid identifier: identifiers can not begin with a digit High level: invalid identifier: blanks (spaces) are not allowed in identifiers High-level: invalid identifier: special symbol High!level: invalid identifier: special symbol High?level: invalid identifier: special symbol High_level: valid identifier High$level: valid identifier $High$level: valid identifier _High$level: valid identifier

Words that Java supplies: Keywords A word that has a specific pre-defined meaning in Java is called keyword. The listed below are Java keywords and reserved words. Words that have no meaning to the java compiler but may not be used as identifiers are called reserved words such as goto, const, true, and false (literal boolean values). abstract Const boolean break byte case else if

class assert continue default do double goto new

extends strictfp final finally float for native static

implements import instanceof int interface long short transient

null package private protected public return throws

true super switch synchronized this throw char

false try void volatile while catch enum

Primitive Data types A primitive is a simple non-object data types that represents a single value. Java’s primitive data types are: Type boolean

# of bits 8

Minimum Range Unsigned

char byte short int long float double

16 8 16 32 64 32 64

Unsigned -27 -215 -231 -263 +/-1.40239846-45 +/-4.94065645841246544-324

7

Maximum Range Just take the values true and false Range: 0- (216-1) 27-1 215-1 231-1 263-1 +/-3.40282347+38 +/-1.79769313486231460+308

Notes: 9 Java characters are in Unicode, which is a 16-bit encoding. If the most significant nine bits of a char are all 0, then the encoding is the same as seven-bit ASCII. 9 These types conform to the IEEE 754 specifications.

Literals: A literal is a value that can be assigned to a primitive or string variable or passed as an argument to a method call.

¾ boolean literals: (just true or false) ¾ Integral literals: (may be expressed in decimal, octal, and hexadecimal). The default is decimal. To indicate octal, prefix the literal with 0. To indicate hexadecimal, prefix the literal with 0x (or 0X). The hex digits may be upper/lowercase. By default, an integral literal is a 32-bit value. To indicate a long (64-bit) literal, append the suffix L (may be lowercase) to the literal expression.

¾ Char literals: A char literal can be expressed as follows: 9 char c = ‘f’; Another way to express a character literal is as four Unicode hexadecimal digits, preceded by \u like: 9 char f1=’\u6789’; Java also supports the following escape sequences: 9 9 9 9 9 9 9 9

‘\n’ : for new line ‘\r’ : for return ‘\t’ : for tab ‘\b’ : for backspace ‘\f’ : for formfeed ‘ \’ ’ : for single quote ‘ \” ’ : for double quotes ‘ \\ ’ : for backslash

8

¾ Floating-point literals: To interpret any floating point literal, a numerical value must contain one of the following: 1. 2. 3. 4.

Decimal point The letter E/e, indicating scientific notations: 3.45E+12 The suffix F/f, indicating a 32-bit float literal: 3.556F The suffix D/d, indicating a 64-bit float literal: 3556D

A floating-point literal with no F or D suffix defaults to a 64-bit double literal.

¾ String literals: A string literal is a text enclosed in double quotes. For example, 9 String s1= “Characters in strings are 16-bit Unicode”

Programm#10: public class MainClass { public static void main (String [] args) { boolean b= true; char r1='c'; char r2='\u5467'; byte b1=12; short s1=222; int i1=4444; long l1=55555; float f1=38883.4F; double d1=44354667.55667D; String str1="Welcome to Chapter 2 of Object-Oriented Course"; String str2="Welcome"+'\n'+"To"+'\t'+'\"'+"JAVA"+'\"'; System.out.print(b+" "); System.out.print('\n'); System.out.print(r1+ " ");

9

System.out.print(r2+ " "); System.out.print(b1+ " "); System.out.print(s1+ " "); System.out.print(i1+ " "); System.out.print(l1+ " "); System.out.print(f1+ " "); System.out.print(d1+ " "); System.out.println(str1); System.out.print(str2); } } Output: true c ? 12 222 4444 55555 38883.4 4.435466755667E7 Welcome to Chapter 2 of O bject-Oriented Course Welcome To "JAVA" Programm#11: public class MainClass { public static void main (String [] args) { /* long l1=5555555555; Compilation Error: integer number too large: 5555555555 Solution: long l1=5555555555 L; */ /* float f1=38883.4; Compilation Error: possible loss of precision found : double Solution: float f1=38883.4 F; */ double d1=44354667.55667; String str1="Welcome to \" JAVA PROGRAMMING \" "; System.out.println(str1); } }

10

Output: Welcome to " JAVA PROGRAMMING " Note about the main() method: It is a requirement for the main method to be declared as a static so that is may be executed without the necessity of constructing an instance of the corresponding class. However, to avoid run-time error (or exception), the main method inside the class that has the same file name should be public. Programm#12:

public class MainClass { public static void main (String [] args) { System.out.println("Welcome to the main of class: MainClass"); Demo1.main(null); // or Demo1 ref1=new Demo1(); ref1.main(null); } } class Demo1 { public static void main (String [] args) { System.out.println("Welcome to the main of class: Demo1"); } } Output: Welcome to the main of class: MainClass Welcome to the main of class: Demo1 Welcome to the main of class: Demo1

11

Note: java.lang package is imported by defaults (i.e. you don't have to import this package)

System: Class System is a subclass of Object class: java.lang.Object | +--java.lang.System

It has the following important fields: 9 static PrintStream out; (The "standard" output stream) 9 static InputStream in; (The "standard" input stream) PrintStream class has the following important methods: void void void void void void void void void

print(boolean b) print(char c) print(char[] s) print(double d) print(float f) print(int i) print(long l) print(Object obj) print(String s)

void void void void void void void void void void

println() println(boolean x) println(char x) println(char[] x) println(double x) println(float x) println(int x) println(long x) println(Object x) println(String x)

How we can read inputs during the flow of program? There are three ways: 1. Using System.in 2. Using Scanner class found in java.util package 3. Using JOptionPane class found in javax.swing package

12

Programm#13: import java.io.IOException; public class MainClass { public static void main (String [] args) throws IOException { int i=System.in.read(); System.out.println(i); // if you insert a --> Output = 97 // if you insert b --> Output = 98 // if you insert 1 --> Output = 49 // if you insert 2 --> Output = 50 // if you insert 22 --> Output = 50 // if you insert 2222 --> Output = 50 } }

Class Scanner java.lang.Object java.util.Scanner

Important Methods: boolean double int long

nextBoolean() nextDouble() nextInt() nextLong()

byte float

String short

13

nextByte() nextFloat() nextLine() nextShort()

Programm#14: import java.util.Scanner; public class MainClass { public static void main (String [] args) { Scanner sc=new Scanner(System.in); int i = sc.nextInt(); System.out.println(i); String ii = sc.nextLine(); System.out.println(ii); } } input: 1234 Welcome to "Java Programming" output: 1234 Welcome to "Java Programming"

Class JOptionPane java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent

javax.swing.JOptionPane Important (static) Methods: 9 showMessageDialog 9 showInputDialog Programm#15: import javax.swing.JOptionPane; public class MainClass { public static void main (String [] args) { 14

JOptionPane.showMessageDialog(null,"Welcome to \" JAVA \""); String str=JOptionPane.showInputDialog("Enter Your Name"); String gr1=JOptionPane.showInputDialog("Enter CPE 101 Grade "); String gr2=JOptionPane.showInputDialog("Enter CPE 232 Grade"); String gr3=JOptionPane.showInputDialog("Enter CPE 332 Grade"); int g1=Integer.parseInt(gr1); /* or int g1=Integer.parseInt(JOptionPane.showInputDialog("Enter CPE 101 Grade")); without the need to declare variable gr1 */ int g2=Integer.parseInt(gr2); int g3=Integer.parseInt(gr3); int average=(g1+g2+g3)/3; float aver=(g1+g2+g3)/3F; // or double aver1=(g1+g2+g3)/3.0; JOptionPane.showMessageDialog(null, str+", Your Integer Average = "+average+" and Your Real Average = "+aver); } } Note: int double short boolean

Integer.parseInt(String s) Double.parseDouble ( String s) Short.parseShort ( String s) Boolean.getBoolean ( String name)

15

byte float long

Byte.parseByte ( String s) Float.parseFloat ( String s) Long.parseLong ( String s)