Java Unit - I Notes

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

JAVA

(Unit – I)

 Developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation.


 Developed by James Gosling and Patrick Naughton.
 Simple programming language.
 Writing, compiling and debugging a program is easy in java.
 Create modular programs and reusable code.

Java Virtual Machine (JVM)


we write the program, then we compile the program and at last we run the program.

1) Writing of the program is of course done by java programmer like you and me.
2) Compilation of program is done by javac compiler, javac is the primary java compiler included in java
development kit (JDK). It takes java program as input and generates java bytecode as output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called program run phase.

Each operating system has different JVM, however the output they produce after execution of
bytecode is same across all operating systems. That is why we call java as platform independent
language.

Bytecode:

As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it can be
executed by JVM. The bytecode is saved in a .class file by compiler.

Java Development Kit(JDK):

This is complete java development kit that includes JRE (Java Runtime Environment), compilers and
various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed on your computer.

Java Runtime Environment(JRE):

JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on your system, you
can run a java program however you won’t be able to compile it. JRE includes JVM, browser plugins and
applets support. When you only need to run a java program on your computer, you would only need JRE.

Main Features of JAVA

Java is a platform independent language


Java is an Object Oriented language

4 main concepts of Object Oriented programming are:

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

1. 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.

2. Robust Language - Robust means reliable. Java programming language is developed in a way
that puts a lot of emphasis on early checking for possible errors, that’s why java compiler is able
to detect errors that are not easy to detect in other programming languages. The main features
of java that makes it robust are garbage collection, Exception Handling and memory allocation.

3. Secure - We don’t have pointers and we cannot access out of bound arrays (you get
ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several security flaws
like stack corruption or buffer overflow is impossible to exploit in Java.

4. Java is distributed - Using java programming language we can create distributed applications.
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.

5. Multithreading - Java supports multithreading. Multithreading is a Java feature that allows


concurrent execution of two or more parts of a program for maximum utilisation of CPU.

6. 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.

Syntax:

class HelloWorld
{
public static void main (String[] args)
{
System.out.println("Hello World!");
}
}

First we will be set the path then perform following operations:


Command prompt:
>cd desktop
>javac classname.java
>java classname

Save this file as HelloWorld.java.

Hello World!
Variables in Java
A variable is a name which is associated with a value that can be changed.

For example: when I write int i=10; here variable name is i which is associated with value 10, int is a data
type that represents that this variable can hold integer values.

How to declare a variable in Java

Syntax:
data_type variable_name = value;

Variables naming convention in java

1) Variables naming cannot contain white spaces.


For example: int num ber = 100; is invalid because the variable name has space in it.

2) Variable name can begin with special characters such as $ and _.


3) Variable name should begin with a lower case letter.
4) Variable names are case sensitive in Java.

Types of Variables in Java:

There are three types of variables in Java.

1. Local variable
2. Static (or class) variable
3. Instance variable

Static (or class) Variable

Static variables are also known as class variable because they are associated with the class and common
for all the instances of class.

For example, if I create three objects of a class and access this static variable, it would be common for all,
the changes made to the variable using one of the object would reflect when you access it through other
objects.

Instance variable

Each instance (objects) of class has its own copy of instance variable. Unlike static variable, instance
variables have their own separate copy of instance variable. We have changed the instance variable
value using object obj2 in the following program and when we displayed the variable using all three
objects, only the obj2 value got changed, others remain unchanged. This shows that they have their own
copy of instance variable.

Local Variable
These variables are declared inside method of the class. Their scope is limited to the method which
means that you can’t change their values and access them outside of the method.

Data Types in Java


Data type defines the values that a variable can take.

For Example - if a variable has int data type, it can only take integer values. In java we have two
categories of data type:

1. Primitive data types


2. Non-primitive data types – Arrays and Strings are non-primitive data types, Java is a statically
typed language. A language is statically typed, if the data type of a variable is known at compile
time. This means that you must specify the type of the variable (Declare the variable) before you
can use it.

1. Primitive data types - In Java, we have eight primitive data types: boolean, char, byte, short, int,
long, float and double.

 byte, short, int and long data types are used for storing whole numbers.
 float and double are used for fractional numbers.
 char is used for storing characters(letters).
 boolean data type is used for variables that holds either true or false.

class JavaExample {
public static void main(String[] args) {

short num;

num = 150;
System.out.println(num);
}
}

Output:

150

Literals in Java

A literal is a fixed value that we assign to a variable in a Program.

int num=10;

Here value 10 is a Integer literal.

char ch = 'A';
Here A is a char literal

Integer Literal

Integer literals are assigned to the variables of data type byte, short, int and long.

byte b = 100;
short s = 200;
int num = 13313131;
long l = 928389283L;

Float Literals

Used for data type float and double.

double num1 = 22.4;


float num2 = 22.4f;

Unicode System
1. Computers just deal with numbers. They store letters and other characters by assigning a
number for each one. For example – A = U + 0041, B = U + 0042.
2. Unicode provides a unique number for every character, no matter what the platform, no matter
what the language, no matter what the program. Example – A = U + 0041, B = U + 0042, C = U +
0043, D = U + 0044.
3. The Unicode system has been adopted by such industry leaders like Apple, HP, IBM, Just
Systems, Microsoft, Oracle and many others. Unicode is required by modern standards such as
XML, JAVA, ECMAScript (JavaScript), COBRA 3.0, WML, LDAP etc.
4. It is supported in many Operating Systems, all modern browsers, and many other products.
5. Unicode and ASCII code are both ways that computer languages store characters as numbers.
ASCII stands for “American Standard Code for Information Interchange” and it allows encoding
for 128 characters. This is fine for English language, but not enough for others. Unicode can
handle 100,000 characters, so by using this encoding scheme, JAVA allows programmers to work
with printed languages from around the world.

Why we need Unicode?

Before Unicode was invented, there were hundreds of different encoding systems for assigning this
number. No single encoding could contain enough characters: For example, the European Union alone
requires several different encodings to cover all its languages. Even for a single language like English no
single encoding was adequate for all the letters, punctuation, and technical symbols in common use.
These encoding systems also collide with one another. That is, two encodings can use the same number
for two different characters, or use different numbers for the same character. Any given computer
(especially servers) needs to support many different encodings; yet whenever data is passed between
different encodings or platforms, the data always runs the risk of corruption.
Java Naming Convention

Java naming convention is a rule to follow as you decide what to name your identifiers such as class,
package, variable, constant, method, etc.

But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by
several Java communities such as Sun Microsystems and Netscape.

All the classes, interfaces, packages, methods and fields of Java programming language are given
according to the Java naming convention. If you fail to follow these conventions, it may generate
confusion or erroneous code.

Identifiers
Naming Rules Examples
Type
public class Employee
It should start with the uppercase letter. {
Class
Use appropriate words. //code snippet
}
interface Printable
It should start with the uppercase letter. {
Interface
Use appropriate words. //code snippet
}
class Employee
{
It should start with lowercase letter. // method
If the name contains multiple words, start it with a lowercase void draw()
Method
letter followed by an uppercase letter such as {
actionPerformed(). //code snippet
}
}
1. It should start with a lowercase letter such as id,
name. class Employee
2. It should not start with the special characters like & {
(ampersand), $ (dollar), _ (underscore). // variable
Variable
3. If the name contains multiple words, start it with the int id;
lowercase letter followed by an uppercase letter //code snippet
such as firstName, lastName. }
4. Avoid using one-character variables such as x, y, z.
//package
package com.javatpoint;
It should be a lowercase letter such as java, lang.
class Employee
Package If the name contains multiple words, it should be separated
{
by dots (.) such as java.util, java.lang.
//code snippet
}
1. It should be in uppercase letters such as RED, class Employee
YELLOW. {
2. If the name contains multiple words, it should be //constant
Constant
separated by an underscore(_) such as static final int MIN_AGE =
MAX_PRIORITY. 18;
3. It may contain digits but not as the first letter. //code snippet
}

Operators in Java

An operator that represents an action, for example + is an arithmetic operator that represents addition.

Types of Operator in Java:

1) Basic Arithmetic Operators


2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Ternary Operator

1) Basic Arithmetic Operators - Basic arithmetic operators are: +, -, *, /, %

Example of Arithmetic Operators

class ArithmeticOperatorDemo {
public static void main(String args[]) {
int num1 = 100;
int num2 = 20;

System.out.println("num1 + num2: " + (num1 + num2) );


System.out.println("num1 - num2: " + (num1 - num2) );
System.out.println("num1 * num2: " + (num1 * num2) );
System.out.println("num1 / num2: " + (num1 / num2) );
System.out.println("num1 % num2: " + (num1 % num2) );
}
}

num1 + num2: 120


num1 - num2: 80
num1 * num2: 2000
num1 / num2: 5
num1 % num2: 0

2) Assignment Operators

 Assignments operators in java are: =, +=, -=, *=, /=, %=


num2 = num1 would assign value of variable num1 to the variable.
 num2+=num1 is equal to num2 = num2+num1
 num2-=num1 is equal to num2 = num2-num1
 num2*=num1 is equal to num2 = num2*num1
 num2/=num1 is equal to num2 = num2/num1
 num2%=num1 is equal to num2 = num2%num1

Example of Assignment Operators

class AssignmentOperatorDemo {
public static void main(String args[]) {
int num1 = 10;
int num2 = 20;

num2 = num1;
System.out.println("= Output: "+num2);

num2 += num1;
System.out.println("+= Output: "+num2);

num2 -= num1;
System.out.println("-= Output: "+num2);

num2 *= num1;
System.out.println("*= Output: "+num2);

num2 /= num1;
System.out.println("/= Output: "+num2);

num2 %= num1;
System.out.println("%= Output: "+num2);
}
}

Output:

= Output: 10
+= Output: 20
-= Output: 10
*= Output: 100
/= Output: 10
%= Output: 0

3) Auto-increment and Auto-decrement Operators - ++ and —

num + + is equivalent to num = num + 1;


num - - is equivalent to num = num - 1;

Example of Auto-increment and Auto-decrement Operators

class AutoOperatorDemo {
public static void main(String args[]){
int num1=100;
int num2=200;
num1++;
num2--;
System.out.println("num1++ is: "+num1);
System.out.println("num2-- is: "+num2);
}
}

Output:

num1++ is: 101


num2-- is: 199

4) Logical Operators

Logical Operators are used with binary variables. They are mainly used in conditional statements and
loops for evaluating a condition.

Logical operators in java are: &&, ||, !

Let’s say we have two boolean variables b1 and b2.

1. b1 && b2 will return true if both b1 and b2 are true else it would return false.
2. b1 || b2 will return false if both b1 and b2 are false else it would return true.
3. !b1 would return the opposite of b1, that means it would be true if b1 is false and it would
return false if b1 is true.

Example of Logical Operators

class LogicalOperatorDemo {
public static void main(String args[]) {
boolean b1 = true;
boolean b2 = false;

System.out.println("b1 && b2: " + (b1&&b2));


System.out.println("b1 || b2: " + (b1||b2));
System.out.println("!(b1 && b2): " + !(b1&&b2));
}}

Output:

b1 && b2: false


b1 || b2: true
!(b1 && b2): true

5) Comparison (Relational) operators


We have six relational operators in Java: ==, !=, >, <, >=, <=

1. == returns true, if both the left side and right side are equal
2. != returns true, if left side is not equal to the right side of operator.
3. > returns true, if left side is greater than right.
4. < returns true, if left side is less than right side.
5. >= returns true, if left side is greater than or equal to right side.
6. <= returns true, if left side is less than or equal to right side.

Example of Relational operators:

class RelationalOperatorDemo {
public static void main(String args[]) {
int num1 = 10;
int num2 = 50;
if (num1==num2) {
System.out.println("num1 and num2 are equal");
}
else{
System.out.println("num1 and num2 are not equal");
}

if( num1 != num2 ){


System.out.println("num1 and num2 are not equal");
}
else{
System.out.println("num1 and num2 are equal");
}

if( num1 > num2 ){


System.out.println("num1 is greater than num2");
}
else{
System.out.println("num1 is not greater than num2");
}

if( num1 >= num2 ){


System.out.println("num1 is greater than or equal to num2");
}
else{
System.out.println("num1 is less than num2");
}

if( num1 < num2 ){


System.out.println("num1 is less than num2");
}
else{
System.out.println("num1 is not less than num2");
}

if( num1 <= num2){


System.out.println("num1 is less than or equal to num2");
}
else{
System.out.println("num1 is greater than num2");
}
}
}

Output:

num1 and num2 are not equal


num1 and num2 are not equal
num1 is not greater than num2
num1 is less than num2
num1 is less than num2
num1 is less than or equal to num2

6) Ternary Operator

This operator evaluates a boolean expression and assign the value based on the result.

Syntax:

variable num1 = (expression) ? value if true : value if false

If the expression results true then the first value before the colon (:) is assigned to the variable num1
else the second value is assigned to the num1.

Example of Ternary Operator

class TernaryOperatorDemo {

public static void main(String args[]) {


int num1, num2;
num1 = 25;
num2 = (num1 == 10) ? 100: 200;
System.out.println( "num2: "+num2);
num2 = (num1 == 25) ? 100: 200;
System.out.println( "num2: "+num2);
}
}

Output:

num2: 200
num2: 100
Java decision-making statements
1. Java decision-making statements allow you to make a decision, based upon the result of a
condition.
2. All the programs in Java have set of statements, which are executed sequentially in the order in
which they appear. It happens when jumping of statements or repetition of certain calculations
is not necessary.
3. A programming language uses control statements to control the flow of execution of program
based on certain conditions.

Java’s Selection statements:

1. if
2. if-else
3. nested-if
4. if-else-if
5. switch-case
6. jump – break, continue, return

These statements allow you to control the flow of your program’s execution based upon conditions
known only during run time.

1. if: if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statement is executed otherwise not.

Syntax:

if(condition) {

// Statements to execute if condition is true

}
Example:

class IfDemo {
public static void main(String args[]) {
int i = 10;
if (i > 15)
System.out.println("10 is less than 15");

System.out.println("I am Not in if");


}}
2. if-else: The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if the
condition is false. Here comes the else statement. We can use the else statement with if
statement to execute a block of code when the condition is false.

Syntax:

if (condition){
// Executes this block if condition is true
}
else{
// Executes this block if condition is false
}
Example:

class IfElseDemo {
public static void main(String args[]) {
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}

3. nested-if: A nested if is an if statement that is the target of another if or else. Nested if


statements means an if statement inside an if statement. Yes, java allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if statement.

Syntax:

if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Example:
class NestedIfDemo {
public static void main(String args[]) {
int i = 10;
if (i == 10) {
if (i < 15)
System.out.println("i is smaller than 15");
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}}

4. if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed
from the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.

Syntax:

if (condition)
statement;
else if (condition)
statement;
else
statement;

Example:

class ifelseifDemo {
public static void main(String args[]) {
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}

5. switch-case: The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.

Syntax:

switch (expression){
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

Example:
class SwitchCaseDemo {
public static void main(String args[]) {
int i = 9;
switch (i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
6. jump: Java supports three jump statement: break, continue and return. These three statements
transfer control to other part of the program.

Break: In Java, break is majorly used for: Terminate a sequence in a switch statement (discussed
above). To exit a loop. Using break, we can force immediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop.

Example:

class BreakLoopDemo {
public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}

Continue: Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for this
particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The
continue statement performs such an action.

Example:

class ContinueDemo {
public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
if (i == 5)
continue;
System.out.print(i + " ");
}
}
}

Loops in Java
Looping in programming languages is a feature which facilitates the execution of a set of
instructions/functions repeatedly while some condition evaluates to true.
Java provides three ways for executing the loops. While all the ways provide similar basic functionality,
they differ in their syntax and condition checking time.

1. while loop: A while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating if
statement.

Syntax :

while (boolean condition){


loop statements...
}
While loop starts with the checking of condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. For this reason
it is also called Entry control loop. When the condition becomes false, the loop terminates which
marks the end of its life cycle.

Example:

class whileLoopDemo {
public static void main(String args[]) {
int x = 1;
while (x <= 4) {
System.out.println("Value of x:" + x);
x++;
}
}}
2. for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.

Syntax:

for (initialization condition; testing condition; increment/decrement){


statement(s)
}
Example:

class forLoopDemo {
public static void main(String args[]) {
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}

3. do while: do while loop is similar to while loop with only difference that it checks for condition
after executing the statements, and therefore is an example of Exit Control Loop.

Syntax:

do{
statements..
}
while (condition);

1. do while loop starts with the execution of the statement(s). There is no checking of any
condition for the first time.
2. After the execution of the statements, and update of the variable value, the condition is
checked for true or false value. If it is evaluated to true, next iteration of loop starts.
3. When the condition becomes false, the loop terminates which marks the end of its life cycle.
4. It is important to note that the do-while loop will execute its statements atleast once before any
condition is checked, and therefore is an example of exit control loop.

Example:

class dowhileloopDemo {
public static void main(String args[]) {
int x = 21;
do {
System.out.println("Value of x:" + x);
x++;
}
while (x < 20); } }

Objects and Classes in Java

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.

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 (tangible and intangible). The
example of an intangible object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as deposit,

withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value of the

ID is not visible to the external user. However, it is used internally by the JVM to

identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state.
It is used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from


which objects are created. So, an object is the instance (result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a class in Java


A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


Class <class_name>{

method;

Instance variable in Java


A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets
memory at runtime when an object or instance is created. That is why it is known as
an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an
object.

Advantage of Method

o Code Reusability
o Code Optimization

new keyword in Java


The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.

Object and Class Example: main within the class


In this example, we have created a Student class which has two data members id
and name. We are creating the object of the Student class by new keyword and
printing the object's value.

Here, we are creating a main() method inside the class.

Example -

File: Student.java

class Student{

int id;

String name;

public static void main(String args[]){

Student s1=new Student();

System.out.println(s1.id);

System.out.println(s1.name);

Output:
0

null

Object and Class Example: main outside the class


In real time development, we create classes and use it from another class. It is a
better approach than previous one. Let's see a simple example, where we are
having main() method in another class.

We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name
with the class name which has main() method.

File: TestStudent1.java

class Student{

int id;

String name;

class TestStudent1{

public static void main(String args[]){

Student s1=new Student();

System.out.println(s1.id);

System.out.println(s1.name);

Output:

null

You might also like