Java Unit I
Java Unit I
Through java
UNIT-I
UNIT-I
JAVA BASICS
History of Java
Java buzzwords
Data types
Variables, scope and life time of variables
Arrays
Operators, expressions, control statements
Type conversion and casting
Simple java program
Classes and objects – concepts of classes, objects
Constructors, methods
Access control
This keyword
Garbage collection
Overloading methods and constructors
Parameter passing
Recursion
String handling , StringTokenizer
Java Basics:-
History of java:-
Java was developed by
✓ James Gosling,
✓ Patrik Naughton,
✓ Chris Warth,
✓ Ed Frank, and
✓ Mike Sheridan
at Sun Microsystems, Inc in 1991.
History of Java
Java started out as a research project.
Java
Byte
codes Java Just-in-time
Java
move Interpreter Compiler
Compiler
locally
or
through Run Time System
n/w
Java Java OS W32
Win Solaris
Byte codes
MAC Others
Hardware
JVM
Runtime
Hardware
The Architecture of the Java Virtual Machine
Binary form of a .class file(partial)
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
0000: cafe babe 0000 002e 001a 0a00 0600 0c09 ................
0010: 000d 000e 0800 0f0a 0010 0011 0700 1207 ................
0020: 0013 0100 063c 696e 6974 3e01 0003 2829 .....<init>...()
0030: 5601 0004 436f 6465 0100 046d 6169 6e01 V...Code...main.
0040: 0016 285b 4c6a 6176 612f 6c61 6e67 2f53 ..([Ljava/lang/S
0050: 7472 696e 673b 2956 0c00 0700 0807 0014 tring;)V........
0060: 0c00 1500 1601 000d 4865 6c6c 6f2c 2057 ........Hello, W
0070: 6f72 6c64 2107 0017 0c00 1800 1901 0005 orld!...........
0080: 4865 6c6c 6f01 0010 6a61 7661 2f6c 616e Hello...java/lan
0090: 672f 4f62 6a65 6374 0100 106a 6176 612f g/Object...java/
00a0: 6c61 6e67 2f53 7973 7465 6d01 0003 6f75 lang/System...ou ...
➢ Java is a pure oop or not ?
Multithreaded
multiple concurrent threads of executions can run
simultaneously
utilizes a sophisticated set of synchronization
primitives (based on monitors and condition
variables paradigm) to achieve this
Java Features (5)
Dynamic
java is designed to adapt to evolving environment
libraries can freely add new methods and instance
variables without any effect on their clients
interfaces promote flexibility and reusability in code
by specifying a set of methods an object can perform,
but leaves open how these methods should be
implemented
can check the class type in runtime
Java Features (6)
Distributed
Java is designed for the distributed environment of
the Internet, because it handles TCP/IP protocols.
Allows objects on two different computers to
execute procedures remotely by using package called
Remote Method Invocation (RMI).
Architecture-Neutral
Goal of java designers is “write once; run anywhere,
any time, forever.”
Byte Code
Simple Type
Derived Type
User-defined Type
Data Types
float double
Ex:-
byte b, c;
Floating-Point Types
Declaring a Variable
➢ In Java, all variables must be declared before they can be used.
Scope
The scope of a declared element is the portion of the program where the element is
visible.
Lifetime
The lifetime of a declared element is the period of time during which it is alive.
➢ The scope defined by a method begins with its opening curly brace and ends with closing curly brace.
➢ Scopes can be nested.
➢ Objects declared in the outer scope will be visible to code within the
inner scope. The reverse is not true.
➢ Objects declared within the inner scope will not be visible outside it.
public class Scope
{
public static void main(String args[])
{
int x; //know to all code within main
x=10;
if(x==10)
{ // starts new scope
int y=20; //Known only to this block
Operator Result
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
–– Decrement
➢ The operands of the arithmetic operators must be of a numeric
type.
➢ You cannot use them on boolean types, but you can use them on
char types.
➢ No fractional component attached to the result, when the division
operator is applied to an integer type.
➢ The modulus operator, %, returns the remainder of a division
operation. It can be applied to floating-point types as well as
integer types.
➢
Ex:- int x = 42;
double y = 42.25;
x mod 10 = 2
y mod 10 = 2.25
➢
// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
// arithmetic using doubles
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
/ Demonstrate ++ and --.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
Relational Operators
➢ Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Note :-
int done;
// ...
if(!done) ... // Valid in C/C++
if(done) ... // but not in Java.
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
The Assignment Operator
➢ Java defines several bitwise operators which can be applied to the integer
types, long,int, short, char, and byte.
➢ These operators act upon the individual bits of their operands.
➢ Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
Cotnd..
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
The ? Operator
General form:
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
Operator Precedence
Control Statements
➢ iteration
➢ jump
Java’s Selection Statements
➢ if ( condition )
▪ Same as in c/c++.
▪ The condition is any expression that returns a boolean value.
➢ Switch( expression )
▪ Same as in c/c++.
▪ The expression must be of type byte, short, int, or char;
▪ Each of the values specified in the case statements must be of a type
compatible with the expression.
➢
// Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
▪ 1. break
▪ Using break to Exit a Loop
▪ break;
▪ Similar to c/c++
▪ 3. return
▪ The return statement is used to explicitly return from a method.
▪ It transfers control back to the caller of the method.
Type Conversion and Casting
Types of Conversions:
1.Widening conversion
2.Narrowing conversion
When one type of data is assigned to another type of
variable, an automatic type conversion will take place if the
following two conditions are met:
▪ When these two conditions are met, a widening conversion takes place.
➢ For widening conversions, the numeric types, including integer,
floating-point, and double types, are compatible with each other.
➢ Ex:
➢ int a=10;
➢ double b=a;
//char to int
char c='a';
System.out.println(“char to int conversion");
i2=c;
System.out.println(i2);
}
}
The narrowing conversion occurs from a type to a different
type that has a smaller size, such as from a long (64 bits) to
an int (32 bits).
In general, the narrowing primitive conversion can occur in
these cases:
short to byte or char
char to byte or short
int to byte, short, or char
long to byte, short, or char
float to byte, short, char, int, or long
double to byte, short, char, int, long, or float
The narrowing primitive conversion must be explicit.
You need to specify the target type in parentheses.
➢ it is still possible to obtain a conversion between incompatible types.
➢ Cast keyword / operator will be used to perform conversion between
incompatible types.
➢ General form:
➢ ( target-type ) value;
public class Narrowing
{
public static void main(String args[])
{
byte b;
int i=257;
double d=323.142;
Reference variables are used in Java to store the references of the objects created by the
operator new
Any one of the following syntax can be used to create a reference to an int array
int x[];
int [] x;
int [] x = null;
Initializing an array in Java
An array can be initialized while it is created as follows
int [][] x;
//x is a reference to an array of int arrays
x = new int[3][];
//Create 3 new int array references, x[0], x[1] and x[2]
//x.length is 3
x[0] = new int[4]; //x[0].length is 4
x[1] = new int[6]; //x[1].length is 6
x[2] = new int[3]; //x[2].length is 3
for(int i = 0; i < x.length; ++i)
for(int j = 0; j < x[i].length; ++j)
System.out.println(x[i][j]);
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
void states that the main method will not return any value.
• type methodname1(parameter-list) {
• body of method
• }
• type methodname2(parameter-list) {
• body of method
• }
• …
• type methodnameN(parameter-list) {
• body of method
• }
• }
➢ The data, or variables, defined within a class are called instance
variables.
➢ Functions defined within a class are called methods.
➢ The methods and variables defined within a class are called
members of the class.
• Note:-
• The class declaration and the implementation of the
methods are stored in the same place and not defined separately.
Constructors and Methods
Constructors and Methods
A constructor is a special member function whose task is to initialize the objects of its
class.
A constructor has the same name as the class in which it resides and is syntactically
similar to a method.
Box() {
width = 10;
height = 10;
depth = 10;
}
}
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Methods
General Form:
type name(parameter-list) {
// body of method
}
The type of data returned by a method must be compatible with the return type
specified by the method.
The variable receiving the value returned by a method must also be compatible with
the return type specified for the method.
return value;
Here, value is the value returned.
Ex:
double volume() {
return w*h*d;
}
class Box {
double width;
double height;
double depth;
double vol;
// get volume of box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
}
}
Parameterized constructor
The constructor that can take the arguments are called parameterized constructors
class Box {
double width;
double height;
double depth;
protected:
▪ Allows the class itself, subclasses, and all classes in the same package to access the
members.
▪ To declare a protected member, use the keyword protected.
public:
▪ Any class, in any package ,has access to a class's public members.
▪ To declare a public member, use the keyword public.
default :
▪ When no access specifier is used, then by default the member of a class is public
within its own package, but cannot be accessed outside of its package.
class Test {
int a; // default access class AccessTest {
public int b; // public access public static void main(String args[])
private int c; // private access {
/*protected applies only when Test ob = new Test();
inheritance is involved*/
// methods to access c
// These are OK, a and b may be accessed directly
void setc(int i) { // set c's value ob.a = 10;
c = i; ob.b = 20;
} // This is not OK and will cause an error
int getc() { // get c's value //ob.c = 100; // Error!
return c;
// You must access c through its methods
}
} ob.setc(100); // OK
System.out.println(ob.a + " " +ob.b + " " + ob.getc());
}
}
The this Keyword
➢this keyword is used inside any method to refer to the current object.
Ex:
Box(double w, double h, double d) {
this.w = w;
this.h = h;
this.d = d;
}
Instance Variable Hiding
➢ In java, it is illegal to declare two local variables with the same name inside
the same or enclosing scopes.
➢ But , you can have local variables, including formal parameters to methods,
which overlap with the names of the class’ instance variables.
➢ When a local variable has the same name as an instance variable, the local
variable hides the instance variable.
Contd..
Therefore ,this can be used to resolve any name collisions that might occur
between instance variables and local variables.
ex:
double width,height,depth;
➢ Defining two or more methods within the same class that share the same name, as long as their
parameter declarations are different is called method overloading.
➢ When an overloaded method is invoked, Java uses the type and/or number of arguments to determine
which version of the overloaded method to call.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
Call-by-value
➢The call-by-value copies the value of a actual parameter into the formal parameter of the
method.
➢In this method, changes made to the formal parameter of the method have no effect on the
actual parameter
➢Simple types, int, float, char, double, are passed by value
// Simple types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +a + " " + b);
}
}
Call-by-reference
class Student{
int rollno;
String name;
static String college ="ITS";
s1.display();
s2.display();
}
}
2) static method
If you apply static keyword with any method, it is known as static method
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
Example of static method
//Program of changing the common property of all objects(static field).
class Student{
int rollno;
String name; public static void main(String args[]){
static String college = "ITS"; Student.change();
static void change(){ Student s1 = new Student (111,"Karan");
college = "BBDIT"; Student s2 = new Student (222,"Aryan")
} Student s3 = new Student (333,"Sonoo")
Student(int r, String n){ s1.display();
rollno = r; s2.display();
name = n; s3.display();
}
}
void display (){System.out.println(rollno+" "+name+" "+college);}
}
Methods declared as static have several restrictions:
▪ They can only call other static methods.
▪ They must only access static data.
▪ They cannot refer to this or super in any way.
Ex:
class A{
int a=40;//non static
•
•
String Class
• Ex:-
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
▪ String s2 = "abc";
• String(String strObj)
ex:
class s{
public static void main(String args[]) {
char c[]={‘j’,’a’, ‘v’,’a’};
String s1=new String(c);
String s2=new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
• String(byte asciiChars[])
• String(byte asciiChars[], int startIndex, Int numChars)
Ex:
class SubStringCons
{
public static void main(String args[])
{
byte ascii[]={65,66,67,68,69,70};
ex;
char chars[]={‘a’,’b’,’c’};
String s=new String(chars);
System.out.println(s.length());
Special String Operations
String Literals
String Concatenation
String Concatenation with Other Data Types
String Conversion and toString( )
Character Extraction
charAt( )
getChars( )
getBytes( )
toCharArray( )
String Comparison
equals( ) and equalsIgnoreCase( )
regionMatches( ) startsWith( ) and endsWith( )
equals( ) Versus ==
compareTo( )
Searching Strings
Modifying a String
substring( )
concat( )
replace( )
trim( )
Changing the Case of Characters Within a String
Special String Operations
String literals
char c[]={‘a’,’b’,’c’};
String s1=new String(c);
String s2=“abc”; // use string literal
System.out.println("abc".length());
String Concatenation:
String age=“9”;
String s=“he is”+age+”years old.”;
System.out.println(s);
class Box {
double width , height , depth;
Box(double w, double h, double d){
width=w;
height=h;
depth=d;
}
public String toString()
{
return "dimensions are "+width+" by" +height+" by"+depth +".";
}
}
class toStringDemo{
public static void main(String args[]){
Box b= new Box(10,12,14);
String s=" Box b:"+b; //concatenate Box objectcls
System.out.println(s);
}
}
Character Extraction
charAt():
to extract a single character from a string
char charAt(int where)
Ex:
char ch;
ch=“abc”.charAt(1);
getChars():
to extract more than one character at a time,
System.out.println(str);
for(int i=0;i<b.length;i++)
{
System.out.print(b[i]+" ");
}
}
}
toCharrArray():
-To convert all the characters in a String object into a
character array
Syntax:
char[] toCharArray()
Ex:
public class CharArray
{
public static void main(String args[])
{
String text = "Coffee Cup";
char ch[] = text.toCharArray();
for(int i=0;i<ch.length;i++)
{
System.out.print(ch[i]);
}
}
}
String Comparison
To compare the strings or substrings within strings.
}
}
String Comparison
boolean startsWith(String str) //to determine whether a given String begins
with a specified string.
boolean startsWith(String str, int startIndex) //to specifies the index into the invoking
string at which point the search will begin.
equals( ) Versus ==
// It compares the characters inside a String object
//To compare two object references to see whether they refer to the same instance.
String Comparison
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
//String s2 = s1;
System.out.println(s1.equals(s2));
System.out.println( s1 == s2);
}
}
Output:
true
false
String Comparison
int compareTo(String str)
Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.
Ex: ABC➔ 65 66 67
abc➔ 97 98 99
Ex:ABC ➔65 66 67
abc➔ 65 66 67
String Comparison
class SortString {
static String arr[] = {
“Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country“};
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
The output of this program is the list of words:
Now aid all come country for good is men of
the the their time to to
Searching Strings
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
S t r i n g ’ s a r e o b j e c t s
s1.substring(13);
s1.substring(9, 12);
s1.substring(0, 6);
Ex:
String s = "Hello".replace('l', 'w');
}
}
String trim( )
The trim( ) method returns a copy of the invoking string from which any leading and
trailing whitespace has been removed
Ex:
String s = “ Hello World ".trim();
Changing the Case of Characters Within a String
String toLowerCase( )
String toUpperCase( )
class LowerUpper {
public static void main(String args[]) {
String str1 = "java";
String str2 = "JAVA";
System.out.println("Upper Case Of : "+str1+" is : "+str1.toUpperCase());
System.out.println("Lower Case Of : "+str2+" is : "+str2.toLowerCase());
}
}
String Buffer
StringBuffer represents growable and writeable character
sequences.
StringBuffer may have characters and substrings inserted in
the middle or appended to the end.
StringBuffer Constructors
StringBuffer defines these three constructors:
StringBuffer( ) //reservse up to 16 char
StringBuffer(int size) //explicitly sets the size of the
StringBuffer(String str)
class BufDec
{
public static void main(String args[])
{
StringBuffer sb1 = new StringBuffer("Coffee Cup“);
StringBuffer sb2 = new StringBuffer(20);
StringBuffer sb3 = new StringBuffer();
System.out.println(sb1);
System.out.println("Buffer 1 Size : "+sb1.capacity());
System.out.println("Buffer 2 Size : "+sb2.capacity());
System.out.println("Buffer 3 Size : "+sb3.capacity());
}
}
int length( )
//The current length of a StringBuffer can be found via the length( ) method
int capacity( )
//The total allocated capacity can be found through the capacity( ) method.
class StringToken{
public static void main(String args[]){
String s=“hello=java,test”;
/*Scanner input=new Scanner(System.in);
String s=input.next();*/
while(st.hasMoreTokens()) {
String result=st.nextToken();
System.out.println(result);
}
}
}
Write a java program that reads a line of integers and then displays each
integer and find the sum of the integers (using StringTokenizer)
import java.util.*;
class SumOfInt{
public static void main(String args[]){
//String s=“1+2+3+4+5+6+7”;
Scanner s= new Scanner(System.in);
String t=s.next();
int sum=0;
sum=sum+Integer.parseInt(a);
}
System.out.println("sum of all integers is: "+sum);
}
}
token <= identifier | keyword | separator | operator | literal | comment
Identifiers: names the programmer chooses
Keywords: names already in the programming language
Separators (also known as punctuators): punctuation characters and
paired-delimiters
Operators: symbols that operate on arguments and produce results
Literals (specified by their type)
Numeric: int and double
Logical: boolean
Textual: char and String
Reference: null
Comments
Line
Block