JAVA UNIT-1
JAVA UNIT-1
22ITC02
Course Outcomes
• Apply the concept of OOP to design, implement and execute
programs.
• Use the strings, interfaces, packages and inner classes for application
development.
• Apply the exception handling mechanisms and multithreading for the
development.
• Develop applications using collection framework.
• Develop database applications using SQL package.
Procedural Oriented Programming (POP)
• Problem is always considered as a sequence of tasks to be done
• Number of functions are written to accomplish these tasks
• Primary focus on functions and little attention to data
• Ex languages like COBOL, FORTRAN, PASCAL, C
• Main drawback: does not model real world problems
Structure of POP
Object Oriented Programming
• Allows us to decompose a problem into several entities called objects
and builds data (attributes) and methods (operations/behaviors)
around these entities.
• OOP is an approach that provides a way of modularizing programs by
creating a portioned memory area for both data and methods that
can be used as templates creating copies of such modules on
demand.
Object-Oriented Programming
Object
• An object is the basic run-time entity (unit) in Object oriented system.
• An object is an instance of a class
• An object is a software bundle of related state and behavior.
• When a program is executed, objects interact by sending messages.
• Different objects of different classes can work together without
knowing the details of their data and code.
Class
• A class is a blueprint of the prototype from which objects are created
• A class and an object are basic constructs of an Object-oriented
programming language. Other constructs are methods and
constructors.
Principles of Object-Oriented Programming
The four pillars of object-oriented programming are
Import Statements(Optional)
Interface Statements(Optional)
Class definitions(Optional)
System.out.print(“” )
System.out.println(“”)
Requirements PATH is an environment
variable that is used to find
• Install JDK and locate binary files like
• Set path “java” and “javac” and to
locate needed executables
• Go to computer properties from the command line or
• Go to advanced setting Terminal window.
• Declaring a variable
Datatype variablename[=value]
Basic operators
Syntax: if(condition)
{
statement 1; //executes when condition is true
}
EX:
class Sampleif
{
public static void main(String args[])
{
int x=15;
int y=7;
if((x+y)>20)
{
System.out.println("x+y is greater than 20");
}
}
}
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
switch (expression)
{
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
For loop
for(initialization; condition; increment/decrement)
{
//block of statements
}
do
{
//statements
} while (condition);
Rules for naming
Some points to know
• Java is strictly case-sensitive
• Comments in Java
// for single-line comments
/*-----
-------*/ for multi line comments
twoD2[3]=new int[4];
Classes and Objects
Defining a class Data
members
class <classname> (variables)
{
Member
//class variables declaration (instance variables) functions(methods)
<access-modifier> <datatype> <variable>[=value];
//functions definitions (instance methods)
<access-modifier> <returntypy> <methodname>([arguments])
{
---
}
}
Creating the object
<classname> <objectname>=new <classname>();
A a1=new A();
Accessing instance variables and methods
a1.<variablename>;
a1.<methodname()>;
Constructors
• It is a special member function that is automatically called when an
object is instantiated i.e an object is allocated with memory.
• Constructor is declared with the same name as that of class name.
• Constructors do not return any value. Hence no return type is
mentioned not even void.
• Constructor may or may not take arguments.
• Constructors are used to initialize the data of the members of a class.
• Even if no constructor is defined in the class the default constructor
will be automatically called.
Syntax
class Class_name
{
<access-modifiers> Class_name(<arguments>)
{
//initialization steps
}
}
varied.
Method overloading
• Methods can also be overloaded i.e can declare more than one
usage:
Scanner sc = new Scanner(System.in);
String var = sc.nextLine();
Scanner class methods
Static keyword
• a variable or method can be declared as static
• static members can be accessed without creating an object, rather
using the class name.
• static variables are global to the objects .
• static variables can be accessed within a class in the satic methods.
• non-static members can not be cassed from static methods.
• we can even create ststic blocks, those will always be executed first in
the program.
final keyword
Passing values in methods
• Pass by Value: In the pass-by-value concept, the
method is called by passing a value. So, it is called
pass-by value. It does not affect the original parameter.
• Pass by Reference: In the pass-by-reference concept,
the method is called using an alias or reference of the
actual parameter. So, it is called pass-by reference.
String classes
• String
Java.lang
• StringBuffer
• StringTokenizer java.util
String class
• Every string we create is an object of a String class
• String objects are immutable i.e once created it can’t be modified.
• If we assign a new string value to the string object then new memory
will be allocated, Garbage Collector will collect previously allocated
memory.
String constructors
• String()
String s=new String()
• String(char[] chars)
char chars[]={‘a’,’b’,’c’};
String st=new String(chars);
• String(char[] chars, int start_index, int no_ofchars)
char chars[]={‘a’,’b’,’c’,’d’,’e’,’f’};
String str=new String(chars,2,3);
Cont..
• String(String strobj)
char chars[]={‘a’,’b’,’c’};
String s1=new String(chars);
String s2=new String(s1);
• String (byte char[])🡪 pass ASCII Characters
byte a[]={65,66,67,68,69,70};
String s1=new String(a); --🡪 ABCDEF
String literals
String s1=“Welcome”;
String s2=“Welcome”;
s1
Welcome s2
• String s1=“hi”;
String s2=s1+” Soni”
• int age=9;
String s3=“ the girl is ”+age;
toString()
• toString() method returns a String Object that contains human
readable String appropriately describes an object of your class.
public String toString()
{
return “string of your wish”;
}
String Class methods
• char charAt(int index)
• int length()
• void getChars(int sourceStart, int sourceEnd, char target[],int targetStart)
• byte[] getBytes()
• chars[] toCharArray()
• boolean equals(String obj)
• boolean equalsIgnoreCase(String obj)
• boolean regionMatche(int startIndex, String str2, int str2startindex, in
numchars)
Cont..
• boolean startsWith(String str)
• Boolean endsWith(String str)
• Int compareTo(String str) 🡪 < 0 invoking string islesser than str
🡪 > 0 invoking string is greater than str
🡪 = 0 invoking string is equal to str
• int indexOf(int ch) or int indexOf(String str)
• int lastIndexOf(int ch) or int lastIndexOf(String str)
• int indexOf(int ch, int startIndex) or int indexOf(String str, int startIndex)
• int lastIndexOf(int ch, int startIndex) or int lastIndexOf(String str, int
startIndex)
• String substring(int startindex)
• String substring(int startindex, int endindex)
• String replace(char orginal, char replacement)
• String replace(charsequence orginal, charsequence replacement)
• String trim()🡪 removes white spaces in the String and returns new
String
• static String valueof(<datatype> datavar)
• String toLowerCase()
• String toUpperCase()
StringBuffer class
• String is immutable.
• StringBuffer is a growable and writable character sequence.
Constructors
-StringBuffer()
-StringBuffer(int size)
-StringBuffer(String str)
-StringBuffer(Charatersequence)
Methods in StringBuffer Class
• int length()
• int capacity()
• void ensureCapacity(int size) 🡪 to set the size of the buffer
• void setLength(int len)🡪 when we increase the length null claraters will be added to
buffer
• char charAt(int index)
• Void setCharAt(int index, char ch)
• Void getChars(int sourceStart, int sourceEnd, char target[], int targerStart)
• StringBuffer append(String str)
• StringBuffer append(int num)
• StringBuffer append(Object obj)
Cont..
• StringBuffer insert(int index, String str)
• StringBuffer insert(int index, char ch)
• StringBuffer insert(int index, Object obj)
• StringBuffer reverse()
• StringBuffer delete(int startindex, int endindex)
• StringBuffer deleteCharAt(int index)
• StringBuffer replace(int startindex, int endindex, String str)
• String substring(int startIndex)
• String substring(int startIndex, int endIndex)
StringTokenizer
• StringTokenizer class in Java is used to break a string into tokens.
• StringTokenizer(String str)
• StringTokenizer(String str, String delim)
• StringTokenizer(String str, String delim, boolean flag)🡪 flag refers to
consider the delim charater to be considered as tokens or not.
Important methods
• public int countTokens()
• public boolean hasMoreTokens()
• public String nextToken()
Wrapper Classes
• A Wrapper class in Java is a class whose object wraps or contains
primitive data types.
• Each Wrapper class has a parse method that converts the value to
primitive datatype, which is in the form of String.
static int parseInt (String s)🡪 converts s to integer
usage : int i=Integer.parseInt(strobj);
Similarly, other primitive datatypes wrapper classes have parse
functions. parseDouble(),parseByte(),parseChar(), etc…
Task: explore more usage of Wrapper classes, other relative methods
Access Modifiers