0% found this document useful (0 votes)
13 views35 pages

Fundamentals of Programming in Java

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
13 views35 pages

Fundamentals of Programming in Java

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 35

CSE310: Programming in Java

Fundamentals of Programming in Java


Object-Oriented Programming
Two Paradigms-
• All computer programs consist of two elements:
code and data.
1. Process Oriented programming(POP)-
code acting on data- Basic, C, COBOL
2. Object Oriented Programming(OOP’s)-
data controlling access to code.- C++, Java, C#.
The Three OOP Principles

All object-oriented programming languages


provide mechanisms that help you implement
the object-oriented model.
They are :
1.Encapsulation
2.Inheritance
3.Polymorphism
Encapsulation
Encapsulation is the mechanism that binds together code
and the data it manipulates, and keeps both safe from
outside interference and misuse.
A class defines the structure and behavior (data and code)
that will be shared by a set of objects.
Each object of a given class contains the structure and
behavior defined by the class.
objects are sometimes referred to as instances of a class.
Thus, a class is a logical construct; an object has physical
reality.
Data- defined by the class are referred to as
member variables or instance variables.
Code - that operates on that data is referred to as
member methods or just methods.
Inheritance is the process by which one object
acquires the properties of another object.
Polymorphism (from Greek, meaning “many
forms”) is a feature that allows one interface to
be used for a general class of actions.
Naming Conventions
All the letters of an identifier in Java should be in lower case
Except:

Class Names: First letter of each word in the identifier should be


capitalized.

Method Names: First letter of each word in the identifier should be


capitalized except the first word.
Identifiers
A name in a program is called an identifier.

Identifiers can be used to denote classes, methods, variables,


and labels.

An identifier may be any descriptive sequence of uppercase


and lowercase letters, numbers, or the underscore and
dollar-sign characters.
Example: number, Number, sum_$, bingo, $$_100

Note: Identifiers must not begin with a number.


Keywords
Keywords are reserved identifiers that are predefined in the
language.

Cannot be used as names for a variable, class, or method.

All the keywords are in lowercase.

There are 50 keywords currently defined in the Java language.

The keywords const and goto are reserved but not used.

true, false, and null are also reserved.


Java Keywords
abstract char else goto long return throw

assert class enum if native short throws

boolean const extends implements new static this

break continue final import package strictfp transient

byte default finally instanceof private super void

case do float int protected switch try

catch double for interface public synchronize while and


d volatile
Writing Your First Java Program

• class MyJavaProgram
• {
• public static void main(String args[])
{
System.out.println(“Have fun in Java…”);
}
• }
• Understanding first java program
• Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
• class keyword is used to declare a class in java.
• public keyword is an access modifier which represents visibility, it means
it is visible to all.
• static is a keyword, if we declare any method as static, it is known as
static method. The core advantage of static method is that there is no need
to create object to invoke the static method. The main method is executed
by the JVM, so it doesn't require to create object to invoke the main
method. So it saves memory.
• void is the return type of the method, it means it doesn't return any value.
• main represents startup of the program.
• String[] args is used for command line argument.
• System.out.println() is used print statement.

• System.out.println is a Java statement that prints the argument passed, into
the System.out which is generally stdout.
• System is a Class
• out is a Static Member Field
• println() is a method
• System is a class in the java.lang package . The out is a static member of the System
class, and is an instance of java.io.PrintStream . The println is a method of
java.io.PrintStream. This method is overloaded to print message to output destination,
which is typically a console or file.
• class System {
• public static final PrintStream out;
• //...
• }
the System class belongs to java.lang package

class PrintStream{
public void println();
//...
}
the Prinstream class belongs to java.io package
Compiling and Executing Java Program
Step-1: Save your file with .java extension.
• Example: Program1.java

NOTE: If the class is public then the file name MUST BE same as
the name of the class.

Step-2: Compile your .Java file using javac compiler from the
location where the file is saved.

javac Program1.java
Compiling and Executing Java Program

Step-3: Execute your java class which contains the following


method: public static void main(String args[]) {}

java MyJavaProgram
Access Specifiers
Specifier Sub class Non-Sub class Sub class Non-Sub class
(Same (Same (Different (Different
Package) Package) Package) Package)

public Yes Yes Yes Yes

protected Yes Yes Yes No

default Yes Yes No No

private No No No No
Important Points
 A user defined outer class can be either public or default. We
can not define a private or protected class.

 One file can have multiple classes/interfaces but out of them


only one can be public.
Objects
Object is an instance of a class. Class is a
template or blueprint from which objects are
created. So object is the instance(result) of a class.
• Object is a real world entity.
• Object is a run time entity.
• Object is an entity which has state and behavior.
• Object is an instance of a class.
Class
• Class in Java
• A class is a group of objects which have common
properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be
physical.
• A class in Java can contain:
• fields
• methods
• constructors
• blocks
• nested class and interface
NEW
• new keyword in Java
• The new keyword is used to allocate memory at
run time. All objects get memory in Heap memory
area.
Object and Class Example: main within class

1.class Student{  
2.  int id;//field or data member or instance variable  
3.  String name;  
4.   
5.  public static void main(String args[]){  
6.   Student s1=new Student();//creating reference
to object of Student  
7.   System.out.println(s1.id);//
accessing member through reference variable  
8.   System.out.println(s1.name);  
9.  }  
10.}  
Object and Class Example: main outside class

1.class Student{  
2.  int id;  
3.  String name;  
4. }  
5.class TestStudent1{  
6.  public static void main(String args[]){  
7.   Student s1=new Student();  
8.   System.out.println(s1.id);  
9.   System.out.println(s1.name);  
10. }  
11.}  
Initialize object
• 3 Ways to initialize object
• There are 3 ways to initialize object in java.
1. By reference variable
2. By method
3. By constructor
1) Initialization through reference

• Initializing object simply means storing


data into object. Let's see a simple example
where we are going to initialize object
through reference variable.
1. class Student{  
2.  int id;  
3.  String name;  
4. }  
5. class TestStudent2{  
6.  public static void main(String args[]){  
7.   Student s1=new Student();  
8.   s1.id=101;  
9.   s1.name="Sonoo";  
10.  System.out.println(s1.id+" "+s1.name);//
printing members with a white space  
11. }  
12.}  
Initialization through method

• In this example, we are creating the two


objects of Student class and initializing the
value to these objects by invoking the
insertRecord method. Here, we are
displaying the state (data) of the objects by
invoking the displayInformation() 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.  }  }   
Initialization through constructor

• In this example, we are creating the two


objects of Student class and initializing the
value to these objects by invoking the
insertRecord method. Here, we are
displaying the state (data) of the objects by
invoking the displayInformation() method.
1.class Box {
2.double width; double height; double depth;
3.// This is the constructor for
4.Box. Box()
5.{ System.out.println("Constructing Box");
6.width = 10; height = 10; depth = 10; }
7.// compute and return volume
8.double volume() { return width * height * depth; }
9.}
10.class BoxDemo6 { public static void main(String args[]) {
11.// declare, allocate, and initialize Box objects
12. Box mybox1 = new Box(); Box mybox2 = new Box();
13.double vol;
14.// get volume of first box
15. vol = mybox1.volume(); System.out.println("Volume is " + vol);
16.// get volume of second box
17.vol = mybox2.volume(); System.out.println("Volume is " + vol);
18.}
19.} 
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, though
not very efficient if you want an input method
for scenarios where time is a constraint like in
competitive programming.
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.

You might also like