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

Classes in Java

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

Classes in Java

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

JAVA Programming

Course Instructor: Dr. Suvojit Dhara


School of Computer Science
UPES Dehradun
TOPICs to be discussed
 Java Basics

 Printing methods
 main() method
 Data types

 Wrapper Classes

 Classes

 Fields
 Access Modifiers
 Methods
 Method Overloading
 Class Modifiers
Let’s START …!!!
First Program

class HelloUPES{
public static void main(String[] args){
System.out.println("Hello UPES, How is the
Josh?");
}
}

UNKNOWNS…
Compile: javac HelloUPES.java
 class
Execute: java HelloUPES.java  public
 static
Output: Hello UPES, How is the Josh?  main
 System.out.println . . . . . . . ???
Printing in Java Program
println() vs print()

class A{
public static void main(String[]
args){
System.out.println("Hello");
System.out.println("UPES");

System.out.print("Hello");
System.out.print("UPES");
}
}

Output: Hello
Alternate method: System.out.print() UPES
HelloUPES
main() method
class HelloUPES{
public static void main(String[] args){
System.out.println("Hello UPES, How is the
Josh?");
}
 The
} program declares a class called HelloUPES with a single member: a method called
main().
 The main() method of a class, if declared exactly as shown, is executed when you run the
class as an application. When run, a main() method can create objects, evaluate expressions,
invoke other methods, and do anything else needed to define an application’s behavior.
 The main() method is declared public so that anyone can invoke it (in this case the Java
virtual machine).
 The main() method is declared static, meaning that the method belongs to the class and is not
associated with a particular instance of the class. It can be invoked using the class name,
without creating an object of the class.
main() method
class HelloUPES{
public static void main(String[] args){
System.out.println("Hello UPES, How is the
Josh?");
}
}
 The main() method is declared void because it doesn't return a value and so has no return
type.
 The main() method’s only parameter is an array of String objects, referred to by the name
args. Arrays of objects are denoted by the square brackets [] that follow the type name.
 In this example, the body of main() contains a single statement that invokes the println()
method and the semicolon ends the statement. A method is invoked by supplying an object
reference (in this case System.out the out field of the System class) and a method named
println() separated by a dot (.).
Data Types
 The Java programming language has built-in “primitive” data types to support integer,
floating-point, boolean, and character values. The primitive data types are:

boolean: either True or false


char: 16-bit Unicode character (unsigned)
byte: 8-bit integer (signed)
short: 16-bit integer (signed)
int: 32-bit integer (signed)
long: 64-bit integer (signed)
float: 32-bit floating-point (IEEE 754)
double: 64-bit floating-point (IEEE 754)

 For each primitive type there is also a corresponding object type, generally termed a
“wrapper” class. For example, the class Integer is the wrapper class for int.
Wrapper Class

 Java's primitive data types (int, char, boolean, double, etc.) are not objects, but in many
situations, you might need to treat them as objects, such as when working with collections,
using generics, or needing access to methods that are available only for objects. A wrapper
class in Java is a class that encapsulates a primitive data type, allowing it to be used as an
object.

 Wrapper classes in Java allow you to treat primitive data types as objects by encapsulating
them in class instances. This allows you to access methods and additional functionality
provided by those wrapper classes. Primitive data types themselves do not have methods,
and you cannot directly call methods on them.
Wrapper Class

 Here are the primitive data types and their corresponding wrapper classes:

 byte → Byte
 short → Short
 int → Integer
 long → Long
 float → Float
 double → Double
 char → Character
 boolean → Boolean
SIZE field in Wrapper Class

class size{ Output:


public static void main(String[] args){
System.out.println("char " + char 16
Character.SIZE); byte 8
System.out.println("byte " + Byte.SIZE); short 16
System.out.println("short " + int 32
Short.SIZE); long 64
System.out.println("int " + float 32
Integer.SIZE);
Double 64
System.out.println("long " + Long.SIZE);
System.out.println("float " +
Float.SIZE);
System.out.println("double " +
 SIZE is public static final variable of wrapper class.
Double.SIZE);
}
}
Methods for Parsing
Integer.parseInt(String): Converts a String to an int.
Double.parseDouble(String): Converts a String to a double.
Boolean.parseBoolean(String): Converts a String to a boolean.

class _parse{
public static void main(String[] args){
String str = "45";
String str1 = "true";
int a = Integer.parseInt(str);
double d = Double.parseDouble(str); Output:
boolean b1 =
Boolean.parseBoolean(str1);
boolean b2 = 45 45.0 true
Boolean.parseBoolean(str); false
System.out.print(a+" "+d+" "+b1+"
"+b2);
}
}
Methods for Conversion
Integer.toString(int): Converts an int to a String.
Double.toString(double): Converts a double to a String.
Boolean.toString(boolean): Converts a boolean to a String.

class _tostring{
public static void main(String[] args)
{
Integer a = 100; Output:
Double d = 67.23;
Boolean b = true;
String str = a.toString();
100
System.out.println(str); 67.23
str = d.toString(); true
System.out.println(str);
str = b.toString();
System.out.print(str);
}
}
Methods for Formatting
Integer.toHexString(int): Returns the hexadecimal string representation of an int.
Integer.parseInt(String, int): Parses a string as a signed integer using the specified radix.

class radix{
public static void main(String[] args){ Output:
int a = 12;
String str = Integer.toHexString(a);
System.out.println(str); c
int b = Integer.parseInt(str, 16); 12
System.out.println(b); 10
System.out.println(Integer.parseInt("12",
8)); 12
System.out.println(Integer.parseInt("12",
10)); }
}
Class
 Every object has a class that defines its data and behavior. In other words, Class is the
blueprint for objects in Java.

 Each class has three kinds of members:

1. Fields are data variables associated with a class and its objects. Fields store results
of computations performed by the class.

2. Methods contain the executable code of a class. Methods are built from
statements. The way in which methods are invoked, and the statements contained
within those methods, are what ultimately directs program execution.

3. Classes and interfaces can be members of other classes or interfaces.


Fields
 A class’s variables are called fields.
Field Initialization
Field Declaration  When a field is declared it can be
 Field declarations can be preceded
initialized by assigning it a value of the
by modifiers that control certain corresponding types.
properties of the field:
-- access modifiers double zero = 0.0; // constant
-- Static double sum = 4.5 + 3.7; // constant
-- Final expression
-- Transient: This double zeroCopy = zero; // field
relates to object serialization double rootTwo = Math.sqrt(2); // method
-- volatile: This relates to invocation
synchronization and memory model double someVal = sum +
issues 2*Math.sqrt(rootTwo); // mixed
Access Modifiers
 If every member of every class and object were accessible to every other class and object
then understanding, debugging, and maintaining programs would be an almost impossible
task.
 One of the strengths of object-oriented programming is its support for encapsulation and
information hiding.
 To control access from other classes, class members have four possible access modifiers:

1. package: Members declared with no access modifier are accessible in classes in


the same package, as well as in the class itself.
2. public: Members declared public are accessible anywhere the class is accessible.
3. protected: Members declared protected are accessible in subclasses of the class, in
classes in the same package, and in the class itself.
4. private: Members declared private are accessible only in the class itself.
Static Fields
 Sometimes you want only one instance of a field shared by all objects of a class. You create
such fields by declaring them static, so they are called static fields or class variables. When
you declare a static field in a class only one copy of the field exists, no matter how many
objects of the class are created.

 Within its own class a static field can be referred to directly, but when accessed externally it
must usually be accessed using the class name. For example, we could print the value of a
static field “nextID” within the class Body as follows:

System.out.println(Body.nextID);

 A static member may also be accessed using a reference to an object of that class, such as:

System.out.println(mercury.nextID);
Static Field Example
class B{ class B{
int a = 0; static int a = 0;
void fun(){ void fun(){
a++; a++;
} }
} }
class A{ class A{
public static void main(String[] public static void main(String[]
arg){ arg){
B b1 = new B(); B b1 = new B();
b1.fun(); b1.fun();
B b2 = new B(); B b2 = new B();
b2.fun(); b2.fun();
B b3 = new B(); B b3 = new B();
b3.fun(); b3.fun();

System.out.println("a = "+ System.out.println("a = "+


b1.a); b1.a);
System.out.println("a = "+ System.out.println("a = "+
b2.a); b2.a);
System.out.println("a = "+ System.out.println("a = "+
b3.a); Output: a = 1 b3.a); Output: a = 3
} }
} a=1 } a=3
Final Fields
 A final field is one whose value cannot be changed after it has been initialized.
 Any attempt to assign to such a field will produce a compile-time error.
 When do you decide whether a field should be final? Consider three things:

1. Does the field represent an immutable property of the object?


2. Is the value of the field always known at the time the object is created?
3. Is it always practical and appropriate to set the value of the field when the object is
created?
class B{
final static int a = 50;
} error: cannot assign a value to final
class A{ variable a
public static void main(String[] B.a = 200;
arg){ ^
B.a = 200;
System.out.println("a =
"+B.a);
Methods
 A function declared within a class scope is called methods of the class.

Method Declaration Method Invoking


 A method in the class is declared as follows:  A method inside a class can be
invoked by preceding an object of the
public int max(int a, int
b) {
class (or subclass based on the access
control) following a dot (.) operator.
//method body
} class B{
public void fun(int n){
 public is the access specifier. System.out.println(n); }
}
 int is the return type of the method. class A{
public static void main(String[]
 max is the name of the method. arg){
 inside (), are the arguments/parameters of B b = new B();
b.fun(3); }
the method. There may be zero or more }
arguments of a method. Output: 3
Method Overloading
 Under the OOP paradigm of Polymorphism, a class in Java can have multiple methods with
the same name but different set of parameters (parameters can differ in numbers or type).
This phenomena is called Method Overloading.

class addition{
public int add(int a, int b){
return (a + b); }
public double add(double a, double b){
return (a + b); }
public int add(int a, int b, int c){
return (a + b * c); } Output:
}
class overloading{ 5
public static void main(String[] arg){
13.3
addition ad = new addition();
System.out.println(ad.add(2,3)); 14
System.out.println(ad.add(4.0,
9.3));

System.out.println(ad.add(2,3,4)); }
Some Important Points
 static fields/variables can be created at class level only.
 A static variable is allotted memory once.
 static methods cannot use this or super keywords.
 abstract methods cannot be static.
 static methods cannot be overridden.
 static methods can only access static variables and other static methods.
 A static inner class cannot access instance variables and methods of the outer class without
the object’s reference.
 A static inner class can access all static variables and methods of the outer class.
 In Java, the outer class cannot be static.
Class Modifiers
A class declaration can be preceded by class modifiers that give the class certain properties:

 public: A public class is publicly accessible: Anyone can declare references to objects of the
class or access its public members. Without a modifier a class is only accessible within its
own package.
 abstract: An abstract class is considered incomplete and no instances of the class may be
created. Usually this is because the class contains abstract methods that must be
implemented by a subclass.
 final: A final class cannot be subclassed.

NOTE: A class cannot be both final and abstract.


Summary
Today, we learned about

• Java printing method, main method.

• Various datatypes in Java

• Wrapper class, size variable and some important methods (parsing, conversion, formatting)

• Class in Java

 Fields (Access specifiers, static, final keywords)


 Methods (Method overloading)
 Class modifiers

You might also like