Java Unit - I Notes
Java Unit - I Notes
Java Unit - I Notes
(Unit – I)
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.
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.
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.
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.
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!");
}
}
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.
Syntax:
data_type variable_name = value;
1. Local variable
2. Static (or class) variable
3. Instance 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.
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 - 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
int num=10;
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
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.
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.
class ArithmeticOperatorDemo {
public static void main(String args[]) {
int num1 = 100;
int num2 = 20;
2) 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
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:
4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in conditional statements and
loops for evaluating a condition.
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.
class LogicalOperatorDemo {
public static void main(String args[]) {
boolean b1 = true;
boolean b2 = false;
Output:
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.
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");
}
Output:
6) Ternary Operator
This operator evaluates a boolean expression and assign the value based on the result.
Syntax:
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.
class TernaryOperatorDemo {
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.
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) {
}
Example:
class IfDemo {
public static void main(String args[]) {
int i = 10;
if (i > 15)
System.out.println("10 is less than 15");
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");
}
}
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 :
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:
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); } }
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.
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
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.
Object Definitions:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
method;
Advantage of Method
o Code Reusability
o Code Optimization
Example -
File: Student.java
class Student{
int id;
String name;
System.out.println(s1.id);
System.out.println(s1.name);
Output:
0
null
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{
System.out.println(s1.id);
System.out.println(s1.name);
Output:
null