Lecture 04 08 Java Class
Lecture 04 08 Java Class
R. S. Yadav
Some Salient Characteristics of Java
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
● 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
8
Scanner Class in Java
Method Description
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();
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
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
18
Operators Precedence
class Precedence {
public static void main(String[] args) {
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
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
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
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
+ "\nAge=" + age); }
}//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. By reference variable
2. By method
3. By constructor
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
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 ?
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?
• 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
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
43
Methods of StringBuffer class
capacity() the total allocated capacity can be found by the capacity( ) method
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.
49
Example: continue
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 :
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:
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
61
Thank You
?
62