Basics of Java Unit-1
Basics of Java Unit-1
Unit-I
22PLC15C
K.S.Mathad
Object Oriented Programming:
Object oriented programming (OOP) is the core of Java programming.
Java is a general purpose, object- oriented programming language
developed by Sun Microsystems. It was invented by James Gosling and his
team and was initially called as Oak.
The most important feature that made Java very popular was the
―Platform- Independent‖ approach.
It was the first programming language that did not tie-up with any particular
operating system( or hardware) rather Java programs can be executed
anywhere and on any system.
Java was designed for the development of the software for consumer
electronic devices like TVs, VCRs, etc.
K.S.Mathad
Two Paradigms:
Every program contains 2 components code
and data.
Two approaches are there to solve the
problem and in program writing: Procedure
oriented and object oriented.
K.S.Mathad
Two Approaches
• Procedure Oriented:
Procedure oriented programs are written based on ―whats
happening‖ around, where the code acts on data. Ex: C etc
Problems increases in procedure oriented as the program grows
larger and more complex.
• Object Oriented:
Object oriented programs are written based on ―Who is being
affected‖ around, which manages the increasing complexity.
It organizes program around data and well defined interfaces of that
data.
Characterized as data controlling access to code. Ex: C++, JAVA,
Small Talk etc
K.S.Mathad
K.S.Mathad
K.S.Mathad
The Three OOP:
K.S.Mathad
Encapsulation:
K.S.Mathad
Encapsulation
K.S.Mathad
Inheritance:
K.S.Mathad
Polymorphism
K.S.Mathad
A First Simple Program
class Example
{
public static void main(String args[ ])
{
System.out.println(“Welcome to
Programming in Java‖”);
}
}
K.S.Mathad
Running with jdk
:Example.java
:javac Example.java
:java Example
K.S.Mathad
A Second Short Program
/* This is a short example
Name of file : Example2.java */
class Example2{
public static void main(String args[])
{
int n=3;
System.out.println( “The value of n is :”+ n );
n=n+5;
System.out.print(“the new value is:”);
System.out.println(n);
}
}
K.S.Mathad
Two Control Statements
• if statement
The if- statement is the most basic of all the control
flow statements. It tells your program to execute a
certain section of code only if a particular test
evaluates to true.
K.S.Mathad
If statement
class Example
{
public static void main(String args[])
{
int a=10;
if(a>0)
System.out.println(“a is positive
number‖”);
System.out.println(“ End of
program”);
}
K.S.Mathad
The for loop
The for loop is similar to that of C/C++
Here is the general form of the traditional for statement:
for(initialization; condition; iteration)
{
//body
}
Initialization sets the loop control variable to initial value.
Condition is a Boolean expression which tests the loop
Iteration expression tells hoe the control variable has to
change at each iteration. Generally the increment or
decrement operator is used to perform iteration.
K.S.Mathad
For loop
class Example
{
public static void main(String args[])
{
int a;
for(a=0;a<5;a++)
System.out.println(a);
}
System.out.println(“End of program”);
}
Output:
0
1
2
3
4
End of Program
K.S.Mathad
In the below example, repeated a loop 5 times and then printed the “*”. This
is also known as the pyramid program. The loop will be repeated unless the
value of “i” and “j” becomes equal to 5.
*
**
***
****
*****
K.S.Mathad
public class PyramidExample {
public static void main(String args[])
{
for(int i=0; i < 5; i++) {
for(int j=0; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
K.S.Mathad
Using blocks of code
Java supports code blocks - which means that
two or more statements are grouped into
blocks of code.
Opening and closing braces is used to achieve
this.
Each block is treated as logical unit.
Whenever two or more statements has to be
linked blocks can be used.
K.S.Mathad
Example
class Example
{
public static void main(String args[])
{
int a=10;
if(a>0)
{ // begin of block
System.out.println(“a is positive number”);
System.out.println(“inside block”);
}// end of block
}
}
K.S.Mathad
Lexical issues:
• Java programs are a collection of whitespace,
identifiers, literals, comments, operators,
separators, and keywords.
• Whitespace:
Java is a free from language- means no need
to follow any indentation rules.
Whitespace is a space, tab, or newline.
K.S.Mathad
• Java character set:
The smallest unit of Java language are its character set used to write Java tokens. This
character are defined by unicode character set that tries to create character for a large number
of character worldwide.
The Unicode is a 16-bit character coding system and currently supports 34,000 defined
characters derived from 24 languages of worldwide.
• Key Words:
– Smallest individual units of programs are known as tokens. Java language includes five
types of tokens. They are
(a) Reserved Keyword
(b)Identifiers
(c) Literals.
(d)Operators
(e) Separators.
K.S.Mathad
Reserved keyword:
• Java language has 50 words as reserved keywords.
They implement specific feature of the language.
K.S.Mathad
Identifiers:
• Identifiers are programmer-designed token used for naming
classes methods variable, objects, labels etc. The rules for
identifiers are
1.They can have alphabets, digits, dollar sign and underscores.
2.They must not begin with digit.
3.Uppercase and lower case letters are distinct.
4.They can be any lengths.
5.Name of all public method starts with lowercase.
6.In case of more than one word starts with uppercase in next
word.
7.All private and local variables use only lowercase and
underscore.
8.All classes and interfaces start with leading uppercases.
9.Constant identifier uses uppercase letters only.
K.S.Mathad
Literals:
K.S.Mathad
Operators:
K.S.Mathad
Separators:
• Separators are the symbols that indicates where group of
code are divided and arranged. Some of the operators are:
K.S.Mathad
Comments:
Java supports 3 styles of comments
Multiline comment: this type of comment begins with /*
and ends with */
• Ex: /* Welcome to
• Java Programming */
Single line comments: this type of comment begins
with // and ends at the end of current line
• Ex: // Welcome to java Programming
Documentation Comment: this type of comment is used
to produce an HTML file that documents your
program. The documentation comment begins with /**
and ends with */
K.S.Mathad
Java Class libraries:
Java environment has several built in class libraries.
Java standard library includes hundreds of classes and methods grouped
into several functional packages. Most commonly used packages are:
(a)Language support Package.
(b)Utilities packages.
(c)Input/output packages
(d)Networking packages
(e)AWT packages.
(f)Applet packages
K.S.Mathad
Import Example
import java.util.Scanner;
class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " +
i);
}
}
K.S.Mathad
Data types, variables and arrays
• Java is a strongly typed language:
The strongly typed nature of Java gives it the robustness
and safety for it.
Every variable and expression has strictly defined type.
Assignments, parameter passing or explicit value
passing are checked for type compatibility.
Java compiler checks all expressions and parameters to
ensure type compatibility.
K.S.Mathad
Data types
• The various data types supported in java is as
follows
K.S.Mathad
• Java defines eight primitive types of data: byte, short, int, long, char,
float, double, and boolean.
• As shown in above figure.
The primitive types represent single values—not complex objects.
Although Java is otherwise completely object-oriented, the primitive
types are not.
They are analogous to the simple types found in most other non–
object-oriented languages.
The reason for this is efficiency. Making the primitive types into objects
would have degraded performance too much. The primitive types are
defined to have an explicit range and mathematical behavior.
Because of Java‗s portability requirement, all data types have a strictly
defined range. For example, an int is always 32 bits, regardless of
the particular platform.
K.S.Mathad
Integers
Java defines four integer types: byte, short, int, and long.
All of these are signed, positive and negative values. Java
does not support unsigned, positive-only integers.
Many other computer languages support both signed and
unsigned integers.
However, Java‗s designers felt that unsigned integers were
unnecessary. Specifically, they felt that the concept of
unsigned was used mostly to specify the behavior of the
high-order bit, which defines the sign of an integer value.
K.S.Mathad
byte, short
The smallest integer type is byte.
This is a signed 8-bit type that has a range from –128 to127.
Variables of type byte are especially useful when you‗re
working with a stream of data from a network or file.
Byte variables are declared by use of the byte keyword.
For example, the following declares two byte variables called
b and c: byte b, c;
• Short
short is a signed 16-bit type.
It has a range from –32,768 to 32,767.
It is probably the least-used Java type.
Here are some examples of short variable declarations:
• short s; short t; K.S.Mathad
byte example
public class AddtionByte {
K.S.Mathad
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision.
For example, calculations such as square root, or transcendental such as
sine and cosine, result in a value whose precision requires a floating-
point type.
There are two kinds of floating-point types, float and double, which
represent single- and double-precision numbers, respectively.
• float
The type float specifies a single-precision value that uses 32 bits of
storage.
• double
Double precision, as denoted by the double keyword, uses 64 bits to store
a value.
Double precision is actually faster than single precision on some modern
processors that have been optimized for high-speed mathematical
calculations. K.S.Mathad
Float type example
public class DataTypeFloatExample {
public static void main(String args[]){
//Declare float type variables.
float f1 = 32.454f;
float f2 = 178.44f;
K.S.Mathad
• Characters
In Java, the data type used to store characters is char.
However, C/C++ programmers beware: char in Java is not the same as
char in C or C++.
In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java
uses Unicode to represent characters.
Unicode defines a fully international character set that can represent
all of the characters found in all human languages.
It is a unification of dozens of charactersets, such as Latin, Greek
Arabic, Cyrillic,Hebrew, Katakana, Hangul, and many more. For this
purpose, it requires 16 bits.
K.S.Mathad
Data Type Default Value Default size
Byte 0 1 byte
short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
K.S.Mathad
• Literals:
• A constant value in Java is created by using a literal representation of it. There are
5 types of literals.
Integer Literals.
Floating-point Literals.
Character Literals.
String Literals.
Boolean Literals.
• Integer literals:
Any whole number value is an integer literal.
These are all decimal values describing a base 10 number.
There are two other bases which can be used in integer literal, octal( base 8)
where 0 is prefixed with the value, hexadecimal (base 16) where 0X or 0x is
prefixed with the integer value.
• Example:
• int decimal = 100;
• int octal = 0144; int hexa = 0x64;
K.S.Mathad
• Example:
• 0.0314 *10² (i.e 3.14).
• 6.5E+32 (or 6.5E32) Double-precision floating-
point literal 7D Double-precision floating-point
literal
• .01f Floating-point literal
• Character literals:
char data type is a single 16-bit Unicode character.
We can specify a character literal as a single printable character
in a pair of single quote characters such as 'a', '#', and '3'.
You must know about the ASCII character set. The ASCII
character set includes 128 characters including letters, numerals,
punctuation etc.
Below table shows a set of these special characters.
K.S.Mathad
K.S.Mathad
• Boolean Literals:
The values true and false are treated as literals in Java programming.
When we assign a value to a boolean variable, we can only use these two
values.
Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is
equivalent to false in Java.
We have to use the values true and false to represent a Boolean value.
• Example
• boolean chosen = true;
• String Literal
The set of characters in represented as String literals in Java.
Always use "double quotes" for String literals.
There are few methods provided in Java to combine strings, modify
strings and to know whether to strings have the same values.
• Example:
String str=“hello world”;
K.S.Mathad
• Variables:
•A variable is an identifier that denotes a storage location used to store a
data value. A variable may have different value in the different phase of the
program. To declare one
• identifier as a variable there are certain rules. They are:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.
• Declaring Variable: One variable should be declared before using.
• The syntax is
• type identifier [ = value][, identifier [= value] ...] ;
Example:
• int a,b,c;
• float quot, div;
K.S.Mathad
Dynamic initialization:
Java allows variables to be initialized dynamically, using
expression valid at the time variable is declared.
• Example:
class Example
{
public static void main(String args[])
{
double a=10, b=2.6; double c=a/b;
System.out.println(“value of c is”+c);
}
}
K.S.Mathad
The Scope and Lifetime of Variables
Java allows variables to be declared within any block. A
block is begun with an opening curly brace and ended by
a closing curly brace. A block defines a scope.
A scope determines what objects are visible to other parts of
your program. It also determines the lifetime of those
objects.
Many other computer languages define two general
categories of scopes: global and local. However, these
traditional scopes do not fit well with Java strict,
object-oriented model.
K.S.Mathad
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{
// known only to this block
int y = 20;
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
K.S.Mathad
Type Casting
Assigning a value of one type to a variable of
another type is known as Type Casting .Type
casting can be done in two ways.
1.Widening Casting(Implicit)
2.Narrowing Casting(Explicitly done)
K.S.Mathad
Implicit
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i;
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
} K.S.Mathad
Explicit
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d;
int i = (int)l;
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
K.S.Mathad
Type promotion rules
K.S.Mathad
Processing Arrays
class TestArray
{
public static void main(String[] args)
{
int [] myList = new int[4];
for (int i=0;i<4;i++)
myList[i]=i+1;
K.S.Mathad
Multidimensional Arrays
• you can declare and create an array of arrays
int coords[] [] = new int[12] [12];
coords[0] [0] = 1; coords[0] [1] = 2;
K.S.Mathad
A few words about strings:
Java supports string type which is an object. It is used to
declare string variables
Array of strings can also be declared.
A string variable can be assigned to another string variable.
String variable can also be used as
argument.
Example:
• String name1=“gautham”, name2;
name2=name1; // sets name2 withvalue gautham
• System.out.println(name2); // string variable passed as parameter.
K.S.Mathad
For loop
class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
}
}
K.S.Mathad
If statement
class IfSample {
public static void main(String args[]) {
int x, y;
x = 10;
y = 20;
if(x < y) System.out.println("x is less than y");
x = x * 2;
if(x == y) System.out.println("x now equal to y");
x = x * 2;
if(x > y) System.out.println("x now greater than y");
// this won't display anything
if(x == y) System.out.println("you won't see this");
}
}
K.S.Mathad
Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
K.S.Mathad
Area of Circle
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
K.S.Mathad
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
K.S.Mathad
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
K.S.Mathad
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
K.S.Mathad
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
K.S.Mathad
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
K.S.Mathad
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
K.S.Mathad
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
K.S.Mathad
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
K.S.Mathad