Basics of Java
Basics of Java
Basics of Java
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.
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.
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
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
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
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.
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;
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.
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
% remainder of division
Relation operators
The following table shows all relation operators supported by Java.
operator description
> Check if operand on the left is greater than operand on the right
Logical operators
Java supports following 3 logical operator. Suppose a=1 and b=0;
|| Logical OR (a || b) is true
Bitwise operators
Java defines several bitwise operators that can be applied to the integer types long, int, short, char and byte
operator description
^ Bitwise exclusive OR
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
/= divides left operand with the right operand 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)
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:
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
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:
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. }
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.
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
Output:
1
2
3
4
5
6
7
8
9
10
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:
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
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);
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;
Example:
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;
Example:
Output:
1
2
3
4
6
7
8
9
10