0% found this document useful (0 votes)
0 views62 pages

Lecture 04 08 Java Class

The document provides an introduction to Java, highlighting its platform independence, object-oriented structure, and the ability to embed in web pages. It covers compiling and executing Java programs, the use of classes and objects, and the Scanner class for input handling. Additionally, it discusses data types, operators, instance variables, and access modifiers, along with examples of object initialization and variable scope.

Uploaded by

neeltrial1
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)
0 views62 pages

Lecture 04 08 Java Class

The document provides an introduction to Java, highlighting its platform independence, object-oriented structure, and the ability to embed in web pages. It covers compiling and executing Java programs, the use of classes and objects, and the Scanner class for input handling. Additionally, it discusses data types, operators, instance variables, and access modifiers, along with examples of object initialization and variable scope.

Uploaded by

neeltrial1
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/ 62

Introduction to Java

R. S. Yadav
Some Salient Characteristics of Java

• Java is platform independent: the same program can


run on any correctly implemented Java system
• Java is object-oriented:
• Structured in terms of classes, which group data with
operations on that data
• Can construct new classes by extending existing ones
• Java designed as
• A core language plus
• A rich collection of commonly available packages
• Java can be embedded in Web pages

2
Compiling and Executing a Java Program

3
Processing and Running HelloWorld

• javac HelloWorld.java
• Produces HelloWorld.class (byte code)
• java HelloWorld
• Starts the JVM and runs the main method

4
Classes and Objects
• The class is the unit of programming
• A Java program is a collection of classes
• Each class definition (usually) in its own .java file
• The file name must match the class name
• A class describes objects (instances)
• Describes their common characteristics: is a blueprint
• Thus, all the instances have these same
characteristics
• These characteristics are:
• Data fields for each object
• Methods (operations) that do work on the objects

5
A Little Example of import and main

import java.util.Scanner; // all classes


of scanner
public class HelloWorld { // starts a
class
public static void main (String[] args) {
// starts a main method
// in: array of String; out: none (void)
}
}
• public = can be seen from any package
• static = not “part of” an object
6
Scanner class
Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc.
and strings. It is the easiest way to read input in a Java program.

● To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream. We may pass an object of class File if we want to read input
from a file.
● To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example,
to read a value of type short, we can use nextShort()
● To read strings, we use nextLine().
● To read a single character, we use next().charAt(0). next() function returns the next token/word in the
input as a string and charAt(0) function returns the first character in that string.
● The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that
have some meaning to the Java compiler. For example, Suppose there is an input string: How are you
In this case, the scanner object will read the entire line and divides the string into tokens: “How”,
“are” and “you”. The object then iterates over each token and reads each token using its different
methods. 7
Scanner Class in Java

Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

8
Scanner Class in Java

Method Description

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

9
Class example
import java.util.Scanner;
public class student {
public static void main(String[] args) {
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);
// String input
System.out.println("Please enter your Name");
String name = sc.nextLine();
// Character input
System.out.println("Please enter your Gender");
char gender = sc.next().charAt(0);
// Numerical data input
// byte, short and float can be read
// using similar-named functions.
System.out.println("Please enter your age");
int age = sc.nextInt();
System.out.println("Please enter your mobile number");
10
long mobileNo = sc.nextLong();
Class example
System.out.println("Please enter your CGPA");
double cgpa = sc.nextDouble();

// Print the values to check if the input was correctly obtained.


System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Age: "+age);
System.out.println("Mobile Number: "+mobileNo);
System.out.println("CGPA: "+cgpa);
sc.close();
}//Main
}//class student

Q.No.1. You are required to display your personal record that includes Name, father’s
name, address, date of birth, etc. Write down the program that uses Scanner class to
take input from user. further, compute your age as on today.

11
Data Types
•Java distinguishes two kinds of entities
• Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
•Non-primitive Data Types
• In java, non-primitive data types are the reference data types or user-created data
types. All non-primitive data types are implemented using object concepts. Every
variable of the non-primitive data type is an object. The non-primitive data types
may use additional methods to perform certain operations. The default value of non-
primitive data type variable is null.
• In java, examples of non-primitive data types are String, Array, List, Queue, Stack,
Class, Interface, etc.

12
13
Primitive Data Types

Data type Range of values

byte -128 .. 127 (8 bits)


short -32,768 .. 32,767 (16 bits)
int -2,147,483,648 .. 2,147,483,647 (32 bits)
long -9,223,372,036,854,775,808 .. ... (64 bits)
float +/-10-38 to +/-10+38 and 0, about 6 digits precision
double +/-10-308 to +/-10+308 and 0, about 15 digits precision
char Unicode characters (generally 16 bits per char)
boolean True or false

14
datatype size
• class SizePrimitiveTypes {
• public static void main(String[] args) {
• System.out.println("Size of byte: " + (Byte.SIZE/8) + " bytes.");
System.out.println("Size of short: " + (Short.SIZE/8) + " bytes.");
System.out.println("Size of int: " + (Integer.SIZE/8) + " bytes.");
System.out.println("Size of long: " + (Long.SIZE/8) + " bytes.");
System.out.println("Size of char: " + (Character.SIZE/8) + " bytes.");
System.out.println("Size of float: " + (Float.SIZE/8) + " bytes.");
System.out.println("Size of double: " + (Double.SIZE/8) + " bytes.");
• } }
• OUTPUT ======
• D:\JavaPrograms>javac SizePrimitiveTypes.java
• D:\JavaPrograms>java SizePrimitiveTypes
• Size of byte: 1 bytes.
• Size of short: 2 bytes.
• Size of int: 4 bytes.
• Size of long: 8 bytes.
• Size of char: 2 bytes.
• Size of float: 4 bytes.
• Size of double: 8 bytes. 15
Operators Precedence

16
Operators Precedence

Associativity of Operators in Java

If an expression has two operators with similar precedence, the expression is


evaluated according to its associativity (either left to right, or right to left). 17
Operators Precedence

18
Operators Precedence
class Precedence {
public static void main(String[] args) {

int a = 10, b = 5, c = 1, result;


result = a-++c-++b;

System.out.println(result);
}
}
The operator precedence of prefix ++ is higher than that of - subtraction operator. Hence,

result = a-++c-++b;

is equivalent to

result = a-(++c)-(++b);

Output: 2
19
Data Type Compatibility and Conversion

Widening or Automatic Type Conversion


Widening conversion takes place when two data types are automatically converted.
This happens when:

● The two data types are compatible.


● When we assign a value of a smaller data type to a bigger data type.

For Example, in java, the numeric data types are compatible with each other but no
automatic conversion is supported from numeric type to char or boolean. Also, char
and boolean are not compatible with each other.

20
Data Type Compatibility and Conversion

• Widening conversion:
• In operations on mixed-type operands, the numeric
type of the smaller range is converted to the numeric
type of the larger range
• In an assignment, a numeric type of smaller range
can be assigned to a numeric type of larger range
• byte to short to int to long
• Long to float to double
• Its also called auto promotion.

21
Data Type Compatibility and Conversion

22
Data Type Compatibility and Conversion

23
Data Type Compatibility and Conversion
• Narrowing
• Converting a value of larger range to value of smaller
range.
• Example: int i; byte b; b=i; //invalid
• b= (byte)i; //valid
• For type conversion and casting the Assignment
Operator is used between the two values.
• General form: var = exp
• Example: int i=10;
long m=10000L;
double d=Math.PI;//PI=3.1415….
i=(int)m;//cast
m=i;//widening
m=(long)d;//cast
d=m;widening
24
Instance Variables

• An instance variable declaration consists of the following parts:


• access specifier (private)
• type of variable (such as int)
• name of variable (such as value)
• Each object of a class has its own set of instance variables
• You should declare all instance variables as private
Variables

Static Variables: When a variable is declared as static, then a single copy of the variable is
created and shared among all objects at a class level. Static variables are, essentially, global
variables. All instances of the class share the same static variable.

Non-Static Variable

● Local Variables: A variable defined within a block or method or constructor is called


local variable.
○ These variable are created when the block in entered or the function is called
and destroyed after exiting from the block or when the call returns from the
function.
○ The scope of these variables exists only within the block in which the variable
is declared. That is, we can access these variable only within that block.
○ Initialisation of Local Variable is Mandatory.
Instance Variables
1. Instance Variables: Instance variables are non-static variables and are declared in a
class outside any method, constructor or block.
a. As instance variables are declared in a class, these variables are created when
an object of the class is created and destroyed when the object is destroyed.
b. Unlike local variables, we may use access specifiers for instance variables. If we
do not specify any access specifier then the default access specifier will be used.
c. Initialisation of Instance Variable is not Mandatory. Its default value is 0
d. Instance Variable can be accessed only by creating objects.

Limitations of Instance Variable

2. It cannot be declared static, abstract, striftp, synchronized, and native.


3. It can be declared final and transient.
4. It can be of any of the four access modifiers available in Java (private, public,
protected, and default).
Local Variables

• A method’s parameters are local to the block of the


method’s body.
• public void aMethod(int A){...};
• If new variables are declared in the initialization of a for
loop, they are local to the loop body.
• for (int i = 0; i < N; i++);
• i’s scope is just the body of the loop.
Hiding fields

• If a local variable is declared with the same name as an


in scope field, that field is “hidden” or “shadowed”.
• class MyClass {
int A; // field
public void someMethod() {
String A;// Local variable
}
Class Example

// Java Program to count number of employees working in a company

class Employee {

private int ID; private String name; private int age; private static int nextId = 1;

// it is made static because it is keep common among all and shared by all objects

public Employee(String name, int age) {

this.name = name; this.age = age; this.ID = nextId++; }

public void show() { System.out.println("Id=" + ID + "\nName=" + name

+ "\nAge=" + age); }

public void showNextId() {

System.out.println("Next employee id will be=" + nextId); }


Class Example
class UseEmployee {

public static void main(String[] args) {

Employee E = new Employee("GFG1", 56);

Employee F = new Employee("GFG2", 45);

Employee G = new Employee("GFG3", 25);

E.show(); F.show(); G.show();

E.showNextId(); F.showNextId(); G.showNextId();

}//main

}//Use Employee
Instance Variables
Access modifier in java

As the name suggests access modifiers in Java helps to restrict the scope of a class,
constructor, variable, method, or data member. There are four types of access modifiers
available in java:

1. Default – No keyword required


2. Private
3. Protected
4. Public
Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

Object and Class Example: Initialization through reference


4. class Student{
5. int id;
6. String name;
7. }
8. class TestStudent2{
9. public static void main(String args[]){
10. Student s1=new Student();
11. s1.id=101;
12. s1.name="Sonoo";
13. System.out.println(s1.id+" "+s1.name);//printing members with a white space
14. }
15. }
34
Object and Class Example: Initialization through method

1. class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9. }
10. class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation();
18. }
19. } 35
Object and Class Example: Initialization through a constructor

1. class Employee{
2. int id;
3. String name;
4. float salary;
5. void Employee(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){System.out.println(id+" "+name+" "+salary);}
11. }
12. public class TestEmployee {
13. public static void main(String[] args) {
14. Employee e1=new Employee(101,"ajeet",45000);
15. Employee e2=new Employee(102,"irfan",25000);
16. Employee e3=new Employee(103,"nakul",55000);
17. e1.display();
18. e2.display();
19. e3.display(); } } 36
Static and Non-static

• We can access static variables without creating an


instance of the class
• As they are already available at class loading time, we
can use them in any of our static methods.
• We cannot use non static methods and variables without
creating an instance of the class as they are bound to
the instance of the class.
• They are initialized by the constructor when we create
the object using new operator.
Instance Variables: Static Vs Non-static

Static variable Non static variable

Static variables can be accessed Non static variables can be accessed using
using class name instance of a class

Static variables can be accessed by Non static variables cannot be accessed inside a
static and non static methods static method.

Static variables reduce the amount Non static variables do not reduce the amount of
of memory used by a program. memory used by a program

Static variables are shared among Non static variables are specific to that instance
all instances of a class. of a class.

Static variable is like a global Non static variable is like a local variable and
variable and is available to all they can be accessed through only instance of a
methods. class.
Why do we need static variable ?

• Static methods are identified to be mostly used when we


are writing any utility methods.
• We can also use static variables when sharing data.
• When sharing data do keep in mind about multithreading
can cause inconsistency in the value. (synchronize the
variable)
Methods
• There are two type of method in java : instance and static method.
• Method are define inside the class.
• Instance method(s) belong to the Object of the class, not to the class i.e. they can be
called after creating the Object of the class.
• Instance methods are not stored on a per-instance basis, even with virtual methods.
They’re stored in a single memory location, and they only “know” which object they
belong to because this pointer is passed when you call them.
• They can be overridden since they are resolved using dynamic binding at run time.
• Static methods are the methods in Java that can be called without creating an object
of class. They are referenced by the class name itself or reference to the Object of
that class.

40
Example: accessing static methods/variables
Class staticDemo{
public static int a = 100; // All instances of staticDemo have this variable as a common `
variable
public int b =2 ;
public static showA(){
System.out.println(“A is “+a);
}
}
Class execClass{
public static void main(String args[]){
staticDemo.a = 35; // when we use the class name, the class is loaded, direct
access to a without any instance
staticDemo.b=22; // ERROR this is not valid for non static variable
staticDemo demo = new staticDemo();
demo.b = 200; // valid to set a value for a non static variable after creating an
instance.
staticDemo.showA(); //prints 35
}
}
How static variable works?

Basic Steps of how objects are created


1. Class is loaded by JVM
2. Static variable and methods are loaded and initialized
and available for use
3. Constructor is called to instantiate the non static
variables
4. Non static variables and methods are now available

• As all the non static variable are available only after the
constructor is called, there is a restriction on using non
static variable in static methods.
StringBuffer class in Java
StringBuffer is a peer class of String that provides much of the functionality of strings. The

string represents fixed-length, immutable character sequences while StringBuffer represents

growable and writable character sequences. StringBuffer may have characters and substrings

inserted in the middle or appended to the end. It will automatically grow to make room for

such additions and often has more characters preallocated than are actually needed, to allow

room for growth.


Constructors of StringBuffer class
1. StringBuffer(): It reserves room for 16 characters without reallocation
StringBuffer s = new StringBuffer();
2. StringBuffer( int size): It accepts an integer argument that explicitly sets the size of the buffer.
StringBuffer s = new StringBuffer(20);
3. StringBuffer(String str): It accepts a string argument that sets the initial contents of the StringBuffer
object and reserves room for 16 more characters without reallocation.
StringBuffer s = new StringBuffer("GeeksforGeeks");

43
Methods of StringBuffer class

Methods Action Performed

append() Used to add text at the end of the existing text.

length() The length of a StringBuffer can be found by the length( ) method

capacity() the total allocated capacity can be found by the capacity( ) method

deleteCharAt() Deletes the character at the index specified by loc

ensureCapacity() Ensures capacity is at least equals to the given minimum.

insert() Inserts text at the specified index position

length() Returns length of the string

reverse() Reverse the characters within a StringBuffer object

Replace one set of characters with another set inside a StringBuffer


replace()
object
44
Methods of StringBuffer class

StringBuffer Class append() Method


1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

StringBuffer capacity() Method


The capacity() method of the StringBuffer class returns the current capacity of the buffer. The default capacity
of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2. StringBufferExample6.java

1. class StringBufferExample6{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 45
9. } }
Decision Making:if, if-else, switch, break, continue, jump

1. if: if statement is used to decide whether a certain statement or block of statements will be
executed or not.
Syntax:
if(condition) {
// Statements to execute if condition is true}
2. if-else: The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it execute another block of statement.
Syntax:
if (condition){ // Executes this block if condition is true}
else{ // Executes this block if condition is false}
Time complexity O(1).
Q. No. You are given your mark obtained in subject OOPS. Write the java class that uses if-
else control statement to the compute grade corresponding to your mark and display it.
46
Decision Making:if, if-else, switch, break, continue, jump
3. nested-if: if statement inside an if statement.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true }}

4. if-else-if ladder: The statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
47
Decision Making:if, if-else, switch, break, continue, jump
5. switch-case:The switch statement is a easy way of multiway branch statement. It provides
an easy way to dispatch execution to different parts of code based on the value of the
expression.
Syntax:
switch (expression){
case value1: statement1; break;
case value2: statement2; break;
.
.
case valueN: statementN; break;
default: statementDefault;}

Q. No. You are given your Grade in subject OOPS. Write the java class that uses if-else
control statement to the display score corresponding to your grade. Also, write the java
program that uses switch statement in place of if-else control statement.

48
Decision Making:if, if-else, switch, break, continue, jump

6. jump: Java supports three jump statements: break, continue and return. These three
statements transfer control to another part of the program.

● Break: In Java, a break is majorly used for:


○ Terminate a sequence in a switch statement (discussed above).
○ To exit a loop.
○ Used as a “civilized” form of goto.
● Continue: Sometimes it is useful to force an early iteration of a loop. That is, you
might want to continue running the loop but stop processing the remainder of the
code in its body for this particular iteration. This is, in effect, a goto just past the
body of the loop, to the loop’s end. The continue statement performs such an
action.

49
Example: continue

// Java program to illustrate using


// continue in an if statement
class ContinueDemo {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is even
// skip and continue
if (i % 2 == 0)
continue;

// If number is odd, print it


System.out.print(i + " ");
}
}
}Output: 1 3 5 7 9

50
Loops in Java
● while loop: A while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as a
repeating if statement.
● Syntax :

while (boolean condition){


loop statements...}
● for loop: for loop provides a concise way of writing the loop structure. Unlike a while
loop, a for statement consumes the initialization, condition and increment/decrement in
one line thereby providing a shorter, easy to debug structure of looping.

Syntax:
for (initialization condition; testing condition; increment/decrement){ statement(s)}

51
Loops in Java
● do while: do while loop checks for condition after executing the statements, and
therefore is an example of Exit Control Loop.
● syntax:

do{ statements..}while (condition);

52
Digital lock
Q. No. 1.You are required to model simple digital lock with integer digit
combination of three security keys. The combination is set into unlock when it is
created security keys. To open the lock user must give correct combination
given in term of single digit at a time. The lock explicitly remember last three
.digits entered

Q. No. 2.You are required to model simple digital lock with integer digit
combination of three security keys. The combination is set into unlock when it is
created security keys. To open the lock user must give correct combination
given in term of single digit at a time. The lock instead of remembering last
three digits entered to make the lock open. The lock remembers if last digit
.entered was first security key and if last two digits were first two security keys
Digital lock )Solution 1(
Program to implement digital lock security where system explicitly remember */
/*last three digit entered
;import java.util.Scanner
{class Lock
;int FirstSecurityKey, SecondSecurityKey, ThirdSecurityKey
;int FirstEnteredKey, SecondEnteredKey,ThirdEnteredKey
;boolean Open
constructor //
{public Lock(int Digit)
;ThirdSecurityKey= Digit%10
;Digit=Digit/10
;SecondSecurityKey=Digit%10
;Digit=Digit/10
;FirstSecurityKey=Digit%10
;FirstEnteredKey=-1
;SecondEnteredKey=-1
;ThirdEnteredKey=-1
;Open=false
;System.out.println( "security numbers"+FirstSecurityKey+SecondSecurityKey+ThirdSecurityKey) //
construcor //}
Digital lock )Solution 1(
public boolean OpenLock(){ return Open=true;}
{)(public void close
;FirstEnteredKey=-1
;SecondEnteredKey=-1
;ThirdEnteredKey=-1
;Open=false
close//}
{public void InputDigit( int Digit)
;FirstEnteredKey= SecondEnteredKey
;SecondEnteredKey= ThirdEnteredKey
;ThirdEnteredKey=Digit
if((FirstEnteredKey==FirstSecurityKey)&&(SecondEnteredKey==SecondSecurityKey)
))ThirdEnteredKey==ThirdSecurityKey(&&
;Open=true
InputDigit//}
Class Lock//}
Digital lock )Solution 1(
{ public class DigitalLock
;static int Digit
{public static void main( String args[])
;int Digit
;Scanner sc=new Scanner(System.in)
;System.out.println( "Please Enter Security number")
;Lock lc=new Lock( Digit)
;System.out.println( "Status of lock"+lc.Open)
{while (!lc.Open)
;System.out.println( "Please Enter Single Digit Integer")
;)(Digit=sc.nextInt
;lc.InputDigit(Digit)
while//}
/*;System.out.println( "Status of lock"+lc.Open)
)(main//}

Class DigitalLock//}
Digital lock )Solution 2(
Program to implement digital lock security where system explicitely remember */
last three digit entered on occurrence of following conditions
Last digit entered is first combination digit .1
/*Last two digit entered were first two digit combination .2
{class LockStatus
;int FirstSecurityKey, SecondSecurityKey, ThirdSecurityKey
;boolean HaveFirst, HaveSecond,HaveThird, Open
constructor //
{public LockStatus(int Digit)
;ThirdSecurityKey= Digit%10
;Digit=Digit/10
;SecondSecurityKey=Digit%10
;Digit=Digit/10
;FirstSecurityKey=Digit%10
;HaveFirst=false; HaveSecond=false;HaveThird=false
;Open=false
;System.out.println( "security numbers"+FirstSecurityKey+SecondSecurityKey+ThirdSecurityKey) //
construcor //}
public boolean OpenLock(){ return Open=true;}
{)(public void close
;HaveFirst=false; HaveSecond=false;HaveThird=false
;Open=false
close//}
Digital lock )Solution 2(
{public void InputDigit( int Digit)
{if (HaveFirst&&HaveSecond)
;if(Digit==ThirdSecurityKey) Open=true
{else if(!(SecondSecurityKey==Digit))
;if(FirstSecurityKey==Digit)HaveSecond=false
{else
;HaveSecond=false; HaveFirst=false
}
else if(!(SecondSecurityKey==Digit)) //}
else{HaveSecond=false; HaveFirst=false;}//else if(!(SecondSecurityKey==Digit))
if (HaveFirst&&HaveSecond)//}
{else if(HaveFirst)
;if(SecondSecurityKey==Digit)HaveSecond=true
;else if(FirstSecurityKey==Digit)HaveFirst=true
else if(HaveFirst)//}
;else if(FirstSecurityKey==Digit)HaveFirst=true
InputDigit//}
Class Lock//}
Digital lock )Solution 2(
{ public class DigitalLock
;static int Digit
{public static void main( String args[])
;int Digit//
;Scanner sc=new Scanner(System.in)
;System.out.println( "Please Enter Security number")
;)(Digit=sc.nextInt
;LockStatus ls=new LockStatus(Digit)
;System.out.println( "Status of lock"+ls.Open)
{while (!ls.Open)
;System.out.println( "Please Enter Single Digit Integer")
;)(Digit=sc.nextInt
;ls.InputDigit(Digit)
while//}
;System.out.println( "Status of lock"+ls.Open)
)(main//}

Class DigitalLock//}
References

• Material available at following url :-


• https://www.google.com/search?ei=-fNiW_aeMIvwvgTir4ioDA&q=instance+method&o
q=insta&gs_l=psy-ab.1.0.0i67k1j0i131k1j0i67k1l3j0i131k1j0i67k1l4.6081.7454.0.102
45.5.5.0.0.0.0.184.785.0j5.5.0....0...1.1.64.psy-ab..0.5.783...0.0.1z0m7TjkWLU
• https://stackoverflow.com/questions/6766343/best-practice-for-getting-datatype-sizesi
zeof-in-java
• https://www.javatpoint.com/q/3783/what-is-instance-methods-in-java?

61
Thank You
?

62

You might also like