0% found this document useful (0 votes)
0 views61 pages

Chapter1_Introduction_Java_2024

The document provides an introduction to Java programming, covering topics such as object-oriented programming, Java applications, and exception handling. It explains the Java Development Kit (JDK), Java Virtual Machine (JVM), and various input/output methods. Additionally, it discusses syntax, data types, and control statements essential for writing Java programs.

Uploaded by

Rana Ben Fraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views61 pages

Chapter1_Introduction_Java_2024

The document provides an introduction to Java programming, covering topics such as object-oriented programming, Java applications, and exception handling. It explains the Java Development Kit (JDK), Java Virtual Machine (JVM), and various input/output methods. Additionally, it discusses syntax, data types, and control statements essential for writing Java programs.

Uploaded by

Rana Ben Fraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Tunis Business School

I. Introduction to Object oriented approach


II. Introduction to Java Applications
1. Input/Output &Data Types
2. Control Statements
3. Java Arrays & Methods
III. Object oriented programming (OOP)
1. Encapsulation
2. Inheritance & Polymorphism
3. Interfaces
IV. Generic Collections
V. Exception Handling
VI. Accessing Databases with JDBC
2
 Developed by James Gosling and his team at Sun
Microsystems (now a subsidiary of Oracle)
 Platform independence
◦ It was designed to run on multiple hosts without any
changes.
 Java’s Development Kit, or JDK,
◦ includes all tools, executables and binaries, which you can
use to compile, execute and debug your Java programs.

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.

3. Run (execute) it.


◦ output: The messages printed to the user by a program.
source code byte code output
compile run
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println();
System.out.println("This program produces");
System.out.println("four lines of output");
}
}
 Its output:
Hello, world!
This program produces
four lines of output

 console: Text box into which


the program's output is printed.

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

 Every executable Java program consists of a class,


◦ that contains a method named main,
 that contains the statements (commands) 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

 Two ways to use System.out.println :


• System.out.println("text");
Prints the given message as output.

• 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 }

 syntax error (compiler error): A problem in the structure of a program that


causes the compiler to fail.
◦ Missing semicolon
◦ Too many or too few { } braces
◦ Illegal identifier for class name
◦ Class and file names do not match
...

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

 Comments are useful for:


◦ Understanding larger, more complex programs.
◦ Multiple programmers working together, who must understand each
other's code.

18
/* Junior Student, IT320, Fall 2022
This program prints lyrics about ... something. */

public class BaWitDaBa {


public static void main(String[] args) {
// first verse
System.out.println("Bawitdaba");
System.out.println("da bang a dang diggy diggy");
System.out.println();

// 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

The NetBeans IDE


• https://netbeans.apache.org/download/

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

•BufferedReader, InputStreamReader, and


Using buffer System.in
23
◦ System.console().readLine()
◦ easy to use but does not work with IDE (such
Eclipse or Netbeans).
◦ You need to use command line window for it to
work
Example Execution

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.

next() • It can read the input only till the space.


• It can’t read two words separated by space.
• Also, next() places the cursor in the same
line after reading the input.

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

◦ read byte input

29
 Used to read different data types
◦ read short input

◦ read int input

30
 Used to read different data types
◦ read long input

◦ read float input

31
 Used to read different data types
◦ read double input

◦ read boolean 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' '.'

◦ It is legal to have variables, parameters, returns of type char


 surrounded with apostrophes: 'a' or '4' or '\n' or '\''
char letter = 'P';
System.out.println(letter); // P
System.out.println(letter + " Diddy"); // P Diddy
 string: A sequence of text characters.
String name = "text";
String name = expression;

◦ 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"

 Use + to print a string and an expression's value together.


◦ System.out.println("Grade: " + (95.1 + 71.9) / 2);
• Output: Grade: 83.5
 Relational operators such as < and == fail on objects.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
if (name == "Barney") {
System.out.println("I love you, you love me,");
System.out.println("We're a happy family!");
}

◦ This code will compile, but it will not print the song.

◦ == compares objects by references (seen later), so it often gives false


even when two Strings have the same letters.
 Objects are compared using a method named equals.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
if (name.equals("Barney")) {
System.out.println("I love you, you love me,");
System.out.println("We're a happy family!");
}

◦ Technically this is a method that returns a value of type boolean,


the type used in logical tests.
Method Description
equals(str) whether two strings contain the same characters
equalsIgnoreCase(str) whether two strings contain the same characters, ignoring upper vs. lower
case
startsWith(str) whether one contains other's characters at start
endsWith(str) whether one contains other's characters at end
contains(str) whether the given string is found within this one
String name = console.next();
if (name.startsWith("Prof")) {
System.out.println("When are your office hours?");
} else if (name.equalsIgnoreCase("STUART")) {
System.out.println("Let's talk about meta!");
}
Conditional Execution
Executes a block of statements only if a test is true
if (test) {
statement;
...
statement;
}

 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.

 Tests use relational operators:


Operator Meaning Example Value
== equals 1 + 1 == 2 true
!= does not equal 3.2 != 2.5 true
< less than 10 < 5 false
> greater than 10 > 5 true
<= less than or equal to 126 <= 100 false
>= greater than or equal to 5.0 >= 5.0 true
Chooses between outcomes using many tests
if (test) {
statement(s);
} else if (test) {
statement(s);
} else {
statement(s);
}

 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

 "Truth tables" for each, used with logical values p and q:


p q p && q p || q p !p
true true true true true false
true false false true false true
false true false true
false false false false
// Returns the larger of the two given integers.
public static int max(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}

 Methods can return different values using if/else


◦ Whichever path the code enters, it will return that value.
◦ Returning a value causes a method to immediately exit.
◦ All paths through the code must reach a return statement.
public static int max(int a, int b) {
if (a > b) {
return a;
}
// Error: not all paths return a value
}

 The following also does not compile:


public static int max(int a, int b) {
if (a > b) {
return a;
} else if (b >= a) {
return b;
}
}
◦ The compiler thinks if/else/if code might skip all paths, even
though mathematically it must choose one or the other.
public static int quadrant(double x, double y) {
if (x > 0 && y > 0) {
return 1;
} else if (x < 0 && y > 0) {
return 2;
} else if (x < 0 && y < 0) {
return 3;
} else if (x > 0 && y < 0) {
return 4;
} else { // at least one coordinate equals 0
return 0;
}
}
for (initialization; test; update) { header
statement;
statement;
... body
statement;
}

◦ Perform initialization once.


◦ Repeat the following:
 Check if the test is true. If not, stop.
 Execute the statements.
 Perform the update.
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}

 Tells Java what variable to use in the loop


◦ Performed once as the loop begins

◦ The variable is called a loop counter


 can use any name, not just i
 can start at any value, not just 1
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}

 Tests the loop counter variable against a limit


◦ Uses comparison operators:
< less than
<= less than or equal to
> greater than
>= greater than or equal to
shortcuts to increase or decrease a variable's value by 1
Shorthand Equivalent longer version
variable++; variable = variable + 1;
variable--; variable = variable - 1;

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

You might also like