0% found this document useful (0 votes)
28 views36 pages

Day5 Userdefined, This, Constructors

Uploaded by

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

Day5 Userdefined, This, Constructors

Uploaded by

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

User Defined Input, Constructors

TNS India Foundation | ‹#›


Partners in Economic Transformation
Recap

● Packages - A set of classes and interfaces grouped together.


● Access Modifiers - It help to restrict the scope of a class, constructor, variable,
method, or data member.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q1. Which of these keywords is used to define packages in Java?

A pKg

B pkg

C package

D Package

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q1. Which of these keywords is used to define packages in Java?

A pKg

B pkg

C package

D Package

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2. Which access modifier restricts a variable or method to be accessible only


within the same class?

A public

B private

C protected

D default

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2. Which access modifier restricts a variable or method to be accessible only


within the same class?

A public

B private

C protected

D default

TNS India Foundation | ‹#›


Partners in Economic Transformation
Learning Objective
• Getting Started with User Input in Java
• Exploring the Scanner Class: Utilizing next() and nextLine()
• Character Input Handling through the Scanner Class
• Utilizing hasNextInt(), hasNextDouble(), hasNextLine(), and hasNext() with the
Scanner Class
• Understanding Java BufferedReader
• Introduction to Constructors in Java
• Differentiating Types of Constructors with examples

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hook
class DoubleJeopardy
{
public static void main(String args[])
{
double value=32;
System.out.println(“A double:”+value);

}
}
What was the input like? Was it fixed?

What happens if I wanted to run the program with different input?

TNS India Foundation | ‹#›


Partners in Economic Transformation
Different ways in which user input can be given
• Using Scanner class
• Using BufferReader

TNS India Foundation | ‹#›


Partners in Economic Transformation
Scanner Class

• The scanner class is the blueprint from which an object can be created.

• This object is used in reading user input.

• The syntax for creating an object from Scanner class is as follows:

Scanner input = new Scanner(System.in);

TNS India Foundation | ‹#›


Partners in Economic Transformation
Activity :Execute the Program

public class UserName


{
public static void main(String args[])
{
Scanner input= new Scanner(System.in);
System.out.println(“Enter your name:”);
String n= input.nextLine();
System.out.println(“Hello” + n);
}
}

TNS India Foundation | ‹#›


Partners in Economic Transformation
Scanner Class

Include this line before the class definition and return the program.

import java.util.Scanner;

TNS India Foundation | ‹#›


Partners in Economic Transformation
Scanner Class Function

• next():Reads a single word value from the input. (stops at “whitespace”)

• nextLine() :Reads a single line value from the input. (stops at \n)

• nextInt():Reads a single int value from the input.

• nextFloat():Reads a single float value from the input.

• nextDouble():Reads a single int value from the input. (Format: Up to 64 digit decimal)

TNS India Foundation | ‹#›


Partners in Economic Transformation
Reading characters using Scanner Class

char c = reader.next().charAt(0);
Where reader is the name of the Scanner object and charAt(0) reads the first character
of a string.

TNS India Foundation | ‹#›


Partners in Economic Transformation
hasNextdouble() and
hasNextInt(),hasNextLine,hasNext()
● hasNextDouble() method of java.util.Scanner class returns true if the next token in
this scanner’s input can be interpreted as a Double using the nextDouble() method.
● hasnextInt() method of java.util.Scanner class scans the next token of the input as
a Int.
● hasNextLine():Returns true if there is another line in the input of this scanner.
● hasNext():Returns true if this scanner has another token in its input.
● If the translation is successful, the scanner advances past the input that matched.
● It always returns boolean value.

TNS India Foundation | ‹#›


Partners in Economic Transformation
BufferedReader Object Creation Syntax

● The BufferedReader maintains an internal buffer of 8192 characters


● During the read operation in BufferedReader, a chunk of characters is read from the
disk and stored in the internal buffer. And from the internal buffer characters are read
individually.
● The number of communication to the disk is reduced. This is why reading characters is
faster using BufferedReader.
● To connect BufferedReader object to file,
● create a FileReader object by passing a valid file name.
● create a BufferedReader object by using FileReader class object.

Example
FileReader fr=new FileReader(“filename.txt”);
BufferedReader br=new BufferedReader(fr)
TNS India Foundation | ‹#›
Partners in Economic Transformation
Hands on Coding

TNS India Foundation | ‹#›


Partners in Economic Transformation
Constructors

• A class provides the plan for an object.

• Every time new is used in creating an object, at least one constructor is called.

• A constructor is a special method that initializes objects and has the same name as the
class.

• Constructors do not return any value.

• A constructor in Java can not be abstract, final, static, or Synchronized.

• constructors are used to assigning values to the class variables at the time of object
creation, either explicitly done by the programmer or by Java itself (default constructor).

TNS India Foundation | ‹#›


Partners in Economic Transformation
Types of Constructors

TNS India Foundation | ‹#›


Partners in Economic Transformation
Default Constructor

• If a constructor is not created explicitly in the class definition, a default constructor will be
created.

• Default constructors are also constructors with no arguments passed to them.

• The purpose of a default constructor is to provide the default values to the object like 0,
null, etc., depending on the type.

• If there is no constructor in a class, compiler automatically creates a default


constructor.

TNS India Foundation | ‹#›


Partners in Economic Transformation
TNS India Foundation | ‹#›
Partners in Economic Transformation
Default Constructor -Example

Class Bike1
{
Bike1()
{
System.out.println(“Bike is created”);
}
public static void main(String args[])
{
Bike1 b = new Bike1();
}

TNS India Foundation | ‹#›


Partners in Economic Transformation
Difference between Constructor and Method
Java Constructor Java Method

A constructor is used to initialize A method is used to expose the


the state of an object. behavior of an object.

A constructor must not have a A method must have a return


return type. type.
The constructor is invoked The method is invoked explicitly.
implicitly.
The Java compiler provides a The method is not provided by
default constructor if you don't the compiler in any case.
have any constructor in a class.

The constructor name must be The method name may or may


same as the class name. not be same as the class name.
TNS India Foundation | ‹#›
Partners in Economic Transformation
Parameterized Constructor
• A Constructor with arguments(or you can say parameters) is known as Parameterized
constructor.
• We can have any number of Parameterized Constructor
• The purpose of a parameterized constructor is to initialize values to the objects when we
create them.
• Example:
Person(String name, int age)
{
// Constructor code.
}

TNS India Foundation | ‹#›


Partners in Economic Transformation
TNS India Foundation | ‹#›
Partners in Economic Transformation
Real Time Application

Custom Data Structures:


Constructors are utilized when creating custom data structures or classes. When you design
classes to represent data in a specific way (e.g., linked lists, trees, graphs), constructors
play a crucial role in initializing the objects of these classes. They set up initial values and
configurations for the instances of these data structures.

Game Development:
Constructors are used extensively in game development frameworks and engines. They are
utilized to create objects representing game elements, characters, levels, and other
components. Constructors initialize these objects with initial states, positions, behaviors, etc.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hands on Coding

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q1. What is true about constructor?

A It can contain return type

B It can take any number of parameters

C It can have any non access modifiers

D Constructor cannot throw an exception

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q1. What is true about constructor?

A It can contain return type

B It can take any number of parameters

C It can have any non access modifiers

D Constructor cannot throw an exception

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2. Which Scanner class method is used to read String value?

A nextLine()

B next()

C readString()

D Both a & b

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2. Which Scanner class method is used to read String value?

A nextLine()

B next()

C readString()

D Both a & b

TNS India Foundation | ‹#›


Partners in Economic Transformation
Summary

● A constructor is a special method that initializes objects and has the same name as the
class.
● Scanner class is used to get user input and found in java.util package.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Assignment Question -1

● Write a java program to get all your details like your Full name with Initial, roll number
,Grade and percentage.

Sample Input: Sample Output:


Ayan S Ayan S
5220365 5220365
A A
9.5% 9.5%

TNS India Foundation | ‹#›


Partners in Economic Transformation
Assignment Question -2
Create a default constructor in the class Student that prints a message “Student object is
created” when the program is run.

● Define a class Commission described as follows:


● Data Members: Name, Address, Phone, Sales_amount
● Member methods:
● (i) To accept details of the sales employee
● (ii) to calculate the commission as follows: Sales_amount >= 100000, commission =
10%; 50000 <= Sales_amount < 100000, commission = 5%; 30000 <= Sales_amount <
50000, commission = 3%; Sales_amount < 30000, no commission.

Write the main method to create an object of a class and call the above member
method.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Assignment Question -3

Define a class Circle with the following data members:


(i) Radius
(ii) Colour
Create these member methods for this class:
(i) getInput() that accepts the details of the circle
(ii) calcArea that calculates the area of the circle using the radius and displays the same.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Let’s Reflect -

1. What is your major learning from today’s session?


2. How are you going to use this learning in your journey on the job?

TNS India Foundation | ‹#›


Partners in Economic Transformation

You might also like