Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java - Unit I

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

Unit - I

 programming language and a platform independent.


 Java is a high level, robust, object-oriented and secure
programming language.
 developed by Sun Microsystems – 1995
 father of Java -James Gosling
 Before java – named as OAK
 Rename to JAVA
 Originally designed for interactive television
 but it was too advanced technology for the digital
cable television industry at the time.
 to develop a language for digital devices such as
set-top boxes, televisions, etc.
 best suited for internet programming.
 Later, Java technology was incorporated by
Netscape.
 Principle / features of java :

◦ Simple, Robust, Portable, Platform-independent, Secured, High

Performance, Multithreaded, Architecture Neutral, Object-

Oriented, Interpreted, and Dynamic.

 Currently, Java is used in internet programming,

mobile devices, games, e-business solutions, etc


 1) James Gosling, Mike Sheridan, and Patrick
Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.

 2) Initially it was designed for small, embedded systems in


electronic appliances like set-top boxes.

 3) Firstly, it was called "Greentalk" by James Gosling, and the


file extension was .gt

 4) After that, it was called Oak and was developed as a part of


the Green project.
 5) Why Oak? Oak is a symbol of strength and chosen as a

national tree of many countries like the U.S.A., France,

Germany, Romania, etc.

 6) In 1995, Oak was renamed as "Java" because it was already

a trademark by Oak Technologies.


 7) Why had they chose the name Java for Java language?

◦ The team gathered to choose a new name. The suggested words were

"dynamic", "revolutionary", "Silk", "jolt", "DNA", etc.

◦ According to James Gosling, "Java was one of the top choices along

with Silk". Since Java was so unique, most of the team members preferred

Java than other names.

 8) Java is an island in Indonesia where the first coffee was produced (called

Java coffee). It is a kind of espresso bean. Java name was chosen by James

Gosling while having a cup of coffee nearby his office.


JAVA follows the OOPs (Object Oriented
Programming ) paradigm.
Object-Oriented concepts are as follows :
 Classes
 objects
 Data Abstraction
 Encapsulation
 Inheritance
 Polymorphism
OOPs have following features

1. Object - Instance of class


2. Class - Blue print of Object
3. encapsulation - Protecting our data
4. polymorphism - Different behaviors at diff.
instances
5. abstraction - Hiding our irrelevance data
6. inheritance - one property of object is
acquiring to another property of object
Object
Basically an object is anything that is identifiable as an
single material item. You can see around and find many
objects like Camera, Monitor, Laptop etc.
In OOP perspective, an object is nothing but an instance
of a class that contains real values instead of variables
2. Class
A class is a template definition of the methods and variables
for a particular kind of object.
class Human
{
private:
EyeColor IColor;
NAME personname;
};
3. Abstraction
Abstraction is a process of identifying the relevant qualities
and behaviors an object should possess.
A Laptop consists of many things such as processor,
motherboard, RAM, keyboard, LCD
screen, wireless antena, web camera, usb ports, battery,
speakers etc.
To use it, you don't need to know how internally LCD
screens, keyboard, web camera, battery, wireless antena,
speakers works.
You just need to know how to operate the laptop by
switching it on. The intrinsic details are invisible.
4. Encapsulation

Encapsulation is a method for protecting data from


unwanted access or alteration by packaging it in an object
where it is only accessible through the object's interface.
Encapsulation are often referred to as information hiding.
 5. Inheritance

Inheritance is the ability to define a new class or object


that inherits the behavior and its functionality of an
existing class.
 The new class or object is called a child or subclass or
derived class while the original class is called parent or
base class.
 6. Polymorphism

As name suggests, Polymorphism means an ability to


assume different forms at different places.
There are two types of polymorphism.
 Compile time polymorphism - It is achieved by
overloading functions and operators
 Run time polymorphism - It is achieved by
overriding virtual functions
Message Communication
 Two classes can communicate with each other through
the objects which is created either in a same package or
in a different class file
•Java is simple-C & C++ features are adapted.
• Java is object-oriented-classes as packages and objects.
•Java is distributed-it can share both data and programs.
•Java is compiled & interpreted
•Java is robust
•Java is architecture-neutral
•Java is portable
•Java’s high performance-Multithreading
•Java is multithreaded-multiple
•Java is dynamic-supports functions of c & c++
•Java is secure
 Major difference is that C is a structure oriented language
and Java is an object oriented language and has mechanism
to define classes and objects.
 Java does not support an explicit pointer type
 Java does not have preprocessor, so we cant use #define,
#include and #ifdef statements.
 Java does not include structures, unions and enum data
types.
 Java does not include keywords like goto, sizeof and
typedef.
 Java adds labeled break and continue statements.
 The Java Development Kit (JDK) is a cross-platformed
software development environment that offers a
collection of tools and libraries necessary for
developing Java-based software applications and
applets.
 It is a core package used in Java, along with the JVM
(Java Virtual Machine) and the JRE (Java Runtime
Environment).
 Java interpreter is a computer program (system
software) that implements the JVM.
 It is responsible for reading and executing the program.
 It is designed in such a way that it can read the byte
program and translate the byte code instruction by
instruction.
 JVM (Java Virtual Machine) is an abstract machine. It
is a specification that provides runtime environment in
which java bytecode can be executed.
What it does
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
 In java, there are two types of data types
 •primitive data types
 •non-primitive data types
 A variable is a container which holds the
value while the Java programis executed.
 A variable is assigned with a data type.
 Variable is a name of memory location.
Variable
 A variable is the name of a reserved area
allocated in memory.
 In other words, it is a name of the memory
location.
 It is a combination of "vary + able" which
means its value can be changed.
Types of Variables
 There are three types of variables in Java

 local variable
 instance variable
 static variable
1) Local Variable
 A variable declared inside the body of the method is called
local variable. You can use this variable only within that
method and the other methods in the class aren't even aware
that the variable exists.
 A local variable cannot be defined with "static" keyword.
2) Instance Variable
 A variable declared inside the class but outside the body of
the method, is called an instance variable. It is not declared
as static
 It is called an instance variable because its value is
instance-specific and is not shared among instances.
3) Static variable
 A variable that is declared as static is called a static
variable. It cannot be local. You can create a single
copy of the static variable and share it among all the
instances of the class.
 Memory allocation for static variables happens only
once when the class is loaded in the memory.
 public class A
 {
 static int m=100;//static variable
 void method()
 {
 int n=90;//local variable
 }
 public static void main(String args[])
 {
 int data=50;//instance variable
 }
 }//end of class
public class Simple
{
public static void main(String args[])
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
 Type casting is when you assign a value of one
primitive data type to another type.
 In Java, there are two types of casting:
 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
Widening Casting
 Widening casting is done automatically when
passing a smaller size type to a larger size
type:
Narrowing Casting
 Narrowing casting must be done manually by
placing the type in parentheses in front of the
value:
Operators are used to perform operations on
variables and values.

Java divides the operators into the following


groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators
Assignment operators are used to assign
values to variables.
Comparison operators are used to compare
two values:
Logical operators are used to determine the
logic between variables or values:
 conditional statements are used to perform
different actions based on various conditions.
 The conditional statement evaluates a
condition before the execution of
instructions.
It is one of the simplest decision-making
statement which is used to decide whether a
block of JavaScript code will execute if a certain
condition is true.
 Syntax
if (condition) {
// block of code will execute if the condition i
s true
}
 For example
var x = 78;
if (x>70) {
console.log("x is greater")
}
 An if….else statement includes two blocks
that are if block and else block. It is the next
form of the control statement, which allows
the execution of JavaScript in a more
controlled way.
 It is used when you require to check two
different conditions and execute a different
set of codes. The else statement is used for
specifying the execution of a block of code if
the condition is false.
Syntax
if (condition)
{
// block of code will execute if the condition is true
}
else
{
// block of code will execute if the condition is false
}
var x = 40, y=20;
if (x < y)
{
console.log("y is greater");
}
else
{
console.log("x is greater");
}
It is an if statement inside an if statement.
Syntax
if (condition1)
{
Statement 1; //It will execute when condition1 is true
if (condition2)
{
Statement 2; //It will execute when condition2 is true
}
else
{
Statement 3; //It will execute when condition2 is false
}
}
var num = 20;
if (num > 10)
{
if (num%2==0)
console.log( num+ " is greater than 10 and even number");
else
console.log(num+ " is greater than 10 and odd number");
}
else
{
console.log(num+" is smaller than 10");
}
console.log("After nested if statement");
 It is a multi-way branch statement that is also
used for decision-making purposes. In some
cases, the switch statement is more
convenient than if-else statements.
 It is mainly used when all branches depend
upon the value of a single variable. It
executes a block of code depending upon the
different cases.
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;
}
var num = 5;
switch(num) {
case 0 : {
console.log("Sunday");
break;
}
case 1 : {
console.log("Monday");
break;
}
case 2 : {
console.log("Tuesday");
break;
}
case 3 : {
console.log("Wednesday");
break;
}
case 4 : {
console.log("Thursday");
break;
}
case 5 : {
console.log("Friday");
break;
}
case 6 : {
console.log("Saturday");
break;
}
default: {
console.log("Invalid choice");
break;
}
}
 Loops can execute a block of code as long as a specified
condition is reached.
 Loops are handy because they save time, reduce errors, and they
make code more readable.

For Loop

for (statement 1; statement 2; statement 3)


{ // code block to be executed }

 Statement 1 is executed (one time) before the execution of the


code block.
 Statement 2 defines the condition for executing the code block.
 Statement 3 is executed (every time) after the code block has
been executed.
The example below will print the numbers 0 to 4:

for (int i = 0; i < 5; i++)


{
System.out.println(i);

}
The while loop loops through a block of code
as long as a specified condition is true:

Syntax
while (condition)
{ // code block to be executed
}
Example
int i = 0;
while (i < 5)
{
System.out.println(i); i++;
}
A do...while loop is similar to a while loop,
except that a do...while loop is guaranteed to
execute at least one time.

Syntax
 Following is the syntax of a do...while loop −
Do
{ // Statements
}
while(Boolean_expression);
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
 What is a labeled loop in Java? A label is a valid
variable name that denotes the name of the loop to
where the control of execution should jump.
 To label a loop, place the label before the loop with a
colon at the end. Therefore, a loop with the label is
called a labeled loop.
public class LabeledForLoop
{
public static void main(String args[])
{
int i, j;
for(i=1;i<=5;i++)
{
System.out.println();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==9)
break inner;
}
}
}
}
 Arrays are used to store multiple values in a
single variable, instead of declaring separate
variables for each value.
 To declare an array, define the variable type
with square brackets:
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
//declare and initialize an array
int[] age = {12, 4, 5, 2, 5};
 One-dimensional Array
 Also known as a linear array, the elements are
stored in a single row. For example:
 In Java, 2D arrays are stored as arrays of
arrays.
 Therefore, the way 2D arrays are declared is
similar 1D array objects.
 2D arrays are declared by defining a data type
followed by two sets of square brackets.
 The syntax to declare and initialize the 2D
array is given as follows.
int arr[2][2] = {0,1,2,3};
 Strings, which are widely used in Java programming,
are a sequence of characters.
 In Java programming language, strings are treated as
objects.
 The most direct way to create a string is to write −
String greeting = "Hello world!";
import java.io.*;
import java.lang.*;

class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String s = "GeeksforGeeks";

// Prints the String.


System.out.println("String s = " + s);

// Declare String using new operator


String s1 = new String("GeeksforGeeks");

// Prints the String.


System.out.println("String s1 = " + s1);
}
}
Output:
String s = GeeksforGeeks
String s1 = GeeksforGeeks
Method Description
charAt(int) Finds the character at given index

length() Finds the length of given string

compareTo(String) Compares two strings

concat(String) Concatenates the object string with argument


string.

contains(String) Checks whether a string contains sub-string

startsWith(String) Checks whether a string starts with the


specified string
endsWith(String) Checks whether a string ends with the
specified string

getBytes() Converts string value to bytes

indexOf(String) Finds the first index of argument string in


object string

lastIndexOf(String) Finds the last index of argument string in


object string

isEmpty() Checks whether a string is empty or not

replace(String, String) Replaces the first string with second string


replaceAll(String, Replaces the first string with
String) second string at all occurrences.

substring(int, int) Extracts a sub-string from specified


start and end index values

toLowerCase() Converts a string to lower case


letters
toUpperCase() Converts a string to upper case
letters
trim() Removes whitespace from both ends

You might also like