0% found this document useful (0 votes)
14 views

JAVA UNIT-1

Uploaded by

premsagark3101
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

JAVA UNIT-1

Uploaded by

premsagark3101
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Java Programming

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

• Abstraction-> hiding of data/information


• Encapsulation-> binding of data and code
• Inheritance-> objects of one class acquire the properties of
another class
• Polymorphism-> ability to take more than one form
What is Java?
• A programming Language and a Platform.
• Language -A high-level, robust, secure Object-oriented programming
language
• Platform – any hardware or software environment in which a
program runs is a platform. Since Java has its own Runtime
Environment (JRE) and Application Programming Interface (API), Java
is a Platform
Where is Java used?
• Desktop applications
• Web applications
• Enterprise applications
• Mobile applications
• Embedded systems
• Smart cards
• Robotics
• Games
History of Java
• Developed by Sun Microsystem engineers led by James Gosling in
1991. (James Gosling, Mike Sheridon, Patrick Naughton, Chris Warth
and Ed Frank)
• The initial name of the language was “Oak”.
• Later in 1995, it was renamed as “Java”.
• It combines the features of C and C++.
• Java can be used to create Applications (stand-alone) and Applets
(web-based).
Java Features/ Buzz words
⮚ Simple
⮚ Object-oriented
⮚ Platform independent
⮚ Portable
⮚ Robust
⮚ Secure
⮚ Distributed
⮚ Multithreaded
⮚ Dynamic
⮚ Compiled and Interpreted
⮚ High Performance
Java Programming Environment
• Java programming environment includes a number of development
tools to develop Applications and Applets.
• These development tools are part of a system called “Java
Development Kit” (JDK).
• The JDK includes
⮚ Packages that contain predefined classes
⮚ Compiler
⮚ Debugger
• JDK provides tools in the directory “bin”
• Two main tools javac and java
• javac is the Java compiler that translates source code to intermediate
code “bytecode”. The bytecode file has the extension of “.class”.
• java is the Java interpreter which interprets and executes the .class
files.

• Other tools present in JDK are javadoc, jdb, appletviewer,


servletrunner etc..
Building and running Java Application

The tool used to


compile is javac

The tool used to


interpret is java
Just-In-Time (JIT) compiler
• It is Java compiler that converts source code to the intermediate code
“bytecode”
Java Virtual Machine (JVM)
• JVM (Java Virtual Machine) is an abstract machine.
• It is a specification that provides a runtime environment in
which Java bytecode can be executed.
• JVMs are available for many hardware and software platforms
(i.e. JVM is platform dependent).
• Java programs are portable, i.e. the .class files can be
executed on any computer with JVM.
• JRE (Java Runtime Environment) consists of Java
platform core classes and supporting files.
• JDK consists of development tools but JRE does not. It
only provides an environment to execute Java
applications
JVM architecture
Structure of java program
Documentation Section (Suggested)

Package Declaration (Optional)

Import Statements(Optional)

Interface Statements(Optional)

Class definitions(Optional)

Main class (Essential)


Essential 🡪 main class
• Class declaration
syntax: class <classname>
{
-----
main() function definition
}
• main() function
Main function is
not part of a
particular
Access
object, can be
the
access using the
main()
class name
function
outside
the class
public static void main(String args[])
{
Command line
----- arguments
No return
} value for
main ()
Basic function for print output

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.

• Click “Environment variable” CLASS PATH is an


• Create new variables environment variable that
is used by the application
VARIABLE NAME: path Class Loader or system to
VARIABLE VALUE: c:\....\jdk1.7.0\bin; locate and load the
compiled Java bytecodes
stored in the .class file.
VARIABLE NAME: class path
VARIABLE VALUE: c:\....\jdk1.7.0\bin;
Building and running
• Create a java program using editor like notepad 🡪 save in desired
location with .java extension
• Go to command prompt🡪 cmd
• Set the drive location of the program location
• Compile 🡪 javac <programname>.java
• Execute 🡪 java <programname>
Java Standard Library
• Java API is a collection of classes and methods grouped in the form of
packages. Some are
⮚ java.lang🡪 language support classes like wrappers, strings, etc.

⮚ java.util🡪 utility classes like date,time, basic events, etc.

⮚ java.io🡪 reading and writing in the form of streams.

⮚ Java.awt🡪 classes foe GUI programs

⮚ Java.applet🡪 classes for applet programs

⮚ Java.swing🡪 classes for swing programs


Java Keywords
Datatypes
Cont..
Datatype Default value Default size
boolean false 1 bit
char ‘\u0000’ 2 byte
byte 0 1 byte
short 0 2 byte
int o 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Variables
• Variable is a name given to memory location
• Types of variables
⮚ Local 🡪 local to a block/method
⮚ Instance🡪 within class
⮚ Static🡪 can be accessed with class name , no need of object

• 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
}

for(data_type var : array_name/collection_name)


{
//block of statements
}
While and do-while
while(condition){
//looping 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

• Documentation comments /**---*/


Type conversion and casting
Java’s Automatic type conversion
When one type of data is assigned to another type of variable, the automatic type
conversion will take place if the following two conditions are met
• Two types are compatible – of the same family ex: byte, short, int, long
• The destination type is larger than source type – from byte to int or int to
long but not in reverse

This automatic type conversion is called “widening conversion”.

Ex: int a=15;


long b=a; //auto type conversion
Casting Incompatible Types
• Converting incompatible types or longer-size variables to shorter-sized
variables is to be done explicitly, which is called Type casting or
“narrowing conversion”
• The type casting syntax:
(Target_type)variable;
Ex:
int a;
byte b;
b=(byte)a;
Automatic type Promotion in Expressions
• In expressions , the automatic type promotion will take place
Ex:
byte a=40,b=50,c=100;
int d =(a*b)/c;

// a*b exceeds the range of byte, hence will be promoted to int


Arrays
• Collection of values belonging to the same data type and referred
with same name.
• To access element in array, the position value called index is used.
• In Java index values start from 0 to (n-1) where n is the size of array.
• Array can be of single dimension, two dimension or multidimension in
java.
• Each array contains the length property which gives the no’of
elements in the array.i.e size of the array.
Arr.length---🡪 gives you the length of the “Arr” Array
Single dimension array
• Declaration syntax:
Datatype variablename[];
variablename=new Datatype[size];
or
Datatype[] variablename;
variablename=new Datatype[size];
Or
Datatype variablename[]=new Datatype[size];
Datatype[] variablename=new Datatype[size];
Or
Datatype variablename[]={val1,val2,…….valn}
Multidimensional array
• Ex: [0][0] [0][1] [0][2] [0][3] [0][4]
int towD[][]=new int [4][5]; [1][0] [1][1] [1][2] [1][3] [1][4]
[2][0] [2][1] [2][2] [2][3] [2][4]
[3][0] [3][1] [3][2] [3][3] [3][4]

int twoD2[][]=new int[4][]; [0][0]

twoD2[0]=new int[1]; [1][0] [1][1]

twoD2[1]=new int[2]; [2][0] [2][1] [2][2]

twoD2[2]=new int[3]; [3][0] [3][1] [3][2] [3][3]

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>();

Ex Pseudo-operator 🡪 memory allocation operator

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
}
}

Automatically called when memory allocated


Class_name ob1;
Ob1= new Class_name(<parametrs to be passed>)); --------------> constructor will
be called
Constructors Overloading of constructors

• Constructors can be overloaded i.e can declare more than one

constructor in a class with same name but different signature

• I.e, either the number of parameters or the type of parameters to be

varied.
Method overloading

• Methods can also be overloaded i.e can declare more than one

method in a class with same name but different signature

• i.e., either the number of parameters or the type of parameters or

the return type to be varied.


Reading Input using Scanner class
Scanner class is available in java.util package.
import java.util.Scanner;

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 Constant pool


String concatenation
• String s1=“hi”+” Soni”;

• 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

You might also like