Unit 1 Complete V2
Unit 1 Complete V2
Unit 1 Complete V2
Prepared By:
Deepak Kumar Sharma
Asst. Professor
Department of Informatics
UPES Dehradun
UNIT-I
JAVA BASICS
History of Java
Java buzzwords
Data types
Variables
Simple java program
scope and life time of variables
Operators, expressions, control statements
Type conversion and casting
Arrays
Classes and objects – concepts of classes, objects
Constructors, methods
Access control
This keyword
Garbage collection
Overloading methods and constructors
Parameter passing
Recursion
static
Deepak Sharma, Asst. Professor, UPES Dehradun
History of Java
Java started out as a research project.
Object Oriented
Focus on the data (objects) and methods manipulating the data
All methods are associated with objects
Potentially better code organization and reuse
Architecture-Neutral
Goal of java designers is “write once; run anywhere,
any time, forever.”
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
Java
Byte
codes Java Just-in-time
Java
move Interpreter Compiler
Compiler
locally
or
through Run Time System
n/w
Java Java OS W32
Win Solaris
Byte codes
MAC Others
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Output:Hello Java
Objects
Classes
Data abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic Binding
class object
Objects are instances of the type class.
The wrapping up of data and functions into a single unit ( called class) is known
as encapsulation. Data encapsulation is the most striking features of a class.
Inheritance is the process by which objects of one class acquire the properties
of another class. The concept of inheritance provides the reusability.
Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
The principle of data hiding helps the programmer to build secure programs.
Real-time systems
Object-oriented databases
CAD/CAM systems
float double
byte
Byte data type is an 8-bit signed two's complement integer
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in
place of integers, since a byte is four times smaller than an
integer.
Example: byte a = 100, byte b = -50
short
Short data type is a 16-bit signed two's complement integer
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data
type. A short is 2 times smaller than an integer
Default value is 0.
Example: short s = 10000, short r = -20000
int
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648 (-2^31)
Maximum value is 2,147,483,647(inclusive) (2^31 -1)
Integer is generally used as the default data type for integral
values unless there is a concern about memory.
The default value is 0
Example: int a = 100000, int b = -200000
long
Long data type is a 64-bit signed two's complement integer
Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807
(inclusive)(2^63 -1)
This type is used when a wider range than int is needed
Default value is 0L
Example: long a = 100000L, long b = -200000L
float
Float data type is a single-precision 32-bit IEEE 754 floating
point
Float is mainly used to save memory in large arrays of
floating point numbers
Default value is 0.0f
Float data type is never used for precise values such as
currency
Example: float f1 = 234.5f
double
double data type is a double-precision 64-bit IEEE 754
floating point
This data type is generally used as the default data type for
decimal values, generally the default choice
Double data type should never be used for precise values
such as currency
Default value is 0.0
Example: double d1 = 123.4
boolean
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for simple flags that track true/false
conditions
Default value is false
Example: boolean one = true
char
char data type is a single 16-bit Unicode character
Minimum value is '\u0000' (or 0)
Maximum value is '\uffff' (or 65,535 inclusive)
Char data type is used to store any character
Example: char letterA = 'A'
float f1 = Float.MAX_VALUE;
float f2 = Float.MIN_VALUE ;
double d1 = Double.MAX_VALUE;
double d2 = Double.MIN_VALUE ;
Types
Instance Variable
Class/Static Variable
Local Variable
void states that the main method will not return any value.
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
• Each time a new object is created, at least one constructor will be invoked.
• The main rule of constructors is that they should have the same name as
the class.
public Puppy() {
}
}
void display(){
System.out.println("display:main");
}
}
Deepak Sharma, Asst. Professor, UPES Dehradun
Creating Objects
There are three steps when creating an object from a class −
Lifetime
The lifetime of a declared element is the period of time during which it is
alive.
A block begins with an opening curly brace and ends by a closing curly
brace.
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Operator Result
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
Operator Result
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
–– Decrement
Deepak Sharma, Asst. Professor, UPES Dehradun
Example:
class IncDec{
public static void main(String args[]){
int a = 1;
int b = 2;
int c,d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
Deepak Sharma, Asst. Professor, UPES Dehradun
class OpEquals{
public static void main(String args[]){
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
Operator Result
|= Bitwise OR assignment
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Deepak Sharma, Asst. Professor, UPES Dehradun
Example:
class Test{
public static void main(String args[]){
int denom=0,num=20;
if (denom != 0 && num / denom > 10)
System.out.println("Hi");
}
}
= += -= *= /= %=
assignment right to left
&= ^= |= <<= >>= >>>=
Deepak Sharma, Asst. Professor, UPES Dehradun
Expressions
Ex1: x = 1;
Ex2: y = 100 + x;
Ex3: x = (32 - y) / (x + 5)
while(condition) do
{ {
// body of loop // body of loop
} } while (condition);
•Instead of declaring and initializing a loop counter variable, you declare a variable
that is the same type as the base type of the array, followed by a colon, which is
then followed by the array name.
•In the loop body, you can use the loop variable you created rather than using an
indexed array element.
•It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
Syntax:
for (int i=0; i<arr.length; i++)
{
for (type var : array)
type var = arr[i];
{
statements using var;
statements using var;
}
}
class For_Each
{
public static void main(String[] arg) {
int[] marks = { 125, 172, 95, 116, 110 };
int highest_marks = marks[0];
for (int num : marks)
{
if (num > highest_marks)
{
highest_marks = num;
}
}
System.out.println("The highest score is " + highest_marks);
}
}
label:
----
----
break label; //it’s like goto
statement
• Package in java can be categorized in two form, built-in package and user-
defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.
Deepak Sharma, Asst. Professor, UPES Dehradun
How to access package from another package?
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*; Output:Hello
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} t:Hello
}
Deepak Sharma, Asst. Professor, UPES Dehradun
Output:Hello
//save by B.java
package mypack; Output:Hello
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} Deepak Sharma, Asst. Professor, UPES Dehradun
}
How to access package from another package?
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
} Deepak Sharma, Asst. Professor, UPES Dehradun
Note: If you import a package, subpackages will not be imported.
Access Modifiers in Java
There are two types of modifiers in Java:
access modifiers
non-access modifiers.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
} Deepak Sharma, Asst. Professor, UPES Dehradun
}
Public
The public access modifier is accessible everywhere. It
has the widest scope among all other modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Deepak Sharma, Asst. Professor, UPES Dehradun
//Example for access control
class AccessTest {
class Test {
int a; // default access public static void main(String args[]) {
public int b; // public access
private int c; // private access Test ob = new Test();
/*protected applies only
// These are OK, a and b may be accessed directly
when inheritance is involved*/ ob.a = 10;
ob.b = 20;
// methods to access c
// This is not OK and will cause an error
//ob.c = 100; // Error!
void setc(int i){
c = i; // set c's value // You must access c through its methods
ob.setc(100); // OK
}
int getc() { System.out.println(ob.a + " " +ob.b + " " + ob.getc());
}
return c; // get c's value }
}
}
Deepak Sharma, Asst. Professor, UPES Dehradun
Scanner Class in Java
Scanner: Helps in reading inputs from many sources.
Communicates with System.in
Can also read from files, web sites, databases, ...
Example:
Scanner console = new Scanner(System.in);
Deepak Sharma, Asst. Professor, UPES Dehradun
Scanner Class- Input types
Method Description
// String input
String name = sc.nextLine();
// Character input
char gender = sc.next().charAt(0);
System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Age: "+age);
System.out.println("Mobile Number: "+mobileNo);
System.out.println("CGPA: "+cgpa);
}
} Deepak Sharma, Asst. Professor, UPES Dehradun
Concepts of Classes, Objects
Representation 2:
Box mybox=new Box();
A constructor has the same name as the class in which it resides and is
syntactically similar to a method.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or
sort the data efficiently.
Random access:We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
But you can have formal parameters to methods, which overlap with the
names of the class’ instance variables.
this can be used to resolve any name collisions that might occur between
instance variables and formal variables.
When a formal variable has the same name as an instance variable, the formal
variable hides the instance variable.
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
class A{ class A{
int a=40;//non static static int a=40;//static
public static void main(String args[]){ public static void main(String args[]){
System.out.println(a); System.out.println(a);
} }
} }
class A2{
A2(){System.out.println("Constructor Called");}
static{
System.out.println("static block is invoked");
}