CoreJavamodified 45-90

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 48

Java Selection Statement –

Scanner Class
• Java supports two selection statements: if and switch.
• These statements allow you to control the flow of your program’s
execution based upon conditions known only during run time.
import java.util.Scanner;
public class ScannerDemo
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in); // Here we initialize object s for Scanner class.
System.out.print("Enter the first value a : ");
int a = s.nextInt(); // Scan int type value
System.out.print("Enter the second value b : ");
int b = s.nextInt(); // Scan int type value
int sum = a * b;
System.out.println("The addition of a and b : a + b = "+sum);
}
}

1
Scanner Class
• Here we import java.uti.Scanner because the Scanner class is inside util package of
java library. Than we create reference (object) of class Scanner named s.
• "System.in" This is the predefine library which allow user to enter value in any
variable at run time through keyboard.
• Now in Scanner class there are so many different different methods for scaning
different type of values.
• Here are some in-built methods of Scanner class for scanning different types of
values.
• 1. nextByte() for scanning byte type value.
• 2. nextShort() for scanning short type value.
• 3. nextInt() for scanning int type value.
• 4. nextLong() for scanning long type value.
• 5. nextFloat() for scanning floting point value.
• 6. nextDouble() for scanning double type value.
• 7. next() for scanning a string.

2
IF Statement
• The if statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths.
• Syntax :
• if (condition)
• {
• statement1;
• }

• When the condition is true the Statement within the if is executed. After that execution
continues with the next statement after the if statement.
• If the condition is false then the statement within the if is not executed and the
execution continues with the statement after the if statement.

3
Assignment 3
• Write a java Program to print the Largest among three numbers using if Statement?
import java.util.Scanner;
class larger1 x2=s.nextInt();
{ System.out.println("En
public static void main(String args[]) ter value for x3 : ");
{ x3=s.nextInt();
int x1,x2,x3;
large = x1;
int large;
Scanner s = new if (x2 > large)
Scanner(System.in); large = x2;
System.out.println("Enter value if (x3 > large)
for x1 : "); large = x3;
x1=s.nextInt(); System.out.println("\n\
System.out.println("Enter value
n\tLargest number = " + large);
for x2 : ");
}
}
4
IF-else statement
Syntax:
if (condition) Write a java program to check whether the given mark is
{ pass or fail using if-else statement?
statement1; import java.util.Scanner;
} class result
else {
public static void main(String args[])
{
{
statement2; Scanner s = new Scanner(System.in);
} System.out.println("Enter marks : ");
int marks = s.nextInt();
if (marks<40)
System.out.println("\nThe student has failed .. ");
else
System.out.println("\nThe student has Passed .. ");
}
}

5
IF-else-if Ladder

Syntax :
if(condition)
statements;
else if(condition)
statemenst;
else if(condition)
statements;
...
...
else
statements;
Write a java program to accept the day between 0 to 6 based on that it has to
print day between Sunday to Saturday using if-else-if Ladder.

6
IF-else-If Ladder
import java.util.Scanner;
class Day else if (day == 3)
{ {
public static void main(String args[]) System.out.println("\n
{ Wednesday");
Scanner s = new Scanner(System.in); }
System.out.println("Enet day between 0 to 6
Day = "); else if (day == 4)
int day = s.nextInt(); {
if (day == 0) System.out.println("\n Thursday");
{ }
System.out.println("\n Sunday"); else if (day == 5)
} {
else if (day == 1) System.out.println("\n Friday");
{ }
System.out.println("\n Monday"); else
} {
else if (day == 2) System.out.println("\n Saturday");
{ }
System.out.println("\n Tuesday"); }
} }

7
Nested - IF

Syntax :
if(condition)
{
if(condition)
statements....
else
statements....
}
else
{
if(condition)
statements....
else
statements....
}

Write a java program to accept three values a, b, c from the user and find out
the maxvalue using Nested-if.

8
Nested-IF
import java.util.Scanner; if (a>b)
class MaxValue {
{ if(a>c)
public static void main(String args[]) max=a;
{ else //This else is associate
with this if(a>c)
int a,b,c; max=c;
int max=0; }else //This else is associate
Scanner s = new with this if(a>b)
Scanner(System.in); {
System.out.println("Enter value for a if(b>c)
: "); max=b;
a=s.nextInt(); else //This else is associate
with this if(b>c)
System.out.println("Enter value for b max=c;
: "); }
b=s.nextInt(); System.out.println("\n max value = "
System.out.println("Enter value for c +max);
: "); }
c=s.nextInt(); }

9
Switch Statement
• The switch statement is Java’s multiway branch statement. It
provides an easy way to dispatch execution to different parts of your
code based on the value of an expression.
• Syntax
switch (expression)
{
case value 1 :
statement 1 ; break;
case value 2 :
statement 2 ; break;
...
...
case value N :
statement N ; break;
default :
statements ; break;
}

10
Switch Statement
switch(ch)
import java.util.Scanner; {
public class Calci case 1:
{ ans=a+b;
public static void main(String[] args) System.out.println("a + b = " + ans);
break;
{
case 2:
int a,b,ch; ans=a-b;
double ans; System.out.println("a - b = " + ans);
Scanner s = new Scanner(System.in); break;
System.out.print("Enter a : "); case 3:
ans=a*b;
a=s.nextInt(); System.out.println("a * b = " + ans);
System.out.print("Enter b : "); break;
b=s.nextInt(); case 4:
System.out.println("Enter 1 for addition"); ans=a/b;
System.out.println("a / b = " + ans);
System.out.println("Enter 2 for subtraction"); break;
System.out.println("Enter 3 for default:
multiplication"); System.out.println("Enter correct choice");
System.out.println("Enter 4 for division"); }
System.out.print("Enter your choice : ");
}
ch=s.nextInt(); }

11
Looping Statements
• Loop repeatedly executes the same set of instructions until a
termination condition is met. Write a java program to print the natural
• While Loop Syntax: number from 1 to 10 using while loop?
class while1
while (condition) {
{ public static void main(String args[])
{
body(statements) of
int i=1;
the loop while(i<=10)
} {
System.out.println("\n" + i);
i++;
}
}
}

12
Do While

• Syntax Write a java program to print the natural


number from 10 to 1 using do while loop?
class dowhile1
do {
{ public static void main(String args[])
{
body of the loop int i=10;
} while (condition); do
{
System.out.println("\n" + i);
i--;
}
while(i>=1);
}
}

13
For-Loop
• The for loop repeats a set of statements a certain number of times until
a condition is matched.

• Syntax Write a java program to print the numbers


from 1 to 9 using for loop?
class forLoop1
for (initialization; {
condition; expression) public static void main(String args[])
{
{ int i;
Set of statements; for (i=0;i<10;i++)
} {
System.out.println("\n"+i);
}
}
}

14
Nested Loop

• Java allows loops to be nested. That is, one


loop may be inside another.
• Write a java program to print the below given
pattern using Nested loop.

15
Nested Loop
class Nested
{
public static void main(String args[])
{
int i, j;
for(i=0; i<10; i++)
{
for(j=i; j<10; j++)
{
System.out.print(".");
}
System.out.println();
}
}
}
16
Break Statement

• This statement is used to jump out of a loop.


• Break statement was previously used in switch – case
statements.
• On encountering a break statement within a loop, the
execution continues with the next statement outside the
loop.
• The remaining statements which are after the break and
within the loop are skipped.
• Break statement can also be used with the label of a
statement.

17
}
c

Break

class break1
{
public static void main(String args[])
{
int i = 1;
while (i<=10)
{
System.out.println("\n" + i);
i++;
if (i==5)
{
break;
}
}
}
}
18
Continue

• This statement is used only within looping


statements.
• When the continue statement is encountered,
the next iteration starts.
• The remaining statements in the loop are
skipped. The execution starts from the top of
loop again.

19
Continue
class continue1
{
public static void main(String args[])
{
for (int i=1; i<=10; i++)
{
if (i%2 == 0)
continue;

System.out.println("\n" + i);
}
}
}
20
Return

• The last control statement is return. The


return statement is used to explicitly return
from a method.
• That is, it causes program control to
transfer back to the caller of the method.
• the return statement immediately
terminates the method in which it is
executed.

21
Return
class Return1
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t)
return; // return to caller
System.out.println("This won't execute.");
}
}
22
Java arrays

• To store the data of the same type in the contiguous


memory allocations we use arrays.
• Arrays are always a fixed length abstracted data
structure which can not be altered when required.
• The Array class implicitly extends java.lang.Object so
an array is an instance of Object.

23
Java Array

• Array Decleration

int[]
array_name; //declares
an array of integers
String[] names;
int[][] matrix; //this is an public class Array
array of arrays {
public static void main(String[] args)
{
int[] a = new int[5];
}
}
24
Java Array

• Array Initialization public class array


{
public static void main(String[]
String names[]; args)
names = new String[10]; {
int[] x = new int [101];
for (int i = 0; i<x.length; i++ )
x[i] = i;
int sum = 0;
for(int i = 0; i<x.length; i++)
sum += x[i];
System.out.println(sum);
}
}

25
Two Dimension/ Multi
Dimension Array
public class multiarray{
public static void main(String[] args) {
int[][] a2 = new int[10][5];
for (int i=0; i<a2.length; i++) {
for (int j=0; j<a2[i].length; j++) {
a2[i][j] = i;
System.out.print(" " + a2[i][j]);
}
System.out.println("");
}
}
}
26
Features of Oops

• Object
– Any entity that has state and behavior is known as an object.
– Ex: chair, pen, table, keyboard, bike etc.

• Class
– Collection of objects is called class. It is a logical entity.

• Inheritance
– Inheritance is a mechanism in which one object acquires all
the properties and behavior of another object. It provides
code reusability.
• Polymorphism
– When one task is performed by different ways i.e. known as polymorphism.

27
Features of Oops

• Abstraction
– Abstraction is a process of hiding the implementation details
and showing only the functionality to the user.
– Abstraction lets you focus on what the object does instead of
how it does it.
• Encapsulation
– It is a process of wrapping code and data together into a
single unit, for example capsule i.e. mixed of several medicines.

28
Object oriented Programming System

• Object means a real world entity such as pen,


Chair, table etc.
• Object oriented programming is a methodology
or paradigm to design a program using classes
and objects.
• It simplifies the software development and
maintenance by providing some concepts:
– Object, Class, Inheritance, polymorphism,
Abstraction, Encapsulation.

29
Advantages of OOPs
• Oops makes development and maintenance easier.

• OOPs provides data hiding whereas in Procedure-oriented

programming language a global data can be accessed from anywhere.

• OOPs provides ability to stimulate real-world event much more

efficiently.

30
Naming Convention
Naming Convention
is a rule to follow as
you decide what to
name your
identifiers(e.g.,
class, packages,
variables, method
etc.)
Advantages
Java Naming convention
make java code easier to
read themselves and by
others.

31
Object
• An entity that have state and behavior is called as object.
• Ex: Chair, TV, table pent
• Characteristic of Object:
– State : represents the data of an object. (value)
– Behavior : represents the behavior of an object (Functionality)
– Identity: Object identity is typically implemented via a unique ID.
The value of the ID is not visible to the external user, but is used
internally by the JVM to identify each object uniquely.
• Example: pen is an object name is Reynolds color is white etc.,
known as state. Used for writing is its behavior.
• Object is instance of the class. Class is a template or blueprint
from which objects are created.

32
Class

• What is a class?
• A class is a group of objects that has common properties. It is a
template or blueprint from which objects are created..
• A class in java can contain:
– data member
– method
– constructor
– block
– class and interface
• Syntax to declare a class:
class <class_name>
{
data member;
method;
}
33
Class Example
Syntax of class:
public class MyPoint
class classname {
{ int x = 0;
type instance-variable1; int y = 0;
type instance-variable2;
//.... void displayPoint()
type instance-variableN; {
System.out.println("Printing the coordinates");
type methodname1(parameter-list) System.out.println(x + " " + y);
{
}
// body of method
}
public static void main(String args[])
type methodname2(parameter-list) {
{ MyPoint obj; // declaration
// body of method obj = new MyPoint(); // allocation of memory
} to an object
// ... obj.x=10; //access data member using object.
type methodnameN(parameter-list) obj.y=20;
{ obj.displayPoint(); // calling a member method
// body of method }
} }
}

34
Class Example
class Students
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
public static void main(String args[])
{
Students s1=new Students();
Students s2=new Students();
s1.insertRecord(111,"Raaki"); What are the different ways to create
s2.insertRecord(222,"Aryan"); an object in java?
s1.displayInformation(); new keyword
s2.displayInformation();
newInstance() method
}
} clone() method
Factory Method 35
Anonymous object
• Anonymous means nameless. An object that have no reference is known
as anonymous object. If you want to use the object only once, anonymous
object is a good approach.
class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factorial is"+fact);
}
public static void main(String args[])
{
new Calculation().fact(5);
}
}
36
Method Overloading

• Class have multiple methods by same name but different


parameter, it is know as Method Overloading.
• Advantage of method overloading
– It increases the readability of the program.
• Different ways to overload the method:
– By Changing number of arguments
– By changing the data type

37
Method Overloading
Changing Number of Arguments
class Calculation1
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation1 obj=new Calculation1();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
38
Method Overloading
Changing data type of argument
class Calculation2
{
void sum(int a, int b) Can we overload the method by
{ changing the return type?
System.out.println(a+b);
} Ans.: We cannot overload the
void sum(double a, double b) method by changing the return
{ type , because ambiguity may
System.out.println(a+b); occur.
}
public static void main(String args[])
{
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
39
Constructor
• Constructor in java is a special type of method that is used to
initialize the object.
• Java constructor is invoked at the time of object creation. It
constructs the values i.e. provides data for the object that is why it is
known as constructor.
• Rules for creating java constructor
– There are basically two rules defined for the constructor.
– Constructor name must be same as its class name
– Constructor must have no explicit return type

40
Default Constructor
• A constructor that have no parameter is known as default constructor.
• Purpose:
– Default constructor provides the default values to the object like 0, null etc. depending on the

type .
Syntax of default constructor: <class_name>(){}

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

41
Non-Parameterized Constructor
class Point1
{
int x;
int y;
Point1() //constructor of class
{
x = 10;
y = 20;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
System.out.println("\t\t\t" + x + " " + y);
}
}
class pointDemo
{
public static void main(String args[])
{
Point1 p1 = new Point1(); // constructor will be call automatically from here
p1.display();
}
}
42
Parameterized Constructor
import java.util.Scanner;
class Point2
{
int x;
int y;
Point2(int a, int b)
{
x = a;
y = b;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
System.out.println("\t\t\t" + x + " " + y);
}
}

43
Parameterized Constructor

class pointDemo1
{
public static void main(String args[])
{
int i,k;
Scanner s = new Scanner(System.in);
System.out.print("Enter int value for i : ");
i = s.nextInt();
System.out.print("Enter int value for k : ");
k = s.nextInt();
Point2 p1 = new Point2(i,k);
p1.display();
}
}

44
Constructor Overloading
• Constructor overloading is a technique in Java in which a class can
have any number of constructors that differ in parameter lists.
class Student5{
int id;
String name;
int age;
public static void main(String args[]){
Student5(int i,String n){ Student5 s1 = new Student5(111,"Kara
id = i; n");
name = n; Student5 s2 = new Student5(222,"Arya
} n",25);
Student5(int i,String n,int a){ s1.display();
id = i; s2.display();
name = n; }
age=a;
}
}
void display(){System.out.println(id+" "+nam
e+" "+age);}

45
Copy Constructor
• There is no copy constructor in java. But, we can copy the values of one
object to another like copy constructor in C++.
• There are many ways to copy the values of one object into another in java.
They are:
– By constructor
– By assigning the values of one object into another
– By clone() method of Object class

class Student6{
int id; public static void main(String args[]){
String name;
Student6(int i,String n){
Student6 s1 = new Student6(111,"Karan")
id = i; ;
name = n;
}
Student6 s2 = new Student6(s1);
s1.display();
Student6(Student6 s){ s2.display();
id = s.id;
name =s.name; }
} }
void display(){System.out.println(id+" "+name);}

46
Constructor Vs Method

47
Interview Questions

• What is constructor?
– Constructor is just like a method that is used to initialize the state of an object. It is
invoked at the time of object creation.

• What is the purpose of default constructor?


– The default constructor provides the default values to the objects. The
java compiler creates a default constructor only if there is no constructor in
the class.

• Does constructor return any value?


– yes, that is current instance (You cannot use return type yet it returns a value).

• Is constructor inherited?
– No, constructor is not inherited.

48

You might also like