Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
74 views

Java Record

1. The document discusses string operations in Java. It defines a string as a collection of characters and describes how strings are represented and initialized in Java. It then lists and describes 15 common string methods like length(), equals(), concat(), indexOf(), toUpperCase(), and trim(). 2. The document also discusses class and object concepts in Java. It defines a class as a collection of members (data and methods) that can be used to create multiple objects. An object is an instance of a class. 3. The document provides examples of method overloading and method overriding in Java. Method overloading allows creating multiple methods with the same name but different parameters, while method overriding involves redefining a superclass method

Uploaded by

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

Java Record

1. The document discusses string operations in Java. It defines a string as a collection of characters and describes how strings are represented and initialized in Java. It then lists and describes 15 common string methods like length(), equals(), concat(), indexOf(), toUpperCase(), and trim(). 2. The document also discusses class and object concepts in Java. It defines a class as a collection of members (data and methods) that can be used to create multiple objects. An object is an instance of a class. 3. The document provides examples of method overloading and method overriding in Java. Method overloading allows creating multiple methods with the same name but different parameters, while method overriding involves redefining a superclass method

Uploaded by

bhavana
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

1.

STRING OPERATIONS

STRING:-

A group of collections of characteristics is called a string.In java “string” is a predefined final class.A java string
is a initialized object of the string class.A string is represented with in double quotes.we can assign string literal
directly to string variables

Eg: String name=”rama”;

String address=new string(“vsp”);

String methods:

String class defines no of methods that are for to perform various string manipulation tasks

1.public Boolean is empty();

To find string is empty(OR)not.

2.public Int Length();

To find the length of the string.

3.public Boolean equals(string s)

It returns ‘true’when two strings are equals(or)it return ‘false’ when two string are not equal

4.public Boolean equal Ignore case(string)

Same as “equals”but it doesn’tconsider class

5.public int compare to (string);

Comparing string lexicographically means after comparison

Method should returns difference b/w string content.

6.public char charAt(int index);

Returns the character at the specified index.

7.public int code point At(Int index);

Returns the characters Ascii value at the specified Index.

8.public string concat (string);

Merging the specified string at the end of the existed string


9.public Boolean contains(string);

To find given string is available(Or)not in a existed string

10.public Int index of (char ch)

Return the index with in existed string of first occurence of the specified character.

11.public Int index of (char ch)int from index

Return the index within existed string of the first occurrence of the specified character ,searching from the
specified index.

12.public string to uppercase();

Converts all characters in string to uppercase.

13.public string to lowercase();

Convert all characters in string to lowercase

14.public string replace (“char old char”,char new char”);

Replacing a character with new character

15.public string trim();

Deleting trailing and leading spaces of a string

program

class StringOperations

public static void main(String args[])

String str1="welcometoaditya";

String str2="WelcomeToAdityaCollege";

System.out.println(str1.concat(str2));

System.out.println(str1.length());

System.out.println(str1.charAt(3));
System.out.println(str1.equals(str2));

String str3="abcd";

System.out.println(str3.replace('a','k'));

System.out.println(str1.indexOf('T'));

System.out.println(str3.toUpperCase());

System.out.println(str2.toLowerCase());

System.out.println(str3.isEmpty());

str1.equalsIgnoreCase(str2);

OUTPUT

D:\rajesh>javac StringOperations.java

D:\rajesh>java StringOperations

welcometoadityaWelcomeToAdityaCollege

15

false

kbcd

-1

ABCD

welcometoadityacollege

false

false
2. creating class and object

Class:- Class defines the structure of an object

Class is collection of members(data+method)

Class may be thought of data type and object as a variable of that data type

Once a class has been defined we can create no of objects belonging to that class .so a class is collection of
similar type.

Eg:- class employee

Members

Employee e,e1;

Object: Object are the basic run time entities in object oriented system. They may also represent user defined
data types

Each object contains data and code to manipulate the data

Object is the physical reality of class

Object is an instance of class

Any programming is analyzed term of object and nature of communication between them.

program

import java.util.Scanner;

import java.util.Scanner;

class CalculateVolumeAndSurface

public static void main(String args[])

CalculateVolumeAndSurface c=new CalculateVolumeAndSurface();


c.volumeandsurfacearea();

public void volumeandsurfacearea()

double length,width,height;

System.out.println("enter the length");

Scanner scn=new Scanner(System.in);

length=scn.nextDouble();

System.out.println("enter the width");

width=scn.nextDouble();

System.out.println("enter the width");

height=scn.nextDouble();

System.out.println("Volume = " + length*width*height);

System.out.println("Surface area = " + 2*((length*width)+(width*height)+


(height*length)));

OUTPUT

D:\rajesh>javac CalculateVolumeAndSurface.java

D:\rajesh>java CalculateVolumeAndSurface

enter the length

12

enter the width

22

enter the width


44

Volume = 11616.0

Surface area = 3520.0

3.a) Method overloading

Method overloading:-

Creating multiple methods with having same method name but different parameters is called method overloading
It is used to executed same logic with different type of arguments we can develop method overloading in same
class to crate an overloaded method,method name should be same and difference in number and type of
parameters

program

class Test1

public int sum(int x,int y)

return x+y;

public int sum(int x,int y,int z)

return x+y+z;

public float sum(float x,float y)

return x+y;

}
class Test2 extends Test1

public float sum(float x,float y)

return x+y;

public float sum(float x,float y,float z)

return x+y+z;

public int sum(int x,int y)

return x+y;

class Methodoverloading

Public static void main(String args[])

Test1 t=new Test1();

Test2 t1=new Test2();

System.out.println(t.sum(123,432));

System.out.println(t.sum(12,13,14));

System.out.println(t.sum(12.5f,13.5f));

System.out.println(t1.sum(14.5f,15.5f));
System.out.println(t1.sum(16.5f,17.5f,18.5f));

System.out.println(t1.sum(12,43));

Output:-

D:\rajesh>javac Methodoverloading.java

D:\rajesh>java Methodoverloading

555

39

26.0

30.0

52.5

55

3.b)Method overriding

Method overriding:-

Pre-defining super class non-static method in subclass with same prototype. This is called method overriding

program

class Vehicle

void start()

System.out.println("Vehicle is started");

void run()
{

System.out.println("Vehicle is running");

void stop()

System.out.println("Vehicle is stopped");

class Bike2 extends Vehicle

void start()

System.out.println("Bike is not started");

void run()

System.out.println("Bike is not in running state, because the bike is not started...!!");

public static void main(String args[])

Bike2 obj = new Bike2();

obj.start();

obj.run();
Vehicle v= new Vehicle();

v.stop();

Output:

D:\rajesh>javac Bike2.java

D:\rajesh>java Bike2

Bike is not started

Bike is not in running state, because the bike is not started...!!

Vehicle is stopped

4.Implementation of Abstract class

Abstract class:-if the class is having abstract keyword at the class definition it is called an abstract class.

If a class contain abstract method (or)methods it must be declared as abstract class.

When we don’t want to create object for our class then make it as abstract class.

Sub class developers provide implementation for abstract methods according to their business requirement which
is called method overloading.

If subclass developer does not override the super class abstract class then subclass should be declared abstract
class.

We can’t create object for abstract class.

Abstract class variable can give reference for its subclass object.

Program

abstract class Cycle

Cycle()

{
System.out.println("I bought new Gear cycle");

abstract void run();

void changeGear()

System.out.println("gear changed to 3rd Gear");

class Honda extends Cycle

void run()

System.out.println("running safely..");

class TestAbstraction2

public static void main(String args[])

Cycle obj = new Honda();

obj.run();

obj.changeGear();

Output:-
D:\rajesh>javac TestAbstraction2.java

D:\rajesh>java TestAbstraction2

I bought new Gear cycle

running safely..

gear changed to 3rd Gear

5. Implementing Exception Handling

Exception:

Exception is a runtime error caused due to logical mistakes occurred during program exception.

Exception is a condition that is caused by a runtime error in the program.

It is a signal that indicates some soft of abnormal condition has been occurred in a code at runtime.

To represent different logical mistakes java defined different exception classes. All the classes are subclasses of
‘throwable” class.

In java exception is an object of one of the subclass of throwable class.

When an exception is raised program exception is terminated abnormally. It means statement which are placed
after exception causing statement won’t be executed.

Exception Handling:

The process of handling exception is converting JVM given exception message into user understandable message
and also for stopping abnormal termination of the program.

Exception handling code should be embedded in java program to handle exception and to print (or) pass user
understandable message.

Program

import java.util.*;

class ExceptionDemo

public static void main(String args[])

{
System.out.println("enter the first value");

Scanner scn=new Scanner(System.in);

int i=scn.nextInt();

System.out.println("enter the second value");

int j=scn.nextInt();

try

double k=i/j;

System.out.println("the value is:"+k);

catch(Exception e)

System.out.println(e);

Output:

Javac ExceptionDemo.java

Java ExceptionDemo

enter the first value:

200

enter the second value

10

The value is 20.


6. Creating Package

Package: A folder that is linked with java class files is called as a packages.

Package is a java folder

It is used to group related classes and Interface

The Grouping is usually done according to their functionality

Packages are contains for classes it is also used to seperate new classes from existed classes

Java.lang: Provides classes that are fundamental to the design of the Java programming language.

Java.io: Provides for system input and output through data streams, serialization and the file system.

Java.awt: Contains all of the classes for creating user interfaces and for painting graphics and images.

Java.util: This class contains utility classes like vector, ArrayList, Scanner date,etc..,

Program

package p1;

public class A

public void m1()

System.out.println("in m1");

public void m2()

System.out.println("in m2");

}
package p2;

public class D

public void m3()

System.out.println("in m3");

import p1.A;

class F

public static void main(String[] s)

A a1=new A();

a1.m1();

a1.m2();

Output:

d:/ rajesh/javac -d . A.java

javac F.java

java F

in m1

in m2
7.Interface

Interface:

Interface is fully un-impletmented class used for declaring set of operations of object. we can develop a "losely
coupled" runtime ploymorphysm object

* it allows us to define only public static final variables and public abstract methods for declaring a object
operation.

* it is mainly introduced in java to support for developin multple inheritance

* it is used for developing a specification this means that do not implement anycode

* data fields contains only constant

syntax:

interface interfacename

final variables declarations;

abstract methods declarations;

Program

interface Shapes

void getArea();

void getSlides();

class Rectangle implements Shapes

public void getArea ()

{
int length=6;

int breadth=5;

int area=length*breadth;

System.out.println("The area of the square is "+area);

public void getSlides()

System.out.println("I have 4 sides");

class Square implements Shapes

public void getArea ()

int length=6;

int area=length*length;

System.out.println("The area of the rectangle is "+area);

public void getSlides()

public static void main(String[] s)

Rectangle r1=new Rectangle();


r1.getArea();

r1.getSlides();

Square s1=new Square();

s1.getSlides();

Output:

D:\rajesh>javac Square.java

D:\rajesh>java Square

The area of the rectangle is 30

I have 4 sides

The area of the square is 25

I can get sides of a polygon

Create MultiThreading

Multi Threading:

Thread: A thread is an independent sequential flow of execution. A thread is created in java stack Area.
It executes methods in sequence one after one. Every Program will have atlease one Thread.

A thread is similar to that has a single flow of control. A program that contains multiple flow of control is
known as MultiThreading program.

A thread which is created by JVM is called main method which executes the flow of main() method.
Threads are created by form main Thread.

Program

class RunnableDemo implements Runnable

{
private Thread t;

private String threadName;

RunnableDemo( String name)

threadName = name;

System.out.println("Creating " + threadName );

public void run()

System.out.println("Running " + threadName );

try

for(int i = 4; i > 0; i--)

System.out.println("Thread: " + threadName + ", " + i);

Thread.sleep(50);

catch (InterruptedException e)

{
System.out.println("Thread " + threadName + " interrupted.");

System.out.println("Thread " + threadName + " exiting.");

public void start ()

System.out.println("Starting " + threadName );

if (t == null)

t = new Thread (this, threadName);

t.start ();

class MultiThreadingDemo

public static void main(String args[])

RunnableDemo R1 = new RunnableDemo( "Thread-1");

R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");

R2.start();

OUTPUT

D:\rajesh>javac MultiThreadingDemo.java

D:\rajesh>java MultiThreadingDemo

Creating Thread-1

Starting Thread-1

Creating Thread-2

Starting Thread-2

Running Thread-1

Thread: Thread-1, 4

Running Thread-2

Thread: Thread-2, 4

Thread: Thread-1, 3

Thread: Thread-2, 3

Thread: Thread-1, 2

Thread: Thread-2, 2

Thread: Thread-1, 1

Thread: Thread-2, 1

Thread Thread-1 exiting.

Thread Thread-2 exiting.

Applets program to draw various program


Web Applets:

Applet: Applets are small java programs that are primarly used in internet applications. They can be transported
over the internet from one computer to another and run using the “applet Viewer” (or) any web browser that
supports java

Applet life cycle:

Every java applets a set of default behavior from the “applet” class.

When an applet is loaded, java automatically calls a series of applet class methods which are called life
cycle methods

Each method changes applet states include:

1. Born on initialize state


2. Runing state
3. Idle State
4. Dead or destroy state

Program

import java.awt.*;
import java.applet.*;

public class DrawingPolygon extends Applet

public void paint(Graphics g)

int x[] = { 70, 150, 190, 80, 100 };


int y[] = { 80, 110, 160, 190, 100 };
g.drawPolygon (x, y, 5);

int x1[] = { 210, 280, 330, 210, 230 };


int y1[] = { 70, 110, 160, 190, 100 };
g.fillPolygon (x1, y1, 5);

/*
<html>
<body>
<applet code="DrawingPolygon.class" width="3000" height="1500">
</applet>
</body>
</html>

*/

Output:

D:\rajesh>javac DrawingPolygon.java

D:\rajesh>appletViewer DrawingPolygon.java
10.implementing multiple inheritance

Multiple inheritence:- it is a process of deriving the properities(or) methods from more than one class into
another class is termed as multiple inheritence

Java doesn’t support multiple inheritence by using classes but it can be supported by using with interface

Program

interface Car

int speed=50;

public void totalDistance();

interface Train

int distance=150;
public void speed();

class Vehicle implements Car,Train

int totalDistance;

int avgSpeed;

public void totalDistance()

totalDistance=speed*distance;

System.out.println("Total Distance Travelled : "+totalDistance);

public void speed()

int avgSpeed=totalDistance/speed;

System.out.println("Average Speed maintained : "+avgSpeed);

public static void main(String args[])

Vehicle v1=new Vehicle();

v1.totalDistance();

v1.speed();

Output:

D:\rajesh>javac Vehicle.java
D:\rajesh>java Vehicle

Total Distance Travelled : 7500

Average Speed maintained : 150

11.THREAD PRIORTIES

THREAD PRIORTIES

Every thread created in JVM is assigned with a priority which affects the order in which it is scheduled by
processor for running .JVM Executive threads based on their priority and scheduling.

Java permits us to set the priority of thread using the set priority () method:

Thread Name.set priority(int);

Thread class defines several priority constants

Final int MIN_PRIORITY=1;

Final int NORM_PRIORITY=5;

Final int MAX_PRIORITY=10;

Program

import java.lang.*;

class ThreadDemo extends Thread {

public void run()

System.out.println("Inside run method");

public static void main(String[] args)

{
ThreadDemo t1 = new ThreadDemo();

ThreadDemo t2 = new ThreadDemo();

ThreadDemo t3 = new ThreadDemo();

System.out.println("t1 thread priority : "+ t1.getPriority());

System.out.println("t2 thread priority : "+ t2.getPriority());

System.out.println("t3 thread priority : "+ t3.getPriority());

t1.setPriority(2);

t2.setPriority(5);

t3.setPriority(8);

System.out.println("t1 thread priority : "+ t1.getPriority());

System.out.println("t2 thread priority : "+ t2.getPriority());

System.out.println("t3 thread priority : "+ t3.getPriority());

System.out.println("Currently Executing Thread : "+ Thread.currentThread().getName());

System.out.println("Main thread priority : "+Thread.currentThread().getPriority());

Thread.currentThread().setPriority(10);

System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());

Output:

D:\rajesh>javac ThreadDemo.java

D:\rajesh>java ThreadDemo

t1 thread priority : 5

t2 thread priority : 5

t3 thread priority : 5
t1 thread priority : 2

t2 thread priority : 5

t3 thread priority : 8

Currently Executing Thread : main

Main thread priority : 5

Main thread priority : 10

You might also like