[go: up one dir, main page]

0% found this document useful (0 votes)
10 views20 pages

Lecture 2

This document provides an overview of Java programming concepts, including the Scanner class for user input, methods, constructors, and the use of keywords like final and this. It explains how to create and use methods, method overloading, and constructors, including default, parameterized, and copy constructors. Additionally, it covers the concepts of getters and setters, as well as the significance of static and public attributes in Java.
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)
10 views20 pages

Lecture 2

This document provides an overview of Java programming concepts, including the Scanner class for user input, methods, constructors, and the use of keywords like final and this. It explains how to create and use methods, method overloading, and constructors, including default, parameterized, and copy constructors. Additionally, it covers the concepts of getters and setters, as well as the significance of static and public attributes in Java.
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/ 20

Lecture 2

- By Prof. Shivani Supe


Scanner Class
The Scanner class is used to get user input, and it is found in the java.util package.
import java.util.Scanner; OR import.java.util*;
class Main {
public static void main(String[] args) {
// creates an object of Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// takes input from the keyboard
String name = input.nextLine();
// prints the name
System.out.println("My name is " + name);
// closes the scanner
input.close();
}
}
Example : Find the area of Circle
import java.util.Scanner;

class AreaOfCircle

{ public static void main(String args[])

{ Scanner s= new Scanner(System.in);

System.out.println("Enter the radius:");

double r= s.nextDouble();

double area=(22*r*r)/7 ;

System.out.println("Area of Circle is: " + area);

}
Java Methods
● A method is a block of code which only runs when it is called.
● Methods are used to perform certain actions, and they are also known as functions.

Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses
(). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own
methods to perform certain actions:

public class Main {

static void myMethod() {

System.out.println("I just got executed!"); }

public static void main(String[] args) {

myMethod();

}}
● myMethod() is the name of the method
● static means that the method belongs to the Main class and not an object of the Main class.
● void means that this method does not have a return value.
● A method can also be called multiple times

public class Main {

static void myMethod(String fname) {

System.out.println(fname + " Leo");

public static void main(String[] args) {

myMethod("Liam");

myMethod("Jenny");

myMethod("Anju");

}
When a parameter is passed to the method, it is called an argument.

Multiple Parameters
public class Main {

static void myMethod(String fname, int age) {

System.out.println(fname + " is " + age); }

public static void main(String[] args) {

myMethod("Liam", 5);

myMethod("Jenny", 8);

myMethod("Anju", 31);

}}
Java Method Overloading
With method overloading, multiple methods can have the same name with different
parameters:
static int plusMethod(int x, int y) {

return x + y; }

static double plusMethod(double x, double y) {

return x + y; }

public static void main(String[] args) {

int myNum1 = plusMethod(8, 5);

double myNum2 = plusMethod(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2); }


Static vs. Public
You will often see Java programs that have either static or public attributes and methods.

In the example below, we created a static method, which means that it can be accessed without creating an object
of the class, unlike public, which can only be accessed by objects:

public class Main { // Static method


static void myStaticMethod() { System.out.println("Static methods can be called without creating objects"); }
// Public method
public void myPublicMethod() { System.out.println("Public methods must be called by creating objects"); }
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object }}
Constructors
● In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.
● It is a special type of method which is used to initialize the object.
● Every time an object is created using the new keyword, at least one constructor is
called.
● It calls a default constructor if there is no constructor available in the class. In such
case, Java compiler provides a default constructor by default.

Rules for Creating Java Constructor


There are following rules for defining a constructor:

1. Constructor name must be the same as its class name.


2. A Constructor must have no explicit return type.
3. A Java constructor cannot be abstract, static, final, and synchronized.
Types of Constructors in Java

● Default Constructor
● Parameterized Constructor
● Copy Constructor

1. Default Constructor in Java

A constructor that has no parameters is known as default constructor. A default constructor


is invisible. And if we write a constructor with no arguments, the compiler does not create
a default constructor. It is taken out. It is being overloaded and called a parameterized
constructor. The default constructor changed into the parameterized constructor. But
Parameterized constructor can’t change the default constructor.
class Main {

int a;

boolean b;

public static void main(String[] args) {

// calls default constructor

Main obj = new Main();

System.out.println("Default Value:");

System.out.println("a = " + obj.a);

System.out.println("b = " + obj.b);

}}
2. Parameterized Constructor in Java

A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with
our own values, then use a parameterized constructor.
class Main {

String languages;

// constructor accepting single value

Main(String lang) {

languages = lang;

System.out.println(languages + " Programming Language"); }

public static void main(String[] args) { // call constructor by passing a single value

Main obj1 = new Main("Java");

Main obj2 = new Main("Python");


3. Copy Constructor in Java #OnHold
Unlike other constructors copy constructor is passed with another object which copies the data
available from the passed object to the newly created object.
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(Person another) {
this(another.name, another.age);
}
// Getters and setters for the instance variables
}
Constructor overloading in Java
In Java, we can overload constructors like methods. The constructor overloading can be defined as the concept of
having more than one constructor with different parameters so that every constructor can perform a different task.

public class Student { //instance variables of the class


int id;
String name;
Student(){ System.out.println("this a default constructor"); }
Student(int i, String n){
id = i;
name = n; }
public static void main(String[] args) {
//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
System.out.println("\nParameterized Constructor values: \n");
Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name); } }
Getter and Setter in Java
Getter in Java: Getter returns the value (accessors), it returns the value of data type int, String,
double, float, etc. For the program’s convenience, the getter starts with the word “get” followed by the
variable name.
Setter in Java: While Setter sets or updates the value (mutators). It sets the value for any variable
used in a class’s programs. and starts with the word “set” followed by the variable name.
class ABC{

private variable;

public void setVariable(int x){

this.variable=x; }

public int getVariable{

return variable;

}} //Note: In both getter and setter, the first letter of the variable should be capital.
import java.io.*; // Importing input output classes
class GetSet { // Member variable of this class
private int num;
// Method 1 - Setter
public void setNumber(int number) {// Checking if number is between 1 to 10 exclusive
if (number < 1 || number > 10) {
throw new IllegalArgumentException();
}
num = number;
} // Method 2 - Getter
public int getNumber() { return num; }
}// Class 2
// Main class
class ABC{ // Main driver method
public static void main(String[] args)
{GetSet obj = new GetSet();
// Calling method 1 inside main() method
obj.setNumber(5);
System.out.println(obj.getNumber()); }}
Keywords

1. Final : The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
● variable
● method
● class

1) Java final variable


class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
} } O/P : Compile Time Error
2) Java final method
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
} }

3) Java final class


final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
} }
2) this : The this keyword refers to the current object in a method or constructor. The most common use of the this
keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class
attribute is shadowed by a method or constructor parameter).

this can also be used to:

● Invoke current class constructor


● Invoke current class method
● Return the current class object
● Pass an argument in the method call
● Pass an argument in the constructor call
public class Main {
int x;
public Main(int x) { // Constructor with a parameter
this.x = x; }
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x); }}

You might also like