Introduction to Java Programming Language

Download Report

Transcript Introduction to Java Programming Language

Introduction to Java
Programming Language
Ivan Devosa
András Csallner Erik
SZTE JGYPK
A very short history of Java

In 1991 James Gosling and Patrick Naughton
were responsible for the Java language project for
use in set-top boxes. Java was initially intended for
interactive television but the target technology
was not ready at that point. The language was first
called Oak after an oak tree outside Gosling's
office, but since that name was already
copyrighted it was renamed as Java. Gosling
intended to put into practice a virtual machine
and a programming language similar to C/C++.
The plan of "Write Once, Run Anywhere"
(WORA), provides no-cost run-times on popular
platforms.

The first public implementation of Java
was in 1995 by Sun Microsystems.
Network and file access restrictions can
be applied for security reasons and
because of configurable safety levels,.
Major web browsers integrated the
capability to run Java applets within pages
(even Internet Explorer 4!)
Java 2 (1999)
 J2EE
 J2ME
 J2SE
 2006: Java EE, Java ME and Java SE.

The primary goals of the Java
language
1."simple, object oriented, and familiar"
 2."robust and secure"
 3."architecture neutral and portable"
 4. able to execute with "high
performance"
 5."interpreted, threaded, and dynamic

The Java platform (software
platform & JVM)
Our first program: “Hello World”
public class HW {

public static void main(String[] args) {

System.out.println("Hello World");

}
}

Let’s run the program!
javac HW.java
 If you get no message displayed after
hitting Enter, compilation was successful.
The new HW.class file is now in the
folder too. Type:
 java HW

Comments









// this line is a comment
/*
* this block is a comment
*/
/**
* this comment block is to be used by
javadoc (Java Automatic Documentation
tool) to create automatic documentation
*/
OOP
System.out.println(“Hello, World!”);
 Here the object out is a nested object.

Instruction, scope of blocks and
compound statements








A single instruction is closed by semicolon
(;).
package b01;
public class Main {
public static void main(String[] args) {
System.out.println("The first
sentence.");
System.out.println("The second
sentence.");
}
}
Allowed characters of appellation
rules in Java

The letters of the English alphabet,
numbers, the underscore (_) and the
dollar ($) sign. The name cannot start
with a number.
Variables, final variables
(“constants”)
Declaration
 Primitive and reference data types

Variable initialisation
Examples:
 Declaration only:
 int numberOfUsers;
 Declaration and initialisation:
 int numberOfUsers=5;

Final variables (“constants”)

final int a=34;
Recommended appellations of
variables, final variables,
methods and classes
Variable names commonly start in
lowercase.
 Example:
 int numberOfCatsInTheHouse;


It is recommended that final variables
(constants) are typed in uppercase.
 Example:
 int SIZEOFARRAY=10;

Names of methods start and continue in
lowercase.
 Example:
 public static void main(String[] args)
 public static int sum(int a, int b)

Names of classes start in uppercase and
continue in lowercase.
 Example:
 class Sample;
 class SampleToShow;

Arrays
Indexing

maximum index = length of array -1
Creating an array
Declare the array:
 int[] ballHolder;
 You may also use (but it is not
recommended in Java):
 int ballHolder[];

This declaration has not created the array
yet because it is a reference type variable:
 ballHolder = new int[5]

Most of the time these two lines are used
in a contracted format:
 int[] ballHolder = new int[5];

Another solution:
 int primes = {7, 11, 13};

Accessing an item of the array
The item can be accessed using square
brackets ([]).
 If we want to put number 8 into the array
at its fourth position (which means index
3):
 ballHolder[3]=8;

Length of an array
length
 int a=ballHolder.length



public static void main(String[] args) {
int[] ballHolder = new int[5]; //creating
array






ballHolder[0]=1; //adding values into the
items
ballHolder[1]=5;
ballHolder[2]=2;
ballHolder[3]=8;
ballHolder[4]=5;
int sum=0; //creating a summarizer
variable, where I will add all the stored
numbers, initialising with 0

sum = sum + ballHolder[0];
//accumulating the values: sum = 0 + 1

sum = sum + ballHolder[1]; // sum = 1
+5

sum = sum + ballHolder[2]; // sum = 6
+2

sum += ballHolder[3]; // sum = 8 + 8

sum += ballHolder[4]; // sum = 16 + 5
=> sum now contains 21

// Contracted "sum +=" format
can be used instead of "sum = sum +"


System.out.println("Sum=
"+sum);//with "+" sign we can
concatenate which we want to write out

}

Multidimensional array (“Array
of array”)
int a[][] = new int[4][9];
 If we want to know the length of the first
array (displays 4):
 System.out.println(a.length);

If we want to know the length of the
second array (displays 9):
 System.out.println(a[0].length);

Operators

Operators work with operands, which
can be literals, variables or method return
types. Operators specify an evaluation or
computation to be performed on a data
object or objects. In Java there are unary
and binary operators. Unary operators
act only on single operands while binary
operators act on pairs of operands.
Arithmetical operators
Description
Operator
Addition
+
Subtraction
-
Multiplication
*
Division
/
Modulus
%
Implicit conversion

When an arithmetical expression has a
floating point operand and an integer
operand, before the execution the integer
operand will be converted into a floating
point number in an implicit way and the
result will also be a floating point number.
Relational operators
Operator
Usage
<
Result is true, if
operand1< opperand2
Greater Than
>
Result is true, if operand
1> operand 2
Less Than Or Equal To
<=
Result is true, if operand
1<= operand 2
Greater Than Or Equal To
>=
Result is true, if operand
1>= operand 2
Equal To
==
Result is true, if operand
1== operand 2
!=
Result is true, if operand
1!= operand 2
Description
Less Than
Not Equal To
Boolean operators
Description
Evaluation AND
Evaluation OR
Evaluation XOR
Logical AND
Logical OR
Negation (logical)
Equal To (logical)
Not Equal To (logical)
Conditional
Operator
&
|
^
&&
||
!
==
!=
?:
Form
operand 1 & operand 2
operand 1 | operand 2
operand 1 ^ operand 2
operand 1 && operand 2
operand 1 || operand 2
Usage
Returns true if operands are true;
both operands are evaluated. If
operands are bits, means bitwise
AND
Returns true if at least one of the
operands is true; both operands
are evaluated. If operands are bits,
means bitwise OR
Returns true if at least one of the
operands is false; both operands
are evaluated. If operands are bits,
means bitwise XOR
Returns true if both operands are
true; only the first operand from
left is evaluated.
Returns true if at least one of the
operands is true; only the first
operand from left is evaluated.
Returns true if operand is false
! operand
operand 1 == operand 2
Returns true if operands are equal
operand 1 != operand 2
Returns true if operands are not
equal
System.out.println( (operand 1 >
operand 2)? “operand 1 is larger”:
“operand 2 is larger”);
?: conditional expression can be
used standalone
p (operand
1)
q (operand
2)
&& (AND) || (OR)
^ (XOR)
true
true
true
true
false
true
false
false
true
true
false
true
false
true
true
false
false
false
false
false
The increment and decrement
operators
Description
Operator
Usage
Simple
=
operand = value
Addition
+=
Instead of operand = operand + value
you may use operand += value
Subtraction
-=
Instead of operand = operand - value
you may use operand -= value
Multiplication
*=
Instead of operand = operand * value
you may use operand *= value
Division
/=
Instead of operand = operand / value
you may use operand /= value
Modulus
%=
Instead of operand = operand % value
you may use operand %= value
AND
&=
Instead of operand = operand & value
you may use operand &= value
OR
|=
Instead of operand = operand + value
you may use operand |= value
XOR
^=
Instead of operand = operand ^ value
you may use operand ^= value
Loops
“for” loop
for (Initialization Expression; Loop
Condition; Step Expression)
{
 Statement
}

public class Main {

public static void main(String[] args) {

for(int i=1;i<21;i++);

{

System.out.println(i);

}

}
}

“for” for arrays
for (item : array)
{
 instructions
}

String[] names = new
String[]{“Tom”,”Peter”,”Nora”};
 for (String s : names)
{
 System.out.println(s);
}

“while” loop
while (Loop Condition)
{
 Statement
}

“do – while” loop
do
{
 Statement
}
 while (Loop Condition)

public class Main {

public static void main(String[] args)

{





//using for loop
int data=5;
int store=5;








for(int i=0;i<9;i++)
{
data *= 2;
System.out.println("Variable \"data\"
contains in step "+(i+1)+". = "+data);
store += data;
System.out.println("Variable \"store\"
contains in step "+(i+1)+". = "+store);
}
System.out.println("Result using \"for\":
"+store);













//using while loop
int data2=5;
int store2=5;
int i=0;
while(i<9)
{
i++;
data2 *= 2;
System.out.println("Variable \"data2\" contains in step
"+(i+1)+". = "+data2);
store2 += data2;
System.out.println("Variable \"store2\" contains in step
"+(i+1)+". = "+store2);
}
System.out.println("Result using \"while\": "+store2);
















//using do-while loop
data=5;
store=5;
int j=0;
do
{
j++;
data *= 2;
System.out.println("Variable \"data\" contains in step "+(j+1)+". =
"+data);
store += data;
System.out.println("Variable \"store\" contains in step "+(j+1)+". =
"+store);
}
while(j<9);
System.out.println("Result using \"do-while\": "+store);
}
}
Fibonacci sequence

public class Main {


public static void main(String[] args) {






int data = 15;
int fib[] = {0, 1, 1};
long sum = 0;
System.out.println();











for (int i = 0; i < data; i++) {
fib[0] = fib[1];
fib[1] = fib[2];
fib[2] = fib[0] + fib[1];
System.out.println(fib[0]);
sum += fib[0];
}
System.out.println("===\nSum " + sum);
}
}
Break, continue

To jump out from a loop you can use
either continue; or break;
Display a 10x10 multiplication table

public class Main {

public static void main(String[] args) {
int start = 1;
int end = 10;
for (int i = start; i <= end; i++) {
for (int j = start; j <= end; j++) {
System.out.format("%6d", (i * j));
}
System.out.println();
}
}











}
Branches
“if –else”
if (Condition)
 Statement1
 else
 Statement2

which number is greater?
if (a>b)
 System.out.println(a);
 else
 System.out.println(b);















public class Main {
public static void main(String[] args) {
int a=10;
int b=15;
if (a>b)
{
System.out.println(a);
}
else
{
System.out.println(b);
}
}
}
Contraction in loops and
branches
if (a>b)
 System.out.println(a);
 else
 System.out.println(b);


res=(a>b)?a:b;
for(int i=12;i>0;i--)
 System.out.println(i);

Decision tree
p (operand q (operand
1)
2)
&& (AND) || (OR)
^ (XOR)
true
true
true
true
false
true
false
false
true
true
false
true
false
true
true
false
false
false
false
false

if((21<=x) && (x<=50))

if((x%2==0)||(x%3==0))
Switch
The syntax of the switch is:
 switch (expression) {


case constant1:


instructions;
break;



case constant2:


instructions;
break;



default:
instructions;




}
The months of the year






















public class Main {
public static void main(String[] args) {
int month = 8;
switch (month) {
case 1:
System.out.println("Jan");
break;
case 2:
System.out.println("Feb");
break;
case 3:
System.out.println("Mar");
break;
case 4:
System.out.println("Apr");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("Jun");
break;

case 7:
System.out.println("Jul");
break;
case 8:
System.out.println("Aug");
break;
case 9:
System.out.println("Sep");
break;
case 10:
System.out.println("Oct");
break;
case 11:
System.out.println("Nov");
break;
case 12:
System.out.println("Dec");
break;
default:
System.out.println("Invalid month!");
break;




















}

}


}
failed or passed?


















public static void main(String[] args) {
byte mark = 3;
switch (mark) {
case 1:
System.out.println("Failed");
break;
case 2:
case 3:
case 4:
case 5:
System.out.println("Passed");
break;
default:
System.out.println("Invalid mark");
break;
}
}
}
Random numbers
int x = (int) (Math.random()*(maxmin+1)+min);
 int x = (int) (Math.random()*(1610+1)+10);

Casting types
10<=x<=20
 int x = (int) (Math.random()*(2010+1)+10)

1<=x<=90
 int x = (int) (Math.random()*(90-1+1)+1)

85<=x<=120
 int x = (int) (Math.random()*(12085+1)+85)

Negatives:
 -100<=x<=110
 int x = (int) (Math.random()*(110-(-100)
+1)+(-100))
 or in a contracted form:
 int x = (int) (Math.random()*(110+100)
+1)-100)

fortune teller program (random
answers)




public class Main {
public static void main(String[] args) {
String[] answers = new String[]{"yes", "no",
"perhaps", "unlike", "not clear now"};

int max = answers.length - 1;

int generated_number = (int)
(Math.random() * (max - 0 + 1) + 0);



System.out.println(answers[generated_number]);
}
}
int generated_number = (int)
(Math.random() * (max - 0 + 1) + 0);
 Obviously, the zeros can be deleted:
 int generated_number = (int)
(Math.random() * (max + 1));

perimeter and area of a possible
triangle







public class Main {
public static void main(String[] args)
{
int a=(int) (Math.random()*(4010+1)+10);
int b=(int) (Math.random()*(4010+1)+10);
int c=(int) (Math.random()*(4010+1)+10);
if ((a<b+c)&&(b<a+c)&&(c<b+c))

{

int perimeter=a+b+c;

System.out.println("Perimeter:
"+perimeter);

int s=perimeter/2;

System.out.println("Area:
"+Math.sqrt(s*(s-a)*(s-b)*(s-c)));

}



else
{
System.out.println("Not a
triangle!!!");

}

}
}

Reading from the input using
System.in.read( )

Java was originally designed for small
devices, which all have different inputs and
mostly only numeric keyboards. A phone
is a good example, particularly if we think
of a 1996 model. Here every button
represents a value (numbers, signs etc.),
therefore a “basic” reader in Java is
designed to read one value at one time.
This means that only one character or
one digit can be read at the same time.


















Read in two numbers using
“System.in.read( )” and decide
which
public
class Main { one is greater
public static void main(String[] args) throws java.io.IOException
{
int value;
int value2;
System.out.println("Welcome! Please type the first number between 0-9");
value = System.in.read()-48;
System.in.read();
System.out.println("The typed number is: " + value);
System.out.println("Welcome! Please type the second number between 0-9");
value2 = System.in.read()-48;
System.in.read();
System.out.println("The typed number is: " + value2);
if(value > value2)
System.out.println(value+" is greater");
else
System.out.println(value2+" is greater"); }
}
Read in a character using
“System.in.read ( )”.
public static void main(String[] args) throws
java.io.IOException
 {

char a;

System.out.println("Üdvözlöm! Kérem
írjon be
egy betűt.");

a = (char) (System.in.read());

System.out.println("A beütött betű: " + a);

}


Exceptions handling

In “Exercise: Read in two numbers using
“System.in.read( )” and decide which one
is greater.” we already checked how the
kind of exception handling solution which
“throws” an error message works.










Syntax:
try
{
instructions
}
catch (Exception e)
{
//exception handling codes. E. g. display a red
error message, with the error code.
System.err.println(“Error”+e.toString());
}
try
 {instructions }
 catch (Exception)
 {instructions }
 catch (Exception)
 {instructions}
 finally {instructions}
















public class Main {
public static void main(String[] args)
{
String a=”dog”;
try
{
int k = a;
}
catch (NumberFormatException e)
{
System.err.println(”Number format error”);
System.exit(1);
}
}
}
So the number evaluating program
has been rewritten in this way
public class Main {

public static void main(String[] args)

{

int value=0;

int value2=0;

System.out.println("Welcome!
Please type the first number between 09");


try {
value = System.in.read() - 48;

System.in.read();

} catch (Exception e) {

System.err.println(e.toString());

}

System.out.println("The typed number
is: " + value);

System.out.println("Welcome! Please
type the second number between 0-9");















try {
value2 = System.in.read() - 48;
System.in.read();
} catch (Exception e) {
System.err.println(e.toString());
}
System.out.println("The typed number is: " +
value2);
if (value > value2) {
System.out.println(value + " is greater");
} else {
System.out.println(value2 + " is greater");
}
}
}
Reading from the input using
Scanner object










packade
import java.util.*;
class Main {
public static void main
{
Scanner reader = new Scanner(System.in);
int x = reader.nextInt();
String s = reader.nextLine();
}
}
calculate how many days there are
in a given month and year









import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int year = 0;
int month = 0;
if (args.length < 2)
{
System.out.println("Missing
parameter! e.g. 2020 2");
Scanner reader = new
Scanner(System.in);

System.out.println("Type the year:
e.g. 2010");

year = reader.nextInt();

System.out.println("Type the
month: e.g. 8");

month = reader.nextInt();

} else {









try {
year = Integer.valueOf(args[0]);
month = Integer.valueOf(args[1]);
System.out.println("Year: " + year
+ " month: " + month);
} catch (NumberFormatException e)
{
System.err.println("Badly formed
parameter! e.g.. 2020 2");
}
}

















int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;













case 2:
if (((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0)) {
numDays = 29;
} else {
numDays = 28;
}
break;
default:
numDays = 0;
break;
}
System.out.println("Number of Days = " +
numDays);

}
 }
Command-line arguments

The system may pass an array of Strings
that contains the command line
arguments to the program. This array is
called args.













public static void main(String[] args) {
if (args.length == 0) {
System.err.println("No parameters");
System.exit(1);
} else {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
for (String s : args) {
System.out.println(s);
}
}
}
Converting variables
try {
 year = Integer.valueOf(args[0]);
 month = Integer.valueOf(args[1]);
 System.out.println("Year: " + year + "
month: " + month);
 } catch (NumberFormatException e) {
 System.err.println("Badly formed
parameter! e.g. 2020 2");
}

Data type wrapper classes
year = Integer.valueOf(args[0]);
 month = Integer.valueOf(args[1]);

Available wrapper classes in Java
Boolean
 Character
 Double
 Float
 Integer
 Long

String

In Java stings are represented by classes
and not by Unicode 16 character arrays.
String and StringBuffer are two classes
that model strings. The String class
represents constant (immutable) strings
unlike the StringBuffer class, which
represents variable (mutable) strings.
String()
 •String(String value)
 •String(char value[])
 •String(char value[], int offset, int count)
 •String(byte ascii[], int hibyte, int offset, int
count)
 •String(byte ascii[], int hibyte)
 •String(StringBuffer buffer)

String s1 = new String();
 String s2 = new String(“Hello”);
 String s2=”Hello”;
 char[] charArray = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’};
 String s3 = new String(charArray);
 String s4 = new String(charArray, 1, 3);

String methods

Concatenation:
s3=s1+s2 or
s5=s4.concat(“this word more”);

Length of a string: the number of Unicode
16 characters in the string
int x = s1.length();

Converting data to string
String.valueOf(data_to_convert)

Character at a given index charAt(int
index)
char c = s1.charAt(4);

Convert to lowercase
String s2 = s2.toLowerCase();

Convert to uppercase
String s2 = s2.toUpperCase();

Comparing strings (since string is an
object, “==” cannot be used to compare
the values of two strings)
Boolean equals(Object obj)
if (s1.equals(s2))
Boolean equalsIgnoreCase(String str)
if (s1.equalsIgnoreCase (s2)) //lowercase
or uppercase does not matter

The endsWith methods determine
whether or not a string ends with a suffix
string, as specified by parameters.
endsWith(String suffix)
if(s1.endWith(“man”)

The startsWith methods determine
whether or not a string starts with a
prefix string, as specified by parameters.
startsWith(String prefix)
if(s1.startsWith(“man”)

Removing spaces
s2=s1.trim();

Replace all characters in a string
String replace (char old_char, char
new_char);
s4 = s3.replace(‘a’, ‘A’);

Substrings
The substring returns the substring
starting at the index specified by
beginIndex until the end of the calling
String object.
s2 = s1.substring(4);

The substring returns a substring starting
at the index specified by beginIndex and
ending specified by endIndex.
s3 = s1.substring(3, 9);
change every even character to
uppercase and every odd
character to lowercase





import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new
Scanner(System.in);

System.out.print("Type a name or a
word: ");

String word = reader.nextLine();

String newWord = "";

String temp = "";
















for (int i = 0; i < word.length(); i++) {
if (i % 2 == 0) {
temp = "";
temp += word.charAt(i);
temp = temp.toUpperCase();
newWord += temp;
} else {
temp = "";
temp += word.charAt(i);
temp = temp.toLowerCase();
newWord += temp;
}
}
System.out.print(newWord+"\n\n");
}
}
Methods

A method is a group of instructions which
has a given name and can be called up
simply by quoting that name at any point
in the source code.
Problems with sequential
programming














public static void main (Srting[] args)
{
int a=25;
int b=15;
int c=a+b;
int d=a*b;
System.out.println(”Sum”+c);
System.out.println(”Product”+d);
// I change the value of variable a, so I have to copy the remaining
part of the source code
a=30;
int c=a+b;
int d=a*b;
System.out.println(”Sum”+c);
System.out.println(”Product”+d);
Why use methods (and
procedural programming)?
Sub-processes are better diverted.
 The program can be structured and
repaired more easily.
 The program contains methods which call
each other.

Defining a method
Modifier Return
s
type
public
static
Method Metho (argum
's return
d
ents)
type
name
void
private
int
protecte
d
char
String
array

public static void main(String[] args)

public static int sum(int a, int b)

tell more…
Working inside a method
public static int sum(int a, int b)
{
 int c=a+b;
 return c;
}

Instance variables
private int a;
 private int b=34;

Procedural solution for the
calculating program










public class Main {
private static int a;
private static int b;
public static void data(int a1, int b1) {
a = a1 + 2;
b = b1 - 1;
writer("sum ", sum(a1, b1));
}






public static int sum(int f, int g) {
int c = f + g;
return c;
}
public static int product() //using instance
variable

{

int c = a * b;

return c;

}
public static void writer(String name, int number) {

System.out.println(name + " " + number);

}





public static void main(String[] args) {
data(25, 15);
writer("product ", product());






//I change the value of one variable
data(30, 15);
writer("product", product());
}
}
Using arrays with methods

Array type parameters can also be applied
with methods. They are treated just like
other parameters, the only difference
being that you have to put them in square
brackets [].You can also use
multidimensional arrays as a parameter, in
this case you have to put them in two
square brackets [] []
read numeric values from ”args”,
then define a greatest (max) and
smallest (min) number







Do not use instance variable.
Methods:
public static double convert(String[ ] x) //Handles the given
parameters
public static double max(double[ ] x) //Searches for the
greatest number
public static double min(double[ ] x) // Searches for the
smallest number
public static String errorhandle () //Displays a message to the
user if the parameter list is not correct
public static void writer(real[ ] t,real maxi, real mini)
//Displays the numbers separated by tabs ("\t") and the
greatest and the smallest numbers.










public class Main {
public static void main(String[] args) {
if (args.length == 0) {
System.err.println(errorhandle());
} else {
int[] series = convert(args);
writer(series, max(series),
min(series));
}
}











public static int[] convert(String[] x) {
int[] yo = new int[x.length];
for (int i = 0; i < x.length; i++) {
try {
yo[i] = Integer.parseInt(x[i]);
} catch (NumberFormatException e) {
System.err.println("Cannot convert to
number!");
}
}
return yo;
}









public static int max(int[] x) {
int max = x[0];
for (int i = 1; i < x.length; i++) {
if (x[i] > max) {
max = x[i];
}
}
return max;
}









public static int min(int[] x) {
int min = x[0];
for (int i = 1; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
}
return min;
}
public static String errorhandle() {

return "At least one item is
needed!";

}

Overloading methods

In Java you can create methods with the
same name and with different parameter
lists. This is called overloading and it
means that the appropriate method will
be activated according to its parameter
list at calling











I have two methods with the same name and a
different parameter list.
static int sum (int a, int b)
{…}
static int sum (int a, double b)
{…}
If I call the sum this way
int a = sum (3, 2.3);
where 2.3 is not an integer, the
static int sum (int a, double b)
{…}
method will automatically be used.
End of semester…