Chapter1_Introduction_Java_2024
Chapter1_Introduction_Java_2024
3
Java Virtual Machine (JVM)
◦ The compiled code is executed by a JVM and not a real machine.
◦ Java code to be compiled just once but still be able to
execute on multiple diverse machine or platforms.
Java Standard Edition (Java SE)
◦ Development platform that enable developers to create secure,
portable, high-performance applications for the widest range of
computing platforms
4
Java Runtime Environment (JRE)
◦ Implementation of a JVM. It loads the classes, defines and
accesses JVM memory, connects with native code etc.
◦ Includes the Java binaries and classes, which are required to
execute your Java code. It excludes the tools that are used to
develop Java programs, like a compiler or a debugger.
For Java programming, you’d need a JDK.
5
1. Write it.
◦ code or source code: The set of instructions in a program.
2. Compile it.
• compile: Translate a program from one language to another.
◦ byte code: The Java compiler converts your code into a format named byte code
that runs on many computer types.
7
public class name { class: a program
public static void main(String[] args) {
statement;
statement;
... method: a named group
statement;
}
of statements
}
statement: a command to be executed
8
A statement that prints a line of output on the console.
◦ pronounced "print-linn"
◦ sometimes called a "println statement" for short
• System.out.println();
Prints a blank line of output.
You must give your program a name.
◦ public class MyNewCourse{
◦ Naming convention: capitalize each word (e.g. MyClassName)
◦ Your program's file must match exactly (MyNewCourse.java)
includes capitalization (Java is "case-sensitive")
10
Identifier: A name given to an item in your
program.
◦ must start with a letter or _ or $
◦ subsequent characters can be any of those or
a number
legal: _myName TheCure ANSWER_IS_42 $bling$
illegal: me+u 49ers side-swipe Ph.D's
11
keyword: An identifier that you cannot use because it already
has a reserved meaning in Java.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized
12
syntax: The set of legal structures and commands that can be used in a
particular language.
◦ Every basic Java statement ends with a semicolon ;
◦ The contents of a class or method occur between { and }
13
1 public class Hello {
2 pooblic static void main(String[] args) {
3 System.owt.println("Hello, world!")_
4 }
5 }
Compiler output:
Hello.java:2: <identifier> expected
pooblic static void main(String[] args) {
^
Hello.java:3: ';' expected
}
^
2 errors
◦ The compiler shows the line number where it found the error.
◦ The error messages can be tough to understand!
14
string: A sequence of characters to be printed.
◦ Starts and ends with a " quote " character.
The quotes do not appear in the output.
◦ Examples:
"hello"
"This is a string. It's very long!"
Restrictions:
◦ May not span multiple lines.
"This is not
a legal String."
◦ May not contain a " character.
"This is not a "legal" String either."
15
escape sequence: A special sequence of characters used to
represent certain special characters in a string.
\t tab character
\n new line character
\" quotation mark character
\\ backslash character
◦ Example:
System.out.println("\\hello\nhow\tare \"you\"?\\\\");
◦ Output:
\hello
how are "you"?\\
16
comment: A note written in source code by the programmer
to describe or clarify the code.
◦ Comments are not executed when your program runs.
Syntax:
// comment text, on one line
or,
/* comment text; may span multiple lines */
Examples:
// This is a one-line comment.
/* This is a very long
multi-line comment. */
17
Where to place comments:
◦ at the top of each file (a "comment header")
◦ at the start of every method (seen later)
◦ to explain complex pieces of code
18
/* Junior Student, IT320, Fall 2022
This program prints lyrics about ... something. */
// second verse
System.out.println("diggy said the boogy");
System.out.println("said up jump the boogy");
}
}
19
Java Development Kit (JDK)
• https://www.oracle.com/java/technologies/downloads/#jdk21-
windows
20
Input : any information that is needed by your program to complete its execution.
• taken from the command line
• read from a file
• etc.
Output : any information that the program must convey to the user.
• prints a string of characters as output.
• print graphics
• create sound
22
Using console •System.console().readLine()
Using scanner
•java.util.Scanner and System.in
class
24
java.util.Scanner and System.in
Steps
1.Use the System.in object to create a Scanner object.
2.Display a prompt to the user for the desired data.
3.Use the Scanner object to read a line of text from the
user.
4.Process the input received from the user.
25
26
• Finds and returns the next complete token
from the scanner.
27
• Returns a line of text as typed by the user.
• It advances the scanner past the current line
and returns the input that was skipped.
nextLine() • It reads input including space between the
words (that is, it reads till the end of line n).
• Once the input is read, nextLine() positions
the cursor in the next line.
28
Used to read different data types
◦ read string input
29
Used to read different data types
◦ read short input
30
Used to read different data types
◦ read long input
31
Used to read different data types
◦ read double input
32
◦ BufferedReader, InputStreamReader, and System.in
33
char : A primitive type representing single characters.
◦ A String is stored internally as an array of char
index 0 1 2 3 4 5
String s = "Ali G.";
value 'A' 'l' 'i' ' ' 'G' '.'
◦ Examples:
String name = "Marla Singer";
int x = 3;
int y = 5;
String point = "(" + x + ", " + y + ")";
string concatenation: Using + between a string and another value
to make a longer string.
"hello" + 42 is "hello42"
1 + "abc" + 2 is "1abc2"
"abc" + 1 + 2 is "abc12"
1 + 2 + "abc" is "3abc"
"abc" + 9 * 3 is "abc27"
"1" + 1 is "11"
4 - 1 + "abc" is "3abc"
◦ This code will compile, but it will not print the song.
Example:
double gpa = console.nextDouble();
if (gpa >= 2.0) {
System.out.println("Application accepted.");
}
Executes one block if a test is true, another if false
if (test) {
statement(s);
} else {
statement(s);
}
Example:
double gpa = console.nextDouble();
if (gpa >= 2.0) {
System.out.println("Welcome to Mars University!");
} else {
System.out.println("Application denied.");
}
if statements and for loops both use logical tests.
for (int i = 1; i <= 10; i++) { ...
if (i <= 10) { ...
◦ These are boolean expressions, seen in Ch. 5.
Example:
if (x > 0) {
System.out.println("Positive");
} else if (x < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
Tests can be combined using logical operators:
Operator Description Example Result
&& and (2 == 3) && (-1 < 5) false
|| or (2 == 3) || (-1 < 5) true
! not !(2 == 3) true
int x = 2;
x++; // x = x + 1;
// x now stores 3
double gpa = 2.5;
gpa--; // gpa = gpa - 1;
// gpa now stores 1.5
shortcuts to modify a variable's value
Shorthand Equivalent longer version
variable += value; variable = variable + value;
variable -= value; variable = variable - value;
variable *= value; variable = variable * value;
variable /= value; variable = variable / value;
variable %= value; variable = variable % value;
x += 3; // x = x + 3;
gpa -= 0.5; // gpa = gpa - 0.5;
number *= 2; // number = number * 2;
The update can use -- to make the loop count down.
◦ The test must say > instead of <
System.out.print("T-minus ");
for (int i = 10; i >= 1; i--) {
System.out.print(i + ", ");
}
System.out.println("blastoff!");
System.out.println("The end.");
◦ Output:
T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff!
The end.
If a programmer has to choose one among many alternatives, if...else can be used but, this makes
programming logic complex.
This type of problem can be handled using switch...case statement
Syntax:
switch (expression)
{
case constant1: Note the colon!
Instruction/s to be executed if expression equals to constant1;
break;
case constant2:
Instruction/s to be executed if expression equals to constant3;
break;
….
default:
Instruction/s to be executed if expression doesn't match to any cases;
}
57
Flowchart:
58
If the expression not matches any of the constant in case, then the default
statement is executed.
when the value in a case matches the test value, all of the actions in the
rest of the structure take place.
This can be corrected by use of the break statement.
59
1. Switch expression must be of integral Type ( int, char)
2. Switch case should have at most one default label
3. Default label is Optional
4. Default can be placed anywhere in the switch
5. Break Statement takes control out of the switch
6. Two or more cases may share one break statement
7. Nesting ( switch within switch ) is allowed.
8. Relational Operators are not allowed in Switch Statement.
9. Case Label must be unique
10. Case Labels must ends with Colon
11. break; is optional (but NEEDED! )
60
switch (ch) {
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
System.out.println("vowel“);
break;
default:
System.out.println("not a vowel“);
}
61