Vous êtes sur la page 1sur 19

Basics of java

Introduction to Java programming


JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was
conceived by James Gosling and Patrick Naughton. It is a simple programming language. Writing,
compiling and debugging a program is easy in java. It helps to create modular programs and reusable
code.

Main Features of JAVA


Java is a platform independent language
To understand the meaning of platform independent, we must need to understand the meaning of
platform first. A platform is a pre-existing environment in which a program runs, obeying its constraints,
and making use of its facilities.
Lets back to the point. During compilation, the compiler converts java program to its byte code. This
byte code can run on any platform such as Windows, Linux, Mac/OS etc. Which means a program that is
compiled on windows can run on Linux and vice-versa. This is why java is known as platform
independent language.

Java is an Object Oriented language


Object oriented programming is a way of organizing programs as collection of objects, each of which
represents an instance of a class.

4 main concepts of Object Oriented programming are:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Simple
Java is considered as one of simple language because it does not have complex features like Operator
overloading, Multiple inheritance, pointers and Explicit memory allocation.

Robust Language
Two main problems that cause program failures are memory management mistakes and mishandled
runtime errors. Java handles both of them efficiently.
1) Memory management mistakes can be overcome by garbage collection. Garbage collection is
automatic de-allocation of objects which are no longer needed.
2) Mishandled runtime errors are resolved by Exception Handling procedures.

Secure
It provides a virtual firewall between the application and the computer. Java codes are confined within
Java Runtime Environment (JRE) thus it does not grant unauthorized access on the system resources.

Java is distributed
Using java programming language we can create distributed applications. RMI(Remote Method
Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications in java. In
simple words: The java programs can be distributed on more than one systems that are connected to
each other using internet connection. Objects on one JVM (java virtual machine) can execute
procedures on a remote JVM.

Multithreading
Java supports multithreading. It enables a program to perform several tasks simultaneously.

Portable
As discussed above, java code that is written on one machine can run on another machine. The platform
independent byte code can be carried to any platform for execution that makes java code portable.

Compilation and Execution of First Java Program


To create a java code an editor such as notepad, text pad or an IDE like eclipse can be used.

Sample Java Code:


public class FirstJavaProgram {
public static void main(String[] args){
System.out.println("This is my first program in java");
}//End of main
}//End of FirstJavaProgram Class
Output: This is my first program in java

In the above program the class FirstJavaProgram has public access and hence declared public.
class is the keyword used to create a class.
For running stand-alone programs main method is needed which has a signature similar to the one
defined in the above program.
Main method takes an array of strings as an argument. The name of the array can be anything.
To display the output, pass the string as an argument to the method System.out.println.

Steps for compilation and Execution


Step1: Save the source file as WelcomeApp.java.
Step2: Open command prompt and navigate to the directory where you have stored the file.
Step 3: To compile, type javac FirstJavaProgram.java and press Enter.
Step 4: On successful compilation, you will see the command prompt and FirstJavaProgram.class file in
the same folder where WelcomeApp.java is stored. This is the byte code of the program.
Step 5: To execute, type java FirstJavaProgram. Do not type the extension while executing.
Step 6: See the output This is my first program in java displayed on the console.

Common programming Errors in Java


The following are the general programming errors and the solution for them while running on windows
machine.
1) javac is not recognized as an internal or external command, operable program or batch file This
means that the operating system cannot find the compiler javac. In order to resolve this the PATH
variable has to be set.
2) Exception in thread mainjava.lang.NoClassDefFoundError: FirstJavaProgram This error means
that java cannot find your compiled byte code, WelcomeApp.class. If the class file is present in directory
other than the directory where java file is stored, then the CLASSPATH must be set pointing to the
directory that contains compiled class files.

Another Example
If you are a beginner and feel hard to understand the below example then just skip it and try to
understand it once you finished reading all of my linked tutorials. After reading all tutorials it would be
easy for you to learn things much faster.

package FirstCode
import java.lang.*;
class WelcomeMessage
{
printMessage()
{
System.out.println("Hello World");
}
}
class Myclass
{
public static void main(String []args)
{
WelcomeMessage obj=new WelcomeMessage ();
obj.printMessage();
}
}
Output: Hello World

Interpreting the code

a) Line 1. The package FirstCode creates a folder to store the class files generated after compilation
b) Line2. It imports the class library java.lang and its subsequent classes
c) Line 3. Initiates a class with the name WelcomeMessage
d) Line 5. Declares a method with name printMessage
e) Line 7. Defines the actual working code of the method
f) Line 10. Initiates the class having the main method; it should bear the name of the file : Myclass.java
g) Line 12. Declares the main method
h) Line 14. Initiates the creation of the object
i) Line 15. Calls the method printMessage () with the help of the object
j) The above code is saved and compiled to run on JVM
The programming structure

1) The programming pattern is divided into classes which has meth0d definitions
2) This assists in distributing the code into smaller units
3) The libraries can be used over and over again
4) These codes generated here can be called in another program if required
5) The memory allocation is done only after the execution of the new keyword
6) It gets easier to collect memory that does not has any future use

JVM (Java virtual Machine)

1) Class loader accepts class files


2) Compilation creates class files
3) The interim memory is required during execution
4) It consists of heaps, stacks and registers to store data
5) JRE has native methods and libraries
6) JVM runs two main threads
a) demon
b) Non-demon threads

Demon Threads

It has been Run by JVM for itself. Used for garbage collection. JVM decides on a thread for being a
demon thread

Non-demon threads

main () is the initial and non-demon thread. Other implemented threads are also non-demon threads.
The JVM is active till any non-demon thread is active.
Execution on JVM
1) JVM executes Java byte codes
2) Other programming language codes if converted to adequate Java byte code can be executed on JVM
3) JVM is different for different platforms and can also act as a platform itself
4) JVM supports automatic error handling by intercepting the errors which can be controlled
5) This feature is useful in platform independency and multi user ability of Java.

Compilation
1) The compiler requires to know the TYPE of every CLASS used in the program source code
2) This is done by setting a default user environment variable CLASSPATH
3) The Javac (Java Compiler) reads the program and converts it into byte code files called as class files

Java Source code

1) It essentially consists of a main () method


2) This method is public and thus can be called by any object
3) This method is also static and so can be called without instantiating the object of the class
4) It does not return any value
5) The controlling class of every Java application usually contain a main method
6) This can be avoided to allow the class to be tested in a stand-alone mode.
7) Other methods can subsequently be called in main ()

First Java Program


Let us look at a simple java program.
class Hello
{
public static void main(String[] args)
{
System.out.println ("Hello World program");
}
}
class : class keyword is used to declare classes in Java
public : It is an access specifier. Public means this function is visible to all.
static : static is again a keyword used to make a function static. To execute a static function you do not have to
create an Object of the class. The main() method here is called by JVM, without creating any object for class.
void : It is the return type, meaning this function will not return anything.
main : main() method is the most important method in a Java program. This is the method which is executed,
hence all the logic must be inside the main() method. If a java class is not having a main() method, it causes
compilation error.
System.out.println : This is used to print anything on the console like printf in C language.

Steps to Compile and Run your first Java program


Step 1: Open a text editor and write the code as above.
Step 2: Save the file as Hello.java
Step 3: Open command prompt and go to the directory where you saved your first java program assuming it is
saved in C:\
Step 4: Type javac Hello.java and press Return to compile your code. This command will call the Java Compiler
asking it to compile the specified file. If there are no errors in the code the command prompt will take you to the
next line.
Step 5: Now type java Hello on command prompt to run your program.
Step 6: You will be able to see Hello world program printed on your command prompt.

Now let us see What happens at Runtime


After writing your Java program, when you will try to compile it. Compiler will perform some compilation operation
on your program.
Once it is compiled successfully byte code(.class file) is generated by the compiler.

After compiling when you will try to run the byte code(.class file), the following steps are performed at runtime:-

1. Class loader loads the java class. It is subsystem of JVM Java Virtual machine.
2. Byte Code verifier checks the code fragments for illegal codes that can violate access right to the object.

Data Types in Java


Java language has a rich implementation of data types. Data types specify size and the type of values that can be
stored in an identifier.
In java, data types are classified into two catagories :

1. Primitive Data type


2. Non-Primitive Data type

1) Primitive Data type


A primitive data type can be of eight types :
Primitive Data types

char boolean byte short int long float double

Once a primitive data type has been declared its type can never change, although in most cases its value can
change. These eight primitive type can be put into four groups

Integer
This group includes byte, short, int, long
byte : It is 8 bit integer data type. Value range from -128 to 127. Default value zero. example: byte b=10;
short : It is 16 bit integer data type. Value range from -32768 to 32767. Default value zero. example: short s=11;
int : It is 32 bit integer data type. Value range from -2147483648 to 2147483647. Default value zero. example: int
i=10;
long : It is 64 bit integer data type. Value range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Default value zero. example: long l=100012;

Floating-Point Number
This group includes float, double
float : It is 32 bit float data type. Default value 0.0f. example: float ff=10.3f;
double : It is 64 bit float data type. Default value 0.0d. example: double db=11.123;

Characters
This group represent char, which represent symbols in a character set, like letters and numbers.
char : It is 16 bit unsigned unicode character. Range 0 to 65,535. example: char c='a';
Boolean

This group represent boolean, which is a special type for representing true/false values. They are defined constant
of the language. example: boolean b=true;

2) Non-Primitive(Reference) Data type


A reference data type is used to refer to an object. A reference variable is declare to be of specific and that type
can never be change. We will talk a lot more about reference data type later in Classes and Object lesson.

Identifiers in Java
All Java components require names. Name used for classes, methods, interfaces and variables are called Identifier.
Identifier must follow some rules. Here are the rules:

All identifiers must start with either a letter( a to z or A to Z ) or currency character($) or an underscore.
After the first character, an identifier can have any combination of characters.
A Java keyword cannot be used as an identifier.
Identifiers in Java are case sensitive, foo and Foo are two different identifiers.

3. reter reads the byte code stream and then executes the instructions, step by step.

Variable
Java Programming language defines mainly three kind of variables.

1. Instance variables
2. Static Variables
3. Local Variables

1) Instance variables
Instance variables are variables that are declare inside a class but outside any method,constructor or block.
Instance variable are also variable of object commonly known as field or property.
class Student
{
String name;
int age;
}
Here name and age are instance variable of Student class.

2) Static variables
Static are class variables declared with static keyword. Static variables are initialized only once. Static variables are
also used in declaring constant along with final keyword.
class Student
{
String name;
int age;
static int instituteCode=1101;
}
Here instituteCode is a static variable. Each object of Student class will share instituteCode property.
3) Local variables
Local variables are declared in method constructor or blocks. Local variables are initialized when method or
constructor block start and will be destroyed once its end. Local variable reside in stack. Access modifiers are not
used for local variable.

float getDiscount(int price)


{
float discount;
discount=price*(20/100);
return discount;
}
Here discount is a local variable.

Java Operators
Java provides a rich set of operators enviroment. Java operators can be devided into following categories

Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Misc operators

Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are used in algebra.

operator description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denumerator

% remainder of division

++ Increment operator increases integer value by one


-- Decrement operator decreases integer value by one

Relation operators
The following table shows all relation operators supported by Java.

operator description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

Logical operators
Java supports following 3 logical operator. Suppose a=1 and b=0;

operator description example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false

Bitwise operators
Java defines several bitwise operators that can be applied to the integer types long, int, short, char and byte

operator description

& Bitwise AND


| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the right
operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the
same precedence.Example
a = 0001000
b= 2
a << b= 0100000
a >> b= 0000010

Assignment Operators
Assignment operator supported by Java are as follows

operator description example

= assigns values from right side operands to left a=b


side operand

+= adds right operand to the left operand and a+=b is same as


assign the result to left a=a+b

-= subtracts right operand from the left operand a-=b is same as


and assign the result to left operand a=a-b
*= mutiply left operand with the right operand a*=b is same as
and assign the result to left operand a=a*b

/= divides left operand with the right operand and a/=b is same as
assign the result to left operand a=a/b

%= calculate modulus using two operands and a%=b is same as


assign the result to left operand a=a%b

Misc operator
There are few other operator supported by java language.
Conditional operator
It is also known as ternary operator and used to evaluate Boolean expression
epr1 ? expr2 : expr3
If epr1Condition is true? Then value expr2 : Otherwise value expr3

instanceOf operator
This operator is used for object reference variables. The operator checks whether the object is of particular type
(class type or interface type)

Control statements in java with examples


Java If-else Statement

The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various
types of if statement in java.

o if statement
o if-else statement
o nested if statement
o if-else-if ladder

Java IF Statement

The Java if statement tests the condition. It executes the if block if condition is true.

Syntax:

1. if(condition){
2. //code to be executed
3. }

Example:
1. public class IfExample {
2. public static void main(String[] args) {
3. int age=20;
4. if(age>18){
5. System.out.print("Age is greater than 18");
6. }
7. }
8. }

Output:

Age is greater than 18

Java IF-else Statement

The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is
executed.

Syntax:

1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
6. public class IfElseExample {
7. public static void main(String[] args) {
8. int number=13;
9. if(number%2==0){
10. System.out.println("even number");
11. }else{
12. System.out.println("odd number");
13. }
14. }
15. }

Output:

odd number

Java IF-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

Syntax:

1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }

Example:

1. public class IfElseIfExample {


2. public static void main(String[] args) {
3. int marks=65;
4.
5. if(marks<50){
6. System.out.println("fail");
7. }
8. else if(marks>=50 && marks<60){
9. System.out.println("D grade");
10. }
11. else if(marks>=60 && marks<70){
12. System.out.println("C grade");
13. }
14. else if(marks>=70 && marks<80){
15. System.out.println("B grade");
16. }
17. else if(marks>=80 && marks<90){
18. System.out.println("A grade");
19. }else if(marks>=90 && marks<100){
20. System.out.println("A+ grade");
21. }else{
22. System.out.println("Invalid!");
23. }
24. }
25. }

Output:

C grade
Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement.

Syntax:

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

1. public class SwitchExample {


2. public static void main(String[] args) {
3. int number=20;
4. switch(number){
5. case 10: System.out.println("10");break;
6. case 20: System.out.println("20");break;
7. case 30: System.out.println("30");break;
8. default:System.out.println("Not in 10, 20 or 30");
9. }
10. }
11. }

Output:

20
Java For Loop

The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is
recommended to use for loop.

There are three types of for loop in java.

o Simple For Loop


o For-each or Enhanced For Loop
o Labeled For Loop

Java Simple For Loop

The simple for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value.

Syntax:

1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
Example

1. public class ForExample {


2. public static void main(String[] args) {
3. for(int i=1;i<=10;i++){
4. System.out.println(i);
5. }
6. }
7. }

Output:

1
2
3
4
5
6
7
8
9
10

Java For-each Loop

The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we
don't need to increment value and use subscript notation.

It works on elements basis not index. It returns element one by one in the defined variable.

Syntax:

1. for(Type var:array){
2. //code to be executed
3. }

Example:

1. public class ForEachExample {


2. public static void main(String[] args) {
3. int arr[]={12,23,44,56,78};
4. for(int i:arr){
5. System.out.println(i);
6. }
7. }
8. }

Output:
12
23
44
56
78
Java While Loop

The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it
is recommended to use while loop.

Syntax:

1. while(condition){
2. //code to be executed
3. }
4. public class WhileExample {
5. public static void main(String[] args) {
6. int i=1;
7. while(i<=10){
8. System.out.println(i);
9. i++;
10. }
11. }
12. }

Output:

1
2
3
4
5
6
7
8
9
10

Java do-while Loop

The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed
and you must have to execute the loop at least once, it is recommended to use do-while loop.

The Java do-while loop is executed at least once because condition is checked after loop body.

Syntax:

1. do{
2. //code to be executed
3. }while(condition);

1. public class DoWhileExample {


2. public static void main(String[] args) {
3. int i=1;
4. do{
5. System.out.println(i);
6. i++;
7. }while(i<=10);
8. }
9. }

Output:

1
2
3
4
5
6
7
8
9
10
Java Break Statement

The Java break is used to break loop or switch statement. It breaks the current flow of the program at specified
condition. In case of inner loop, it breaks only inner loop.

Syntax:

1. jump-statement;
2. break;

Java Break Statement with Loop

Example:

1. public class BreakExample {


2. public static void main(String[] args) {
3. for(int i=1;i<=10;i++){
4. if(i==5){
5. break;
6. }
7. System.out.println(i);
8. }
9. }
10. }
Output:

1
2
3
4
Java Continue Statement

The Java continue statement is used to continue loop. It continues the current flow of the program and skips the
remaining code at specified condition. In case of inner loop, it continues only inner loop.

Syntax:

1. jump-statement;
2. continue;

Java Continue Statement Example

Example:

1. public class ContinueExample {


2. public static void main(String[] args) {
3. for(int i=1;i<=10;i++){
4. if(i==5){
5. continue;
6. }
7. System.out.println(i);
8. }
9. }
10. }

Output:

1
2
3
4
6
7
8
9
10

Vous aimerez peut-être aussi