Java Unit1
Java Unit1
Unit 1
Java
Java Example
class Simple
System.out.println("Hello Java");
1
}
According to Sun, 3 billion devices run java. There are many devices where
java is currently used. Some of them are as follows:
1) Standalone Application
2) Web Application
An application that runs on the server side and creates dynamic page, is
called web application. Currently, servlet, jsp, struts, jsf etc. technologies
are used for creating web applications in java.
2
3) Enterprise Application
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java
ME are used for creating mobile applications.
3
Comparison Index C++ Java
Mainly used for C++ is mainly used for Java is mainly used for application
system programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.
Pointers C++ supports pointers. You Java supports pointer internally. But
can write pointer program in you can't write the pointer program in
C++. java. It means java has restricted
pointer support in java.
Compiler and C++ uses compiler only. Java uses compiler and interpreter
Interpreter both.
Call by Value and C++ supports both call by Java supports call by value only. There
Call by reference value and call by reference. is no call by reference in java.
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies
on third-party libraries for
thread support.
Virtual Keyword C++ supports virtual Java has no virtual keyword. We can
keyword so that we can override all non-static methods by
4
decide whether or not default. In other words, non-static
override a function. methods are virtual by default.
unsigned right C++ doesn't support >>> Java supports unsigned right shift >>>
shift >>> operator. operator that fills zero at the top for
the negative numbers. For positive
numbers, it works same like >>
operator.
Inheritance Tree C++ creates a new Java uses single inheritance tree
inheritance tree always. always because all classes are the child
of Object class in java. Object class is
the root of inheritance tree in java.
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
5
static is a keyword, if we declare any method as static, it is known as
static method. The core advantage of static method is that there is no
need to create object to invoke the static method. The main method is
executed by the JVM, so it doesn't require to create object to invoke
the main method. So it saves memory.
void is the return type of the method, it means it doesn't return any
value.
main represents startup of the program.
String[] args is used for command line argument. We will learn it
later.
System.out.println() is used print statement. We will learn about the
internal working of System.out.println statement later.
To write the simple program, open notepad by start menu -> All
Programs -> Accessories -> notepad and write simple program as
displayed below:
6
As displayed in the above diagram, write the simple program of java in
notepad and saved it as Simple.java. To compile and run this program, you
need to open command prompt by start menu -> All Programs ->
Accessories -> command prompt.
7
To compile and run the above program, go to your current directory first;
my current directory is c:\new . Write here:
To compile: javac Simple.java
To execute: java Simple
In the previous page, we have learned about the first program, how to
compile and how to run the first java program. Here, we are going to learn,
what happens while compiling and running the java program. Moreover, we
will see some question based on the first program.
8
What happens at compile time?
At compile time, java file is compiled by Java Compiler (It does not interact
with OS) and converts the java code into bytecode.
In this page, we will learn about the variable and java data types. Variable
is a name of memory location. There are three types of variables: local,
instance and static. There are two types of datatypes in java, primitive
and non-primitive.
Variable
9
int data=50;//Here data is variable
Types of Variable
There are three types of variables in java
local variable
instance variable
static variable
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called
instance variable . It is not declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be
10
local.
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
11
Operators in java
Operators Precedence
multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
ternary ? :
12
The Java if statement is used to test the condition. It returns 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 if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
13
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
14
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example:
15
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
20
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:
16
public class ForExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
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:
while(condition){
//code to be executed
}
Example:
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 while loop.
17
It is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
Example:
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:
jump-statement;
break;
Example:
public class BreakExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
18
}
}
}
Syntax:
jump-statement;
continue;
Example:
19
Smalltalk is considered as the first truly object-oriented programming
language.
Object means a real word entity such as pen, chair, table etc.Object-
Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies the software development and
maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example:
chair, pen, table, keyboard, bike etc. It can be physical and logical.
Class
Inheritance
Polymorphism
20
In java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog
barks woof etc.
Abstraction
Encapsulation
Binding (or wrapping) code and data together into a single unit is
known as encapsulation. For example: capsule, it is wrapped with
different medicines.
21
Object and Class in Java
Object is the physical as well as logical entity whereas class is the logical
entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc. It can be physical or logical (tengible and
intengible). The example of integible object is banking system.
For Example: Pen is an object. Its name is Reynolds, color is white etc.
known as its state. It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from
22
which objects are created. So object is the instance(result) of a class.
Class in Java
data member
method
constructor
block
class and interface
class <class_name>
{
data member;
method;
}
In this example, we have created a Student class that have two data
members id and name. We are creating the object of the Student class by
new keyword and printing the objects value.
class Student1
{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
23
}
Method in Java
In java, a method is like function i.e. used to expose behaviour of an
object.
Advantage of Method
Code Reusability
Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
class Student2{
int rollno;
String name;
24
void displayInformation(){System.out.println(rollno+" "+name);}//method
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
111 Karan
222 Aryan
class Rectangle{
int length;
int width;
void calculateArea(){System.out.println(length*width);}
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
25
There are many ways to create an object in java. They are:
By new keyword
By newInstance() method
By clone() method
void calculateArea(){System.out.println(length*width);}
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
26
Method Overloading
Suppose you have to perform addition of the given numbers but there can
be any number of arguments, if you write the method such as a(int,int) for
two parameters, and b(int,int,int) for three parameters then it may be
difficult for you as well as other programmers to understand the behaviour
of the method because its name differs. So, we perform method overloading
to figure out the program quickly.
In this example, we have created two overloaded methods, first sum method
performs addition of two numbers and second sum method performs
27
addition of three numbers.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.
10. }
11. }
Output:30
40
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
}
}
Output:21.0
40
Why Method Overloaing is not possible by changing the return type of method
28
In java, method overloading is not possible by changing the return type of
the method because there may occur ambiguity. Let's see how ambiguity
may occur:
class Calculation3{
int sum(int a,int b){System.out.println(a+b);}
double sum(int a,int b){System.out.println(a+b);}
}
}
Yes, by method overloading. You can have any number of main methods in a
class by method overloading. Let's see the simple example:
class Overloading1{
public static void main(int a){
System.out.println(a);
}
29
Constructor
Default Constructor
A constructor that have no parameter is known as default constructor.
30
Syntax of default constructor:
1. <class_name>(){}
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Default constructor provides the default values to the object like 0, null etc.
depending on the type.
class Student3{
int id;
String name;
31
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Test it Now
Output:
0 null
0 null
parameterized constructor
32
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have
any number of constructors that differ in parameter lists.The compiler
differentiates these constructors by taking into account the number of
parameters in the list and their type.
33
Output:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are
given below.
Constructor is used to initialize the state of an object. Method is used to expose behaviour
of an object.
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if Method is not provided by compiler
you don't have any constructor. in any case.
Constructor name must be same as the class name. Method name may or may not be
same as class name.
static keyword
34
The static keyword in java is used for memory management mainly. We
can apply java static keyword with variables, methods, blocks and nested
class. The static keyword belongs to the class than instance of the class.
static variable
The static variable can be used to refer the common property of all
objects (that is not unique for each object) e.g. company name of
employees,college name of students etc.
The static variable gets memory only once in class area at the time of
class loading.
class Student8{
int rollno;
35
String name;
static String college ="ITS";
s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS
class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
36
}
Output:1
1
1
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;
System.out.println(count);
}
}
}
Output:1
2
3
If you apply static keyword with any method, it is known as static method.
37
Example of static method
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
38
Java static block
o Is used to initialize the static data member.
o It is executed before main method at the time of classloading.
Ans) Yes, one of the way is static block but in previous version of JDK not in
JDK 1.7.
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
} Output:static block is invoked (if not JDK7)
39