0% found this document useful (0 votes)
14 views

Java

The document provides an introduction to the Java programming language, covering its features, portability, and tools required for development. It includes detailed explanations of Java syntax, primitive types, control structures, arrays, and the Scanner class for input handling. Additionally, it features quizzes to test knowledge on Java concepts.

Uploaded by

ouchbelinda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java

The document provides an introduction to the Java programming language, covering its features, portability, and tools required for development. It includes detailed explanations of Java syntax, primitive types, control structures, arrays, and the Scanner class for input handling. Additionally, it features quizzes to test knowledge on Java concepts.

Uploaded by

ouchbelinda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Java Programming Language

0.9
Table of contents

Objectives 3
I - Java Programming Language 4
1. Java Features .............................................................................................................4
2. Java Portability ..........................................................................................................4
3. Tools to make Java Programs...................................................................................4
4. A first Java program ..................................................................................................5
5. Primitive types ...........................................................................................................5
6. Primitive types ...........................................................................................................6
7. Wrapper Classes ........................................................................................................6
8. Operators ...................................................................................................................6
9. Type Conversion ........................................................................................................7
10. Control Structures ...................................................................................................7
11. Strings ......................................................................................................................8
12. Arrays........................................................................................................................9
13. The Scanner Class..................................................................................................11
14. Test your knowledge .............................................................................................12

2
Objectives

Introduce the Java programming language.


Know what is needed to make a Java program.
Acquire the bases of Java language.

3
Java Programming Language I

1. Introduction
There are many Object-Oriented programming languages:
- Java,
- C++,
- Python,
- C#,
- PHP,
- Ruby,
- etc.

2. Java Features
- Java is an Object-Oriented programming language
- It has a syntax close to that of C++ programming language.
- It is portable, i.e. the compiled code could be executed on different platforms and in different
environments.

3. Java Portability

4. Tools to make Java Programs


- Java Virtual Machine (JVM) will be available when we install JRE (Java Runtime Environnement).
- JDK (Java Developement Kit) offers the tools to develop and compile Java programs, it includes JRE.
- The IDEs (Integrated Development Environments) make it easier to edit, manage, compile, debug and
run Java programs and projects.

4
Java Programming Language

5. A first Java program


- We define a class Test in a text file "Test.java".
- We must have a method main that will be the starting point of the program execution.
1 public class Test {
2 public static void main(String[] args) {
3 System.out.println("Welcome L1");
4 }
5}

- The instruction System.out.println(...) allows to display the text between the parentheses.
- The compilation generates the file "Test.class".
- The execution displays on the console the text:
Welcome L1

Using an object from the class WelcomeAgent


1 //in a file "WelcomeAgent.java"
2 public class WelcomeAgent {
3 int id;
4 void welcomeMsg(int section) {
5 System.out.println("Welcome Section "+section+", I am agent "+id);
6 }
7}
1 //in a file "FirstEg.java"
2 public class FirstEg {
3 public static void main(String[] args) {
4 int section=3;
5 WelcomeAgent ag1=new WelcomeAgent();
6 ag1.id=1;
7 ag1.welcomeMsg(section);
8 WelcomeAgent ag2=new WelcomeAgent();
9 ag2.id=2;
10 ag2.welcomeMsg(section);
11 }
12 }

Output:
1 Welcome Section 3, I am agent 1
2 Welcome Section 3, I am agent 2

6. Primitive types
- Conventional or traditional types.
- They are not object classes.
- Used to declare variables and constants in methods and attributes in classes.
Integer types
Type Size Min Max

int 32 bits -231 +231-1

short 16 bits -215 +215-1

long 64 bits -263 +263-1

byte 8 bits -27 +27-1

5
Java Programming Language

7. Primitive types
boolean, chars and reals

Type Size

boolean 1 bit

char 16 bits

float 32 bits

double 64 bits

8. Wrapper Classes
To manipulate integers, reals and others like objects.
A wrapper type includes a primitive variable and offers a set of methods applicable on the
variable.

Primitive type Wrapper class

int Integer

byte Byte

short Short

long Long

boolean Boolean

char Char

float Float

double Double

9. Operators

Operator Description

= Assignment

+-*/ Arithmetic operators

&& || ! Logical operators

== != < > >= <= Comparison operators

++ -- (in/de)crementation

+= -= *= /= Arithmetic operation followed by an assignment

...

6
Java Programming Language

10. Type Conversion


Implicit:
double x=25; /* The integer value 25 is automatically converted to a double-precision real value */
Explicit (cast):
int a=(int)2.25;
System.out.println(a); //displays 2
Note: we can assign an expression to a variable when declaring it as in the examples above.

11. Control Structures


All instruction should end by ;
Conditional instructions
1 if(condition){
2 bloc_1;}
3
4 if(condition){
5 bloc_1;}
6 else{
7 bloc_2;}
8

Note:
Curly braces {} are optional if a block contains a single statement.
The Switch Statment
1 switch (expression){
2 case v1:
3 bloc_1; //instructions executed when expression==v1
4 break;
5 case v2:
6 bloc_2; //instructions executed when expression==v2
7 break;
8 ...
9 default:
10 bloc_n; //instructions executed when expression is other then v1,v2,...
11 break;}

"While" Loop
1 while(condition){
2 bloc;}

or
1 do{
2 bloc;} while(condition);

"For" Loop
1 for(preparation; condition; change){
2 bloc;}

preparation is executed when arriving at the for loop


condition is evaluated every time to enter/exit the loop
change is executed at the end of each iteration

7
Java Programming Language

12. Strings
The class String
Declaration
1 String s="NTIC L1 MI";

Display
1 System.out.println(s);

Some escape sequences:


\n new line
\t go to next tab mark
\\ show a backslash
\" show quote
\' single apostrophe Example:
1 System.out.println("NTIC:\n\tL1\\\t\"MI\"");

displays:
1 NTIC:
2 L1\ "MI"

Concatenation:+
Example:
1 String s1="L1",s2="MI";
2 s1+=" "+s2;
3 System.out.println(s1); displays L1 M1

Some Methods:

Method Description

int length() returns the length of the string.

boolean equals(s2) checks whether the string is equal to s2 or not.

checks whether the string is equal to s2 without


boolean equalsIgnoreCase(s2) considering case (lowercase/uppercase
difference)

String toLowerCase() converts the string to lowercase letters

String toUpperCase() converts the string to uppercase letters

returns the string without blanks at the


String trim()
beginning and end

char charAt(p) returns the character at position p. p=0,1,2,...

String subString(p) returns the substring starting at position p

returns the substring starting at position p


String subString(p,q)
without the substring starting at position q

returns the position of the first occurrence of


Int indexOf(s)
the string s

8
Java Programming Language

Method Description

returns the position of the first occurrence of


Int indexOf(s,p)
the string s starting from position p

returns the position of the last occurrence of the


Int lastIndexOf(s)
string s

Example
1 public static void main(String[] args) {
2 String s=" Welcome L1 MI ";
3 s=s.trim();
4 System.out.println("1) The length of \""+s+"\" is "+s.length());
5 System.out.println("2) "+s.equals("Welcome L1 Mi"));
6 s=s.toUpperCase();
7 System.out.println("3) "+s.equals("Welcome L1 Mi".toUpperCase()));
8 System.out.println("4) "+s.charAt(2));
9 System.out.println("5) "+s.substring(8));
10 System.out.println("6) "+s.substring(1,3));
11 s=s.substring(0,s.indexOf(" "))+"-"+s.substring(s.indexOf(" ")+1);
12 System.out.println("7) "+s);
13 }

Output:
1 1) The length of "Welcome L1 MI" is 13
2 2) false
3 3) true
4 4) L
5 5) L1 MI
6 6) EL
7 7) WELCOME-L1 MI

13. Arrays
Declaration:
1 elemType[] arrId;

Or
1 elemType arrId[];

e.g.
1 int[] t;
2 Double[] m;
3 char[] code;

The declaration of an array is not enough to start using it.


We must create it by allocating the necessary space in memory, or link it to an existing array.
1 arrId=new elemType[taille];
2 //example
3 code=new char[8];
4

It is possible to create the table when declaring it


1 char[] code=new char[8];

An array is created if it is initialized during declaration

9
Java Programming Language

1 int[] t={82,2,534}; //creates a 3 intergers array


2 int[] y=t;
3 //y and t refer to the same array.

Access to array elements


arrId[ix] designates the element of the arrId array whose index is ix
0 ≤ ix < arrId.length
arrId.length gives the number of elements of arrId
Example:
1 public class Essai {
2 public static void main(String[] args) {
3 int[]t=new int[5];
4 for(int i=0;i<t.length;i++)
5 t[i]=i*2+1;
6 for(int i=0;i<t.length;i++)
7 System.out.print(t[i]+"\t");
8 }
9}

Output:

Multidimensional Arrays
It is an array of arrays; each element is an array.
Declaration of a 2-dimensional array:
1 elemType[][] arrId;
2 //e.g.
3 double[][]m=new double[5][3]; //5 rows et 3 columns
4 int[][]t={{1,255},{21,4,16}}; // 2 rows with different lengths!!
5

Example:
1 public class Essai {
2 public static void main(String[] args) {
3 int[][]t= {{1,255},{21,4,16}};
4 int[][]y=t;
5 int temp=t[0][0];
6 t[0][0]=t[1][0];
7 t[1][0]=temp;
8 for(int i=0;i<y.length;i++) {
9 for(int j=0;j<y[i].length;j++)
10 System.out.print(y[i][j]+"\t");
11 System.out.print("\n");}
12 }
13 }

Output:

10
Java Programming Language

14. The Scanner Class


With Java, reading operation is more complicated than writing.
We should first import the Scanner class:
1 import java.util.Scanner;

We declare an object from the class Scanner and associate it with the standard input flow System.in
1 Scanner rdr=new Scanner(System.in);

Inputs are retrieve through some methods of the object rdr:

Method Description

returns the next token from the input as a


String next()
String

String nextLine() returns the rest of the current line

int nextInt() scans the next token of the input as an int

long nextLong() scans the next token of the input as a long

float nextFloat() scans the next token of the input as a float

double nextDouble() scans the next token of the input as a double

returns true if the next token in this scanner's


boolean hasNextInt()
input can be interpreted as an integer value

returns true if the next token in this scanner's


boolean hasNextLong()
input can be interpreted as a long value

returns true if the next token in this scanner's


boolean hasNextFloat()
input can be interpreted as a float value

returns true if the next token in this scanner's


boolean hasNextDouble()
input can be interpreted as a double value

void close() closes the scanner

Example:
1 import java.util.Scanner;
2 public class Test {
3 public static void main(String[] args) {
4 int a,b;
5 String s;
6 Scanner sc=new Scanner(System.in);
7 System.out.print("Type two integer values:");
8 while(!sc.hasNextInt()) {
9 s=sc.next();
10 System.out.print("Invalid input, retry please:");}
11 a=sc.nextInt();
12 while(!sc.hasNextInt()) {
13 s=sc.next();
14 System.out.print("Invalid input, retry please:");}
15 b=sc.nextInt();
16 System.out.print(a+"+"+b+"="+(a+b));
17 sc.close();

11
Java Programming Language

18 }
19 }

Output:

15. Test your knowledge


Objectives
Quiz 1
Which of the following statements about Java's portability is true?
 Java code needs to be recompiled for each platform

 Java code can only run on Windows operating systems

 Java code can run on any platform with the Java Virtual Machine (JVM)

 Java code is compiled directly into machine code

Quiz 2
Which of the following are primitive data types in Java?
 Char

 float

 String

 boolean

Quiz 3
What is the wrapper class for the primitive data type int in Java?
 Int

 intWrap

 integer

 Integer

Quiz 4
What is the result of the expression 10/3 in Java?
 3.33

 3.0

 3

 Error

Quiz 5
What is the output of the following code snippet?

12
Java Programming Language

1 int x=10,y=3;
2 System.out.println("Sum="+x+y);

 Sum=13

 Sum=103

 Sum=x+y

 Error

Quiz 6
Which of the following casting are done implicitly in Java?
 double to int

 long to float

 char to String

 boolean to int

Quiz 7
What is true about wrapper classes?
 They are equivalent to primitive types

 They offer useful methods

 Wrapper class numeric attributes are initialized to null.

 Wrapper class numeric attributes are initialized to zeros.

Quiz 8
Which of the following correctly declares an array in Java?
 int[] tab=new int[5];

 int tab=new int[5];

 int numbers[5]

 int tab[]=new int[5];

Quiz 9
What is the index of the last character in the String "Hello"?
 5

 4

 6

 "Hello".length()-1

Quiz 10
Which methods are used to read input from the user in Java?
 getInput()

 scanInt()

13
Java Programming Language

 nextDouble()

 next()

Quiz 11
Closing the Scanner object
 is obligatory to allow running the program.

 is highly recommended.

 is done through the method close()

 is done implicitly.

Quiz 12
Which of the following are valid ways to initialize a string in Java?
 String str="Hello";

 String str=new String("Hello");

 String str={'H', 'e', 'l', 'l', 'o'};

 String str="";

Quiz 13
What is the default value of an uninitialized integer variable in Java?
 0

 null

 a random value

 Error

Quiz 14
An matrix in Java
 all the rows should have the same length.

 the elements could be objects of a given class.

 the rows could be initialized at different times with elements of different types.

 can have more than one identifier.

Quiz 15
Suppose that the value of i was 5, the instrauction "i+=(++i);" will set its value to:
 10

 6

 11

 Error

Quiz 16
According to Java conventions,

14
Java Programming Language

 the classes identifiers start in capital letters.

 objects and variable names start in lower case.

 the names of constant fields are written entirely in capital letters.

 the first letter in each word in a compound identifier after the first is capitalized.

15

You might also like