Day 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

An Introduction to Java

CI: Nandan Banerji


JAVA HISTORY

JDK Builds from Oracle (java.net)


FEATURES OF JAVA
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple
programming language because:
• Java syntax is based on C++.
• Java has removed many complicated and rarely-used features, for
example, explicit pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.
FEATURES OF JAVA
Object-oriented
Java is an object-oriented programming language.
• Everything in Java is an object.
• No freefunctions.
• All code belong to someclass.
• Classes are in turn arrangedin a hierarchy or package structure.
FEATURES OF JAVA
Platform Independent
• Languages like C, C++, etc. which are
compiled into platform specific machines.
• Java is Write Once and Run Anywhere
(WORA).
• Java code is compiled by the compiler and
converted into bytecode.
• Java Virtual Machine executes the bytecode.
FEATURES OF JAVA
Secured
Java is best known for its security.
• No explicit pointer
• Java Programs run inside a virtual
machine sandbox
• Classloader
• Bytecode Verifier
• Security Manager
FEATURES OF JAVA
Robust
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the
Java Virtual Machine to get rid of objects which are not being used
by a Java application anymore.
• There are exception handling and the type checking mechanism in
Java.
FEATURES OF JAVA
Architecture-neutral
Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.

Portable
Java is portable because it facilitates you to carry the Java bytecode
to any platform. It doesn't require any implementation.

Multi-threaded
We can write Java programs that deal with many tasks at once by
defining multiple threads.
FEATURES OF JAVA
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes.
It means classes are loaded on demand.

Interpreted
• The program are compiled into Java Virtual Machine (JVM) code
called bytecode
• Each bytecode instruction is translated into machine code at the
time of execution
FEATURES OF JAVA
Distributed
• Java is distributed because it facilitates users to create distributed
applications in Java.
• Fully supports IPv4, with structures to support IPv6
• Includes support for Applets: small programs embedded in HTML
documents
• RMI and EJB are used for creating distributed applications.
• This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
POPULARITY OF JAVA
JAVA PLATFORMS

Used for developing Used for developing Used for developing


applications for small Desktop based large‐scale, distributed
memory‐constrained application and networking applications
devices, such as cell networking and Web‐based
phones, pagers and PDAs applications applications
JAVA ARCHITECTURE
Phase 3: Load

Class Loader Java Class


Libraries
Source
Code Phase 1: Edit
(.java)
Bytecode
Phase 4: Verify
Java Bytecodes Verifier
move locally or
Phase 2: through network
COMPILER
Compile
Java Virtual Machine Phase 5:Execute
(JVM)
Java
Bytecode
(.class>
Operating
Compile-time System
Environment
Hardware

13
Quiz
1. Write the correct order of the Java program execution
A. Class Loader
B. Interpretation
C. Compilation
D. Byte Code Verification
E. Java Source Code
F. Execution
Quiz

2. Which of the following is used to load a .class file?


A. Class Loader
B. Byte Code Verifier
C. JIT Compiler
D. Interpreter
Quiz

3. When a java program is compiled, it creates a


A. an obj file
B. an exe file
C. a .class file
D. a .sh file
First Program

class FirstProgram
{
public static void main(String args[])
{
System.out.println(“This is my First Java Program”);
}
}
Understand First Program

• A Java source file can contain multiple classes, but only one class
can be a public class.
• The source file name must match the name of the public class
defined in the file with the .java extension.
• A public class is accessible across packages.
• Body of every member function of a class (called method in Java)
must be written when the method is declared.
Understand First Program
public static void main(String[] args)
• main is the starting point of every Java application
• public is used to make the method accessible by all
• static is used to make main a static method of class.
• Static methods can be called by JVM without using any object; just using
the class name.
• void means main does not return anything
• String args[ ] represents an array of String objects that holds the
command line arguments passed to the application.
Understand First Program
System.out.println()
– Used to print a line of text followed by a new line
– System is a class inside the Java API
– out is a public static member of class System
– out represents the standard output (similar to stdout or cout)
– println is a public method of the class of which out is an object
We can use the plus operator (+) to concatenate multiple String
objects and create a new String object.
How to Execute a Java Program
1. Using Java Online Compiler
2. Using JDK and Notepad
3. Using Editors and JRE
PATH

• PATH is an environmental variable in DOS(Disk Operating System),


Windows and other operating systems like Unix.

• PATH tells the operating system which directories(folders) to


search for executable files, in response to commands issued by a
user .

• It is a convenient way of executing files without bothering about


providing the absolute path to the folder, where the file is located.
CLASSPATH

• CLASSPATH is a parameter which tells the JVM or the Compiler,


where to locate classes that are not part of Java Development
ToolKit(JDK).

• CLASSPATH is set either on command-line or through


environment variable.

• CLASSPATH set on command-line is temporary in nature, while the


environment variable is permanent.
Naming Conventions
Class Names
➢ Class names should be nouns, in mixed case with the first letter
of each internal word capitalized
➢ Class names should be simple and descriptive
➢ Eg: class Student, class TestStudent

Method Names
➢ Methods should be verbs, in mixed case with the first letter
lowercase, with the first letter of each internal word capitalized
➢ Eg: void run(), void getColor()
Try it and Tell me
Sample.java
class A {
void m1() { }
}
class B {
void m2() { }
}
class C {
void m3() { }
}
Try it and Tell me
class A {
void m1() { }
}
public class B {
void m2() { }
}
class C {
void m3() { }
}

What should be the Source File Name


Try it and Tell me
Sample.java
class Sample {
public static void main() {
System.out.println(“Welcome”);
}
}
• Compilation Error
• Runtime Error
• The program compiles and executes successfully but prints
nothing.
• It will print “Welcome”
JVM Architecture

There are mainly three sub


systems in the JVM as shown in
the above diagram,
1.ClassLoader
2.Runtime Memory/Data Areas
3.Execution Engine
JVM Classloader

Bootstrap ClassLoader: It loads the rt.jar file which contains all


class files of Java Standard Edition.

Extension ClassLoader: It loads the jar files located


inside $JAVA_HOME/jre/lib/ext directory.

System/Application ClassLoader: It loads the classfiles from


classpath.

You can change the classpath using "-cp" or "-classpath" switch.


JVM Classloader
The four main principles in JVM, Class Loader
1. Visibility Principle: ClassLoader of a child can see the class
loaded by Parent but not vice versa.
2. Uniqueness Principle: A class loaded by the parent ClassLoader
shouldn’t be loaded by the child again.
3. Delegation Hierarchy Principle: JVM follows a hierarchy of
delegation to choose the class loader for each class loading
request.
4. No Unloading Principle: class cannot be unloaded by the
Classloader
JVM Classloader
Linking

1. Verification: Whether it is coming from a valid compiler or not


and code has a correct structure and format.

2. Preparation: Static variables memory will be allocated and


assigned with default values based on the data types.

3. Resolution: JVM will assign memory location for those objects by


replacing their symbolic links with direct links.
JVM Memory Areas
Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime
constant pool, field and method data, the code for methods.
Heap
It is the runtime data area in which objects are allocated.
Stack
Java Stack stores frames. It holds local variables and partial results
and plays a part in method invocation and return.
JVM Memory Areas
Program Counter Register
PC (program counter) register contains the address of the Java virtual
machine instruction currently being executed.

Native Method Stack


It contains all the native methods used in the application.
JVM Execution
Execution Engine:
1.Interpreter: Read bytecode stream then execute the instructions.
2. Just-In-Time(JIT) compiler: It is used to improve the performance.
3.Garbage Collector: Mark and Sweep Phases.

Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface
to communicate with another application written in another language
like C, C++, Assembly etc.
Command line arguments
While executing a java program, command line arguments can be
passed by
java Simple <argument1> <argument2>….<argument-n>
args[0] args[1] args[2]

You can access these arguments in your program, using the String
array that you have passed as an argument to the main method.
String[] args
Command line arguments
class Argument {
public static void main(String[] args) {
System.out.println(args[0]);
}
}

If we run java Argument Welcome


What will be the output
Do It Yourself
Write a Program to accept a String as a Command line argument and
the program should print a Welcome message.

Example :

C:\> java Message John

O/P Expected : Welcome John


Command line arguments
class Arguments {
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println(args[1]);
}
}

If we run java Arguments Welcome Sai


What will be the output
Do It Yourself
Write a Program that accepts two Strings as command line arguments
and generate the output in a specific way as given below.

Example:

If the two command line arguments are Wipro and Bangalore then the
output generated should be Wipro Technologies, Bangalore, India.

If the command line arguments are ABC and Mumbai then the output
generated should be ABC Technologies, Mumbai, India

[Note: It is mandatory to pass two arguments in command line]


Finding length of an Array
To find the number of command line arguments that a user may pass
while executing a java program.
args.length

where args is the String array that we pass to the main method and
length is the property of the Array Object
Try it and Tell me
class FindLength{
public static void main(String[ ] args) {
int len = args.length;
System.out.println(len);
}
}

What will be the output of following Executions


java FindLength 1 2 3 4 5 6 7

java FindLength Tom John Lee


Primitive Data Types
Data Size Default Value
Minimum Range Maximum Range
Type (in bits) (for fields)
byte 8 -128 +127 0
short 16 -32768 +32767 0
int 32 -2147483648 +2147483647 0
long 64 -9223372036854775808 +9223372036854775807 0L
float 32 1.40E-45 3.40282346638528860e+38 0.0f

4.94065645841246544e-
double 64 1.79769313486231570e+308d 0.0d
324d
char 16 0 to 65,535 '\u0000'
boolean 1 NA NA false
Try it and Tell me
What will be the result, if we try to compile and execute the
following code?

class Test {
public static void main(String args[]) {
byte b=128;
System.out.println(b);
}
}
Try it and Tell me
What will be the result, if we try to compile and execute the
following code?

class Test {
public static void main(String ar[]) {
double f=1.2;
boolean b=1;
System.out.println(f);
System.out.println(b);
}
}
Try it and Tell me
class Test {
public static void main(String ar[]) {
float f=1;
float b=1.2;
float c=1.2323f;
System.out.println(f);
System.out.println(b);
System.out.println(c);
}
}
Try it and Tell me
class FloatExample
{
public static void main(String args[])
{
float d=987654321.1234567f;
float c=6.123456789f;
System.out.println(d);
System.out.println(c);
}
}
Try it and Tell me
class Test {

public static void main(String [ ] ar) {

int a=10,b=017,c=0X3A;

System.out.println(a+","+b+","+c);

}
Basically if an assigned integer value begins with 0,it is considered to be an octal value.
If the assigned integer value begins with 0x it is taken as hexadecimal value.
Type Casting
Type casting is when you assign a value of one primitive data type to
another type.
Widening Casting (automatically) - converting a smaller type to a larger
type size

byte -> short -> char -> int -> long -> float -> double

Narrowing Casting (manually) - converting a larger type to a smaller


size type

double -> float -> long -> int -> char -> short -> byte
Try it and Tell me
class WideType {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt;
System.out.println(myInt);
System.out.println(myDouble);
}
}
Try it and Tell me
class NarrowCast{
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble;
System.out.println(myDouble);
System.out.println(myInt);
}
}
Parsing
Parsing in its most general sense is the extraction of the necessary
information from some piece of data, most often textual data.

There are many Java classes that have the parse() method.

Usually the parse() method receives some string as input, "extracts" the
necessary information from it and converts it into an object of the calling
class.

Integer

static int parseInt(String s) Ex: Integer.parseInt(“10”);

static int parseInt(String s, int radix) Ex: Integer.parseInt(101,2)


Try it and Tell me
class ParseEx{
static public void main(String[] args) {
int i1 = Integer.parseInt(args[0]);
int i2 = Integer.parseInt(args[1]);
System.out.println(i1+i2);
System.out.println(i1+i2+20);
}
}
When we compile the above code successfully and execute it as
Java ParseEx 10 20
the output will be
Do It Yourself
Write a program to accept two numbers a and b as
arguments for Division.java
Store the value of a/b in c and display c value.
Keywords
abstract continue for new switch

assert default goto package synchronized


boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
Try it and Tell me
What will be the result, if we try to compile and execute the
following code?

class Test {
public static void main(String [ ] ar) {
int for=2;
System.out.println(for);
}
}
Operators
• Java provides a set of operators to manipulate operations.
• Types of operators in java are,
– Arithmetic Operators
– Unary Operator
– Relational Operators
– Logical Operators
– Simple Assignment Operator
– Bitwise Operators
Arithmetic Operators
Operator Description Example

+ Addition A +B

- Subtraction A -B

* Multiplication A *B

/ Division A/B

% Modulus A%B
Do It Yourself
Write a program to accept two arguments of integer type and perform all
the arithmetic operations and display the outputs.
Example: java Calc 20 5
Output:
The value of A is 20 and B is 5
The result of A + B is 25
The result of A - B is 15
The result of A * B is 100
The result of A / B is 4
The result of A%B is 0
Unary Operators

Operator Description Example


+ Unary plus operator +A
- Unary minus operator -A
++ Increment operator ++A or A++
-- Decrement operator --A or A--
Try it and Tell me
class Sample
{
public static void main(String args[])
{
int a = 10;
System.out.println("a value is "+a);
int b=++a;
System.out.println("b value is "+b);
int c=a++;
System.out.println("c value is "+c);
System.out.println("Final a value is "+a);
}
}
Relational Operators
Operator Description Example
== Two values are checked, and if equal, then the condition becomestrue (A == B)

!= Two values are checked to determine whether they are equal or not, and if not (A != B)
equal, then the condition becomes true
> Two values are checked and if the value on the left is greater than the value (A > B)
on the right, then the condition becomes true.
< Two values are checked and if the value on the left is less than the value on the (A < B)
right, then the condition becomes true
>= Two values are checked and if the value on the left is greater than equal to the (A >= B)
value on the right, then the condition becomes true
<= Two values are checked and if the value on the left is less than equal to the value (A <= B)
on the right, then the condition becomes true
Try it and Tell me
class Sample{
public static void main(String[] args){
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
Logical Operators
Operator Description Example

&& This is known as Logical AND & it combines two variables or (A && B) is false
expressions and if and only if both the operands are true, then
it will return true

|| This is known as Logical OR & it combines two variables or (A || B) is true


expressions and if either one is true or both the operands are
true, then it will return true

! Called Logical NOT Operator. It reverses the value of a !(A && B) is true
Boolean expression
Try it and Tell me
class Sample{
public static void main(String[] args){
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b) );
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b) );
}
}
Shift Operators <<and >>
• The shift operators(<< and >>) shift the bits of a number to the
left or right, resulting in a new number.

• They are used only on integral numbers( and not on floating point
numbers, i.e. decimals).

• The right shift operator(>>) is used to divide a number in the


multiples of 2.

• The left shift operator(<<) is used to multiply a number in the


multiples of 2.
Right Shift Operator >>
• When we apply the right shift operator >>, the value gets divided
by 2 to the power of number specified after the operator.
• int x = 16;
• x = x >> 3;
• 16 will be divided by the value 2 to the power of 3, which is 8.
• The result is 2.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
Left Shift Operator <<
• When we apply the left shift operator <<, the value gets multiplied
by 2 to the power of number specified after the operator.
int x = 8;
x = x << 4;
• 8 will be multiplied by the value 2 to the power of 4, which is 16.
• The result is 128.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
Do It Yourself
Write a program to accept two numbers.
Perform the following operations
1. Left shift the First number by second number
of times
2. Right Shift the first number by second number
of times
Bitwise Operators
The bitwise operators take two bit numbers, use OR/AND to determine
the result on a bit by bit basis.

The 3 bitwise operators are :

• & (which is the bitwise AND)

• | (which is the bitwise inclusive OR)

• ^ (which is the bitwise exclusive OR)


Bitwise & Operators
class BitwiseExample1 {
public static void main(String[] args) {
int x = 7;
7-> 0111
int y = 9; 9-> 1001
int z = x & y;
0001
System.out.println("z = "+z);
}
}
Bitwise | Operators
class BitwiseExample2 {
public static void main(String[] args) {
int x = 5;
5-> 0101
int y = 9;
9-> 1001
int z = x | y;
System.out.println("z = "+z); 1101

}
}
Bitwise ^ Operators
class BitwiseExample3 {
public static void main(String[] args) {
int x = 5;
int y = 9; 5-> 0101
int z = x ^ y; 9-> 1001

System.out.println("z = "+z);
1100
}
}
Do It Yourself
Write a program to accept two numbers.
Perform the following operations
1. Bitwise AND operation on a and b
2. Bitwise OR operation on a and b
3. Bitwise EXOR operation on a and b
Do It Yourself
Write a program to print all the arguments passed to a FindArguments.java
program.
Input: Number of arguments can be 0 to 12
Output Format:
The Number of Arguments are :
Example: java FindArguments Hi Nandan
The Following are the Arguments: Output:
The Number of Arguments are : 3
The Following are the Arguments:
1 Hi
2 Sai
3 Kiran
THANK YOU

You might also like