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

java unit 2

This document covers fundamental concepts of Java programming, including classes, objects, methods, constructors, and access control. It explains the structure of a Java class, the creation of instances, method overloading, and the significance of access modifiers. Additionally, it discusses garbage collection, recursion, and inner classes, providing examples and syntax for better understanding.

Uploaded by

saradha.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

java unit 2

This document covers fundamental concepts of Java programming, including classes, objects, methods, constructors, and access control. It explains the structure of a Java class, the creation of instances, method overloading, and the significance of access modifiers. Additionally, it discusses garbage collection, recursion, and inner classes, providing examples and syntax for better understanding.

Uploaded by

saradha.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

UNIT II

• Classes
• Objects
• Constructors
• Overloading method
• Access control
• Static and fixed methods
• Inner classes, string classes
• Inheritance, over riding method
• Abstract class
CLASS

• A class is an object oriented construct. It is designed to


perform a specific task.
• A Java class is defined by its class name, an open curly
brace, a list of methods and fields, and a close curly
brace.
• The name of the class is made of alphabetical characters
and digits without spaces, the first character must be
alphabetical.
• A class is a module that can contain executable code.
• Every program you write will be a class.

2
syntax of CLASS

class <ClassName>
{
attributes/variables;
Constructors();
methods();
}
3
INSTANCE

• Instance is an Object of a class which is an entity with its


own attribute values and methods.

• Creating an Instance

ClassName refVariable;
refVariable = new Constructor();
or
ClassName refVariable = new Constructor();

4
Methods

Method: A named sequence of statements that can be executed


together to perform a particular action.

• A special method named main signifies the code that should


be executed when your program runs.

• Your program can have other methods in addition to main.

5
BYTE CODE

• Java programs are translated into an


intermediate language called bytecode.
• Bytecode is the same no matter which computer
platform it is run on.
• Bytecode is translated into native code that the
computer can execute on a program called the
Java Virtual Machine (JVM).
• The Bytecode can be executed on any computer
that has the JVM. Hence Java’s slogan, “Write
once, run anywhere”.

6
Helloworld
• To begin you need a text editor.
– Notepad, TextPad, …
– Create a new directory.
• Open new file, save it as HelloWorld.java in new directory
• Write the following code and save the file:
/*simple java application*/
class HelloWorld
{
public static void main(String[] args)
{
System.out.println(“Hello World”); //displays a string
}
}
• Note: the file name should have the same name as the class
7
Compiling and running

• Assuming the HelloWorld.java is saved in the D:\JavaProjects\HelloWorld


directory:

• Open the a Console, (startRun…), type cmd.

• Type cd \ to return to d:>

• Go to the helloworld directry


– (cd D:\JavaProjects\HelloWorld)

• compile your application


– javac HelloWorld.java

• Run your application


– java HelloWorld.class

8
Closer Look

• Three primary components: source code comments, the


HelloWorld class definition, and the main method.

• Comments are ignored by the compiler but are useful to other


programmers.

• Two supported kinds of comments


– /* text */ The compiler ignores everything from /* to */.

– // text The compiler ignores everything from // to the end of the


line.

• The most basic form of a class definition is


– class name {…}
9
– Every program must have at least one class, and this class should contain
Reserved Words
Reserved words or keywords are words that have a specific meaning to
the compiler and cannot be used for other purposes in the program.
For example, when the compiler sees the word class, it understands
that the word after class is the name for the class.

10
Modifiers
Java uses certain reserved words called modifiers that specify the
properties of the data, methods, and classes and how they can be
used. Examples of modifiers are public and static. Other modifiers are
private, final, abstract, and protected. A public datum, method, or class
can be accessed by other programs. A private datum or method cannot
be accessed by other programs.

11
Statements

A statement represents an action or a sequence of actions. The


statement System.out.println("Welcome to Java!") in the program is a
statement to display the greeting "Welcome to Java!" Every statement
in Java ends with a semicolon (;).
Blocks

A pair of braces in a program


forms a block that groups
components of a program.

public class Test {


Class block
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Method block
}
}

13
Closer Look, cont…

• In the Java programming language, every application must


contain a main method whose signature is:
– public static void main(String[] args)
– The modifiers public and static can be written in either order (public
static or static public).
– You can name the argument anything you want, but most programmers
choose "args" or "argv.“

• This is the string array that will contains the command line
arrguments.
– The main method is the entry point for your application and will
subsequently invoke all the other methods required by your program.

• System.out.println("Hello World!");
– uses the System class from the API to print the "Hello World!" message
to standard output.
14
Class Definition

• A class contains a name, several variable declarations (instance variables) and several
method declarations. All are called members of the class.
• General form of a class:
class classname {
type instance-variable-1;

type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }

type method-name-m(parameter-list) { … }
}
15
Example: Class Usage
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
} }
16
Constructor
• A constructor initializes the instance variables of an object.
• It is called immediately after the object is created but before the
new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default
return type of a class
• constructor is the same class
• When the class has no constructor, the default constructor
automatically initializes all its instance variables with zero.

17
Example: Constructor

public class Hello {


String name;
//Constructor
Hello(){
this.name = "BeginnersBook.com"; //this keyword refers to the current object.
}
public static void main(String[] args) {
Hello obj = new Hello();
System.out.println(obj.name);
}
}

19
No – Arg Constructor

Constructor with no arguments is known as No-arg constructor. The


signature is same as default constructor, however body can have any code
unlike default constructor where the body of the constructor is empty.
class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
Parameterized Constructor
• Constructor with arguments(or you can say parameters)
is known as Parameterized constructor

• In this example we have a parameterized constructor with two


parameters id and name. While creating the objects obj1 and obj2 I
have passed two arguments so that this constructor gets invoked after
creation of obj1 and obj2.
public class Employee {

int empId;
String empName;

//parameterized constructor with two parameters


Employee(int id, String name){
this.empId = id;
this.empName = name;
}
void info(){
System.out.println("Id: "+empId+" Name: "+empName);
}

public static void main(String args[]){


Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info();
} 22
}
Methods

• General form of a method definition:


type name(parameter-list) {
… return value;

}
• Components:
1) type - type of values returned by the method. If a method does not return any
value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists separated by commas
4) return value indicates what value is returned by the method.
23
Example: Method

• Classes declare methods to hide their internal data


structures, as well as for their own internal use: Within a
class, we can refer directly to its member variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
24
Parameterized Method

• Parameters increase generality and applicability of a method:


• 1) method without parameters
int square() { return 10*10; }
• 2) method with parameters
int square(int i) { return i*i; }
• Parameter: a variable receiving value at the time the method is
invoked.
• Argument: a value passed to the method when it is invoked.

25
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of variables and
methods.
• Encapsulation, safely sealing data within the capsule of
the class Prevents programmers from relying on details
of class implementation, so you can update without
worry
• Helps in protecting against accidental or wrong usage.
• Keeps code elegant and clean (easier to maintain)

26
Access Modifiers: Public, Private, Protected

• Public: keyword applied to a class, makes it


available/visible everywhere. Applied to a
method or variable, completely visible.
• Default(No visibility modifier is specified): it
behaves like public in its package and private in
other packages.
• Default Public keyword applied to a class, makes
it available/visible everywhere. Applied to a
method or variable, completely visible.

27
• Private fields or methods for a class only visible within that class.
Private members are not visible within subclasses, and are not
inherited.
• Protected members of a class are visible within the class, subclasses
and also within all classes that are in the same package as that class.

28
Visibility
public class Circle {
private double x,y,r;

// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
29
Keyword this

• Can be used by any object to refer to itself in


any class method
• Typically used to
– Avoid variable name collisions
– Pass the receiver as an argument
– Chain constructors

30
Keyword this

• Keyword this allows a method to refer to the object that invoked it.
• It can be used inside any method to refer to the current object:
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}

31
Garbage Collection

• Garbage collection is a mechanism to remove objects from memory


when they are no longer needed.
• Garbage collection is carried out by the garbage collector:
• 1) The garbage collector keeps track of how many references an object
has.
• 2) It removes an object from memory when it has no longer any
references.
• 3) Thereafter, the memory occupied by the object can be allocated
again.
• 4) The garbage collector invokes the finalize method.
32
finalize() Method

• A constructor helps to initialize an object just after it has been


created.
• In contrast, the finalize method is invoked just before the object is
destroyed:
• 1) implemented inside a class as:
protected void finalize() { … }
• 2) implemented when the usual way of removing objects from
memory is insufficient, and some special actions has to be carried out

33
Method Overloading

• It is legal for a class to have two or more methods


with the same name.
• However, Java has to be able to uniquely associate
the invocation of a method with its definition relying
on the number and types of arguments.
• Therefore the same-named methods must be
distinguished:
• 1) by the number of arguments, or
• 2) by the types of arguments
• Overloading and inheritance are two ways to
implement polymorphism.
34
Example: Overloading

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

35
Constructor Overloading
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height * depth; }
}
36
Parameter Passing

• Two types of variables:


1) simple types
2) class types
• Two corresponding ways of how the arguments are passed to
methods:
• 1) by value a method receives a cope of the original value;
parameters of simple types
• 2) by reference a method receives the memory address of the
original value, not the value itself; parameters of class types

37
Call by value
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.print("a and b before call: “);
System.out.println(a + " " + b);
ob.meth(a, b);
System.out.print("a and b after call: ");
System.out.println(a + " " + b);
}
}
38
Call by reference
• As the parameter hold the same address as the argument, changes to the
object inside the method do affect the object used by the argument:
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.print("ob.a and ob.b before call: “);
System.out.println(ob.a + " " + ob.b);
ob.meth(ob);
System.out.print("ob.a and ob.b after call: ");
System.out.println(ob.a + " " + ob.b);
}
}

39
Recursion

• A recursive method is a method that calls itself:


1) all method parameters and local variables are
allocated on the stack
2) arguments are prepared in the corresponding
parameter positions
3) the method code is executed for the new
arguments
4) upon return, all parameters and variables are
removed from the stack
5) the execution continues immediately after the
invocation point
40
Example: Recursion

class Factorial {
int fact(int n) {
if (n==1) return 1;
return fact(n-1) * n;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.print("Factorial of 5 is ");
System.out.println(f.fact(5));
} } 41
Inner classes
• Java inner class or nested class is a class which is declared inside the
class or interface.
• We use inner classes to logically group classes and interfaces in one place
so that it can be more readable and maintainable.
• Additionally, it can access all the members of outer class including private
data members and methods.
• Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Advantage of java inner classes
• There are basically three advantages of inner classes in
java. They are as follows:
• 1) Nested classes represent a special type of
relationship that is it can access all the members
(data members and methods) of outer
class including private.
• 2) Nested classes are used to develop more readable
and maintainable code because it logically group
classes and interfaces in one place only.
• 3) Code Optimization: It requires less code to write.
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
String Handling

• String is probably the most commonly used class in


Java's class library. The obvious reason for this is that
strings are a very important part of programming.
• The first thing to understand about strings is that every
string you create is actually an object of type String.
Even string constants are actually String objects.
• For example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String constant

45
Empty Strings
• An empty String has no characters. It’s length is 0.

String word1 = ""; Empty strings


String word2 = new String();

• Not the same as an uninitialized String.

private String errorMsg; errorMsg


is null
No Argument Constructors
• No-argument constructor creates an empty String. Rarely used.

• A more common approach is to reassign the variable to an empty


literal String. String empty
(Often done = new String();
to reinitialize a variable used to store input.)

String empty = “”;//nothing between quotes


• Java defines one operator for String objects: +.
• It is used to concatenate two strings. For example, this
statement
• String myString = "I" + " like " + "Java.";
results in myString containing
"I like Java."

48
Methods — length, charAt
int length();  Returns the number of characters in
the string

char charAt(i);  Returns the char at position i.

Character positions in strings are numbered starting


from 0 – just like arrays.
Returns:
”Problem".length(); 7
”Window".charAt (2); ’n'
System.out.println ("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))

System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}}

This program generates the following output:


Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3

50
Methods — substring
Returns a new String by copying characters from an existing String.

• String subs = word.substring (i, k); television


• returns the substring of chars in
positions from i to k-1 i k
• String subs = word.substring (i);
television
• returns the substring from the i-th
char to the end
i
Returns:
”television".substring (2,5); “lev"
“immutable".substring (2); “mutable"
“bob".substring (9); "" (empty string)
Methods — Concatenation
String word1 = “re”, word2 = “think”; word3 = “ing”;
int num = 2;
• String result = word1 + word2;
//concatenates word1 and word2 “rethink“
• String result = word1.concat (word2);
//the same as word1 + word2 “rethink“
• result += word3;
//concatenates word3 to result “rethinking”
• result += num; //converts num to String
//and concatenates it to result “rethinking2”
Methods — Find (indexOf)
0 2 6 10 15

String name =“President George Washington";


Returns:
date.indexOf (‘P'); 0
date.indexOf (‘e'); 2
date.indexOf (“George"); 10
(starts searching
date.indexOf (‘e', 3); 6
at position 3)

date.indexOf (“Bob"); -1 (not found)


date.lastIndexOf (‘e'); 15
RANDOM CLASS
Java Random class is used to generate a stream of
pseudorandom numbers.
Random class is part of java.util package.
An instance of Java Random class is used to generate
random numbers.
This class provides several methods to generate random
numbers of type integer, double, long, float, etc.
Java provides three ways to generate random numbers
using some built-in methods and classes as listed below:
 java.util.Random class
 Math.random method : Can Generate Random Numbers of
double type.
 ThreadLocalRandom class

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy