Javappt 2

You might also like

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

Java

Method Overloading
I/O
String
Overloading Methods
• Constructors all have the same name.
• Methods are distinguished by their
• signature
• name
• number of arguments
• type of arguments
• position of arguments
• method overloading means, a class can also have multiple usual
methods with the same name.
Polymorphism
• Allows a single method or operator associated with different meaning
depending on the type of data passed to it.
• It can be realised through:
• Method Overloading
• Operator Overloading (Supported in C++, but not in Java)
• Defining the same method with different argument types (method
overloading) – polymorphism.
• The method body can have different logic depending on the data
type of arguments.
Demonstrate method overloading
class OverloadDemo { class Overload {
void test() { public static void main(String args[]) {
System.out.println("No parameters");} OverloadDemo ob = new OverloadDemo();
void test(int a) { double result;
System.out.println("a: " + a);} // call all versions of test()
void test(int a, int b) { ob.test();
System.out.println("a and b: " + a + " " + b);} ob.test(10);
double test(double a){ ob.test(10, 20);
System.out.println("double a: " + a); result = ob.test(123.25);
return a*a; System.out.println("Result of
} ob.test(123.25): " + result);
} }}
Demonstrate method overloading
class peri{
class Perimeter{
public static void main(String args[]){
int p;
int perimeter(int l,int b) { int res;
p=(l+b)*2; Perimeter pr=new Perimeter();
return p; res=pr.perimeter(10,20);
} System.out.println("Perimeter of Rectangle"+res);
int perimeter(int s) { res=pr.perimeter(10);
p=4*s;
return p; System.out.println("Perimeter of Square"+res);
res=pr.perimeter(10,20,30);
} System.out.println("Perimeter of Triangle"+res);
int perimeter(int s1,int s2,int s3) {
p=s1+s2+s3; }
return p; }
}
}
Overloading Constructors
class Box { Box(double len) {
double width; width = height = depth = len;}
double height; double volume() {
double depth; return width * height * depth;
Box(double w, double h, double d) { }}
width = w; class OverloadCons {
height = h; public static void main(String args[]) {
depth = d; Box mybox1 = new Box(10, 20, 15);
} Box mybox2 = new Box();
Box() { Box mycube = new Box(7);
width = -1; // use -1 to indicate double vol;
height = -1; // an uninitialized vol = mybox1.volume();
depth = -1; // box System.out.println("Volume of mybox1 is " +
} vol);
Overloading Constructors
vol = mybox2.volume(); The output produced by this program
System.out.println("Volume of is :
mybox2 is " + vol); Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
vol = mycube.volume(); Volume of mycube is 343.0
System.out.println("Volume of
cube is " + vol);
}
}
Using Objects as Parameters
class Test { class PassOb {
int a, b; public static void main(String args[]) {
Test(int i, int j) {a = I;b = j;} Test ob1 = new Test(100, 22);
// return true if o is equal to the invoking Test ob2 = new Test(100, 22);
object Test ob3 = new Test(-1, -1);
boolean equals(Test o) { System.out.println("ob1 == ob2: " +
if(o.a == a && o.b == b) return true; ob1.equals(ob2));
else return false; System.out.println("ob1 == ob3: " +
} ob1.equals(ob3));
} }}

Output
ob1 == ob2: true
ob1 == ob3: false
pass object to constructor Objects are passed by reference.
Box(Box ob) { class CallByRef {
width = ob.width;
height = ob.height; public static void main(String args[]) {
depth = ob.depth; Test ob = new Test(15, 20);
}
In main method you can write
System.out.println("ob.a and ob.b
Box mybox1 = new Box(10, 20, 15);
before call: “ +ob.a + " " + ob.b);
Box myclone = new Box(mybox1); ob.meth(ob);
System.out.println("ob.a and ob.b
Objects are passed by reference.
class Test {
after call: " +
int a, b; ob.a + " " + ob.b);
Test(int i, int j) {a = i;b = j;} }
void meth(Test o) {
o.a *= 2;o.b /= 2;}
}
Returning Objects
class Test { Test ob2;
int a; ob2 = ob1.incrByTen();
Test(int i) {a = i;} System.out.println("ob1.a: " + ob1.a);
Test incrByTen() { System.out.println("ob2.a: " + ob2.a);
Test temp = new Test(a+10); ob2 = ob2.incrByTen();
return temp; System.out.println("ob2.a after
}} second increase: "+ ob2.a);
class RetOb { }}
public static void main(String args[]) { //output
Test ob1 = new Test(2); ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
Introducing Access Control
class Test { class AccessTest {
int a; // default access public static void main(String args[]) {
public int b; // public access Test ob = new Test();
private int c; // private access ob.a = 10;
void setc(int i) { c =i;} ob.b = 20;
int getc() { return c;} // ob.c = 100; // Error!
} ob.setc(100); // OK
System.out.println("a, b, and c: " +
ob.a + " " + ob.b + " " + ob.getc());}
}
Static members
• Java supports definition of global methods and variables that can be
accessed without creating objects of a class.
• Such members are called Static members.
• Define a variable by marking with the static methods.
• This feature is useful when we want to create a variable common to all
instances of a class.
• One of the most common example is to have a variable that could keep a
count of how many objects of a class have been created.
• Note: Java creates only one copy for a static variable which can be used
even if the class is never instantiated
Static members

• Static Variables are defined using static


• Access with the class name
ClassName.StatVarName
• Instance Vs Static Variables
• Instance variables :
• One copy per object.
• Every object has its own instance variable.
• Static variables :
• One copy per class
Static Member
class Rectangle { class TestRectangle {
private int width; public static void main(String args[]) {
private int height;
Rectangle r1 = new Rectangle(10, 30);
public static int numRect=0;
int a1 = r1.area();
Rectangle(int w,int h){
width=w; System.out.println(“Area of the rectangle 1is” + a1);
height = h; Rectangle r2 = new Rectangle(20, 30);
numRect++;
} int a2 = r2.area();
// methods System.out.println(“Area of the rectangle 2is” + a2);
public int area() { int count=Rectangle.numRect;
return width * height; System.out.println(“No of rectangle is” + count);
} }
} }
Static members
public static void main(String args[]) {
class UseStatic { meth(42);
static int a = 3; }
}
static int b; Output:
static void meth(int x) { Static block initialized.
x = 42
System.out.println("x = " + x); a=3
System.out.println("a = " + a); b = 12
As soon as the UseStatic class is loaded, all of the
System.out.println("b = " + b); static statements are run.
} First, a is set to 3, then the static block executes,
which prints a message and then initializes b
static { to a*4 or 12.
Then main( ) is called, which calls meth( ),
System.out.println("Static block passing 42 to x.
initialized."); The three println( ) statements refer to the two
static variables a and b, as well as to the local
b = a * 4; variable x.
}
Static Methods
• A class can have methods that are defined
• as static (e.g., main method).
• Static methods can be accessed without using objects. Also, there is NO need to
create objects. They are prefixed with keyword ―static
• 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. (The keyword super relates to
inheritance)
• Static methods are generally used to group related library functions that don‘t
depend on data members of its class. For example, Math library functions.
Example
Comparator class with Static methods
class Comparator { class MyClass {
public static int max(int a, int b) { public static void main(String args[]) {
if( a > b) return a; String s1 = “Heritage";
String s2 = “Institute";
else return b;
String s3 = “Kolkata";
} int a = 10;
public static String max(String a, String int b = 20;
b) {
System.out.println(Comparator.max(a, b));
if( a.compareTo (b) > 0) System.out.println(Comparator.max(s1, s2));
System.out.println(Comparator.max(s1, s3));
return a;
}
else return b;
}
} //Directly accessed using ClassName (NO Objects)
}
Final Members
• A field declared with keyword final is con stant—its value cannot be
changed after it’s initialized
• final int ARRAY_SIZ E = 10 ;
• Final float PI = 4.141;
• They can not be declared inside a method .
• They should be used only as class data members in the beginning of the
class.
• Same as class variables and they do not take any space on individual
objects of the class
• Making a method final ensures that the functionality defined in this
method will never be altered in any way.
Input And Output
BufferedReader
Scanner
Input And Output
• Input is the data what we give to the program.
• Output is the data what we receive from the program in the form of
result.
• Stream represents flow of data i.e. sequence of data.
• To give input we use InputStream and to receive output we use
OutputStream.
Streams
• Java implements streams within class hierarchies defined in the java.io
package.
• A stream is an ordered sequence of data.
• A stream is linked to a physical device by the Java I/O system.
• All streams behave in the same manner, even if the actual physical devices
to which they are linked differ.
• An I/O Stream represents an input source or an output destination.
• Java defines two different types of Streams-
• Byte Streams
• Character Streams
• Byte streams provide a convenient means for handling input and output of
bytes.
• Byte streams are used, for example, when reading or writing binary data.
Reading Input from console
• Character streams provide a convenient means for handling input and
output of characters.
• In some cases, character streams are more efficient than byte streams.
• The abstract classes InputStream and OutputStream define several key
methods that the other stream classes implement.
• Two of the most important methods are read( )and write( ), which,
respectively, read and write bytes of data.
• Both methods are declared as abstract inside InputStream and
OutputStream.
predefined stream
• java.lang package defines a class called System, which encapsulates several
aspects of the run-time environment.
• System contains three predefined stream variables: in, out, and err.
• These fields are declared as public, static, and final within System.
• This means that they can be used by any other part of your program and
without reference to a specific System object.
predefined stream

• System.out refers to the standard output stream. By default, this is the


console.
• System.in refers to standard input, which is the keyboard by default.
• System.err refers to the standard error stream, which also is the console
by default.
• However, these streams may be redirected to any compatible I/O device.
• System.in is an object of type InputStream;
• System.out and System.err are objects of type PrintStream.
How input is read from Keyboard?

connected to send data to


System.in InputStream
BufferedReader
Reader

It represents It reads data from It reads data from


keyboard. To read keyboard and InputStreamReader and
data from keyboard send that data to stores data in buffer. It has
it should be got methods so that data
connected to BufferedReader. can be easily accessed.
InputStreamReader
How input is read from Keyboard?
• In Java, console input is accomplished by reading from System.in.
• To obtain a character-based stream that is attached to the console, wrap
System.in in a BufferedReader object.
• BufferedReader supports a buffered input stream.
• Its most commonly used constructor is:
• BufferedReader (Reader inputReader)
• Here, inputReader is the stream that is linked to the instance of
BufferedReader that is being created.
• Reader is an abstract class. One of its concrete subclasses is
InputStreamReader, which converts bytes to characters.
How input is read from Keyboard?
• To obtain an InputStreamReader object that is linked to System.in, use the
following constructor:
InputStreamReader(InputStream inputStream)
• Because System.in refers to an object of type InputStream, it can be used
for inputStream.
• Putting it all together, the following line of code creates a BufferedReader
that is connected to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

• After this statement executes, br is a character-based stream that is linked


to the console through System.in.
BufferedReader

BufferedReader bufferedreader = new


BufferedReader(new InputStreamReader(System.in));

int a = bufferedreader.read(); read one character


Methods
If you input A it will store 65 in a.
String name = bufferedreader.readLine();
•Each time read( ) is called, int read()
it reads a character from the input String readLine()
stream and returns it as an integer
value.
• It returns –1 when the end of the stream is encountered.
Example
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String input = reader.readLine();
double number = Double.parseDouble(input); System.out.println(input + ":"
+ Math.sqrt(number)); reader.close();
}
}
Scanner Class to receive input
• Scanner class is one of the class of Java which provides the
methods to get inputs.

• Scanner class is present in java.util package so we import this


package in our program.

• We first create an object of Scanner class and then we use the


methods of Scanner class.
• Scanner a = new Scanner(System.in);
• Following are methods of Scanner class:

• nextLine( ) to input a string

• next().charAt(0) input character

• nextByte() to input a byte value

• nextInt( ) to input an integer

• nextFloat( ) to input a float

• nextLong( ) for Long Values

• nextDouble() for double values


To Receive Integer Input
import java.util.Scanner;
class GetInput {
public static void main(String args[]) {
int a;
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer "+a);
}}
To Receive float Input
import java.util.Scanner;
class GetInput {
public static void main(String args[]) {
float b;
Scanner in = new Scanner(System.in);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float "+b);
}}
To Receive String Input
import java.util.Scanner;

class GetInput {

public static void main(String args[]) {


String s;

Scanner in = new Scanner(System.in);

System.out.println("Enter a string");
s = in.nextLine();

System.out.println("You entered string"+s);

}}
Scannerdemo1.java
import java.util.*;
public class scannerdemo1{
public static void main (String []args ) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter name");
String name = sc.nextLine();
System.out.println("enter age");
int age = sc.nextInt();
System.out.println("enter gender");
char gender = sc.next().charAt(0);
System.out.println("name is"+name);
System.out.println("age ="+age);
System.out.println("gender ="+gender);
}
}
student.java
import java.util.*;
class student{
int rno,age,m1,m2,m3;
float max,average;
void accept() {
Scanner sc= new Scanner(System.in);
System.out.println("enter roll no.");
rno=sc.nextInt();
System.out.println("enter age");
age=sc.nextInt();
System.out.println("enter marks in 3 subjects");
m1=sc.nextInt();
m2=sc.nextInt();
m3=sc.nextInt();
}
student.java
void compute() {
average=(m1+m2+m3)/3;
int a=Math.max(m1,m2);
max=Math.max(a,m3);
}
void display() {
System.out.println("roll no."+rno);
System.out.println("age"+age);
System.out.println("m1"+m1);
System.out.println("m2"+m2);
System.out.println("m3"+m3);
System.out.println("average"+average);
System.out.println("maximum marks"+max);
}
student.java
public static void main(String args[]) {
int i
student obj[]=new student[3];
//student [] obj=new student[3];
for(i=0;i<3;i++)
{
obj[i]=new student();
}
for(i=0;i<3;i++)
{
obj[i].accept();
obj[i].compute();
obj[i].display();
}
}
String in Java
• String manipulation is the most common operation performed in Java programs.
• The easiest way to represent a String (a sequence of characters) is by using an array of
characters.
• Example:
char place[] = new char[4];
place[0] = ‘J’;
place[1] = ‘a‘;
place[2] = ‘v‘;
place[3] = ‘a‘;
• Although character arrays have the advantage of being able to query their length, they
themselves are too primitive and don‘t support a range of common string operations.
• For example, copying a string, searching for specific pattern etc.
• Recognizing the importance and common usage of String manipulation in large
software projects, Java supports String as one of the fundamental data type at the
language level. Strings related book keeping operations (e.g., end of string) are
handled automatically.
String Operations in Java
• Following are some useful classes that Java provides for String
operations.
• String Class
• StringBuffer Class
• StringTokenizer Class
String Class

• String class provides many operations for manipulating strings.


• Constructors
• Utility
• Comparisons
• Conversions
• String objects are read-only (immutable)
Strings Basics
• Declaration and Creation:
• String stringName;
• stringName = new String (“string value”);
• Example:
String city;
city = new String (“Bangalore”);
city=“Kolkata”;
• Length of string can be accessed by invoking length()method defined in
String class:
• int len = city.length();
String operations and Arrays

• Java Strings can be concatenated using the + operator.


• String city = “New” +”York”;
• String city1 = “Delhi”;
• String city2 =“New “+city1;
• Strings Arrays
• String city[] = new String[5];
• city[0] = new String(“Kolkata”);
• city[1] = new String(“Mumbai”);
• ……
• String metros[] = {“Delhi”, ”Mumbai”, ”Chennai”, ”kolkata”};
String class
• Constructors
• public String()
• Constructs an empty String.
• Public String(String value)
• Constructs a new string copying the specified string.
• Some useful operations
• public int length()
• Returns the length of the string.
• public charAt(int index)
• Returns the character at the specified location (index)
• public int compareTo( String anotherString)
• public int compareToIgnoreCase( String anotherString)
• Compare the Strings Returns an integer +1, 0, or -1 to indicate whether this string is
greater than, equal to, or less than.
Some useful operations

• equals(s1)
• Returns true if this string is equal to string s1.
• equalsIgnoreCase(s1)
• Returns true if this string is equal to string s1; it is case insensitive.
• String replace(char oldChar, char newChar)
• Returns a new string with all instances of the oldChar replaced with newChar.
• public trim()
• Trims leading and trailing white spaces.
• public String toLowerCase()
• public String toUpperCase()
• Changes as specified.
String Class - example

class StringDemo {
public static void main(String[] args) {
String s = new String("Have a nice Day");
System.out.println("String Length = " + s.length() );
System.out.println("Modified String = " + s.replace('n', 'N'));
System.out.println("Converted to Uppercase = " + s.toUpperCase());
System.out.println("Converted to Lowercase = " + s.toLowerCase()); }}
String Length = 15
Modified String = Have a Nice Day
Converted to Uppercase = HAVE A NICE DAY
Converted to Lowercase = have a nice day
StringBuffer class
• Java StringBuffer class is used to created mutable (modifiable) string.
The StringBuffer class in java is same as String class except it is mutable
i.e. it can be changed.
• Constructors
• StringBuffer(): creates an empty string buffer with the initial capacity of 16.
• StringBuffer(String str): creates a string buffer with the specified string.
• StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.
Important methods
• append(String s): is used to append the specified string with this
string.
• insert(int offset, String s): is used to insert the specified string with
this string at the specified position.
• replace(int startIndex, int endIndex, String str): is used to replace the
string from specified startIndex and endIndex.
• delete(int startIndex, int endIndex): is used to delete the string from
specified startIndex and endIndex.
• reverse(): is used to reverse the string.
methods of StringBuffer class

• int capacity(): is used to return the current capacity.


• charAt(int index): is used to return the character at the specified
position.
• int length(): is used to return the length of the string i.e. total
number of characters.
• substring(int beginIndex): is used to return the substring from the
specified beginIndex.
• substring(int beginIndex, int endIndex): is used to return the
substring from the specified beginIndex and endIndex.
Example
class A{
public static void main(String args[]){
StringBuffer sb1=new StringBuffer("Hello ");
sb1.append("Java");
System.out.println(sb1);//prints Hello Java
StringBuffer sb2=new StringBuffer("Hello ");
sb2.insert(1,"Java");
System.out.println(sb2);//prints HJavaello
StringBuffer sb3=new StringBuffer("Hello");
sb3.replace(1,3,"Java");
System.out.println(sb3);//prints HJavalo
StringBuffer sb4=new StringBuffer("Hello");
sb4.delete(1,3);
System.out.println(sb4);//prints Hlo
}
}
StringTokenizer
• The java.util.StringTokenizer class allows you to break a string into tokens.
It is simple way to break string.
• Constructors
• StringTokenizer(String str)
• creates StringTokenizer with specified string.
• StringTokenizer(String str, String delim)
• creates StringTokenizer with specified string and delimeter.
• StringTokenizer(String str, String delim, boolean returnValue)
• creates StringTokenizer with specified string, delimeter and returnValue. If return
value is true, delimiter characters are considered to be tokens. If it is false, delimiter
characters serve to separate tokens.
Methods of StringTokenizer class
• boolean hasMoreTokens()
• checks if there is more tokens available.
• String nextToken()
• returns the next token from the StringTokenizer object.
• String nextToken(String delim)
• returns the next token based on the delimeter.
• boolean hasMoreElements()
• same as hasMoreTokens() method.
• Object nextElement()
• same as nextToken() but its return type is Object.
• int countTokens()
• returns the total number of tokens.
Example
import java.util.StringTokenizer; Output:
public class Simple{ Heritage
public static void main(String args[]){
Institute
StringTokenizer st = new StringTokenizer(“Heritage
Institute of Technology"," "); of
while (st.hasMoreTokens()) { Technology
System.out.println(st.nextToken());
}
}
}
Example
import java.util.StringTokenizer;
class w
{
public static void main(String args[])
{
String input=args[0];
String del=args[1];
//StringTokenizer st=new StringTokenizer(" 10 20 30"," ");
StringTokenizer st=new StringTokenizer(input,del);
int sum=0;
int i=0;
System.out.println( "length : "+st.countTokens() );
int token[]=new int[st.countTokens()];
while(st.hasMoreTokens())
{
token[i]= Integer.parseInt(st.nextToken());
System.out.println( "num : "+token[i]);
i++;
}
int count=token.length;
for ( i = 0; i < count; i++ )
sum =sum + token[i];
System.out.println( "sum : "+sum );

}
}

You might also like