0% found this document useful (0 votes)
9 views40 pages

Unit 1 Introduction Java SEP

This document provides an introduction to Java, covering the differences between Procedure Oriented Programming (POP) and Object Oriented Programming (OOP), as well as key concepts such as classes, objects, and methods. It outlines the history of Java, its features, and the components of the Java Development Kit (JDK) and Java Runtime Environment (JRE). Additionally, it includes examples of class and object declarations in Java, emphasizing the language's object-oriented nature and its platform independence.

Uploaded by

IT Support
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views40 pages

Unit 1 Introduction Java SEP

This document provides an introduction to Java, covering the differences between Procedure Oriented Programming (POP) and Object Oriented Programming (OOP), as well as key concepts such as classes, objects, and methods. It outlines the history of Java, its features, and the components of the Java Development Kit (JDK) and Java Runtime Environment (JRE). Additionally, it includes examples of class and object declarations in Java, emphasizing the language's object-oriented nature and its platform independence.

Uploaded by

IT Support
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

UNIT-1

Introduction to JAVA

Procedure Oriented Programming (POP):


“POP is a programming paradigm(approach), here bigger problems are broken down into small
solvable problems are converted into procedures/functions/methods”.
POP programs emphasize functions rather than data, that’s why, this approach donot ensure security
to data.
In order to overcome, above problem OOP approach is introduced.

Features of POP’s:
 More focus is on doing things than the data.
 Programs are divided into smaller entities known as functions.
 Most of the functions share global data.
 Functions transform data from one form to another.
 It follows top-down design in program design.
Object Oriented Programming (OOP):
“OOP is a programming paradigm(approach) that represents concepts as ‘objects’ that have data fields
and associated procedures known as methods”.

In OOP, everything is represented as an object, which means the program is divided into
number of small units called object and the data and functions are built around this object.
Functions of one object can access the functions of other objects.
Features of OOP’s:
 More focus is on data rather than functions or procedures.
 Programs are divided into smaller entities known as objects.
 Functions that operate on data of an object are tied together to data structure.
 Objects pass messages (communicate) with each other through functions.
 New data items and functions can be easily added whenever required.
 It follows bottom-up design in program design.
OOPS concepts are as follows:
1. Class
2. Object
3. Method and method passing
4. Pillars of OOPs
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Compile-time polymorphism
 Runtime polymorphism

A class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. Using classes,
you can create multiple objects with the same behavior instead of writing their code multiple
times. This includes classes for objects occurring more than once in your code. In general,
class declarations can include these components in order:
1. Modifiers: A class can be public or have default access (Refer to this for details).
2. Class name: The class name should begin with the initial letter capitalized by
convention.
3. Superclass (if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
5. Body: The class body is surrounded by braces, { }.
An object is a basic unit of Object-Oriented Programming that represents real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking
methods. The objects are what perform your code, they are the part of your code visible to the
viewer/user. An object mainly consists of:
1. State: It is represented by the attributes of an object. It also reflects the properties of
an object.
2. Behaviour: It is represented by the methods of an object. It also reflects the response
of an object to other objects.
3. Identity: It is a unique name given to an object that enables it to interact with other
objects.
4. Method: A method is a collection of statements that perform some specific task and
return the result to the caller. A method can perform some specific task without
returning anything. Methods allow us to reuse the code without retyping it, which is
why they are considered time savers. In Java, every method must be part of some
class, which is different from languages like C, C++, and Python.
History of JAVA:
Java is a general-purpose, concurrent, class-based, object-oriented computer programming language
developed by the Sun Microsystems.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The language was initially called Oak after an oak tree that stood outside Gosling's office.
It went by the name Green later, and was later renamed Java, from Java coffee, said to be consumed
in large quantities by the Java language's creators.
Earlier, C++ was widely used to write object-oriented programming languages; however, it was not a
platform independent and needed to be recompiled for each different processor.
Whereas Java applications are typically compiled to byte code (.class file) that can run on any
platform (OS + Processor).
It is intended to let application developers "write once, run anywhere" (WORA), meaning that code
that runs on one platform does not need to be recompiled to run on another.

In 2010, Oracle Corporation took over the JAVA language from Sun Microsystems.
Difference b/w POP & OOP.
Java Development Kit (JDK)
It is a program development environment for developing java applets and applications.
It includes JRE and command line development tools.
When installed on a computer, the JRE provides the operating system with the means to run Java
Programs.
It provides the libraries, the Java Virtual Machine, and other components to run applets and
applications written in the Java programming language.
JDK Components:
JDK includes the following command line development tools
Javac - The compiler for the java programming language. Using this tool we can compile java
programs and generates byte codes.
Java - The interpreter for java applications used to execute the java byte codes.
Javadoc - API documentation generator used to generate documentation for our java programs.
Applet viewer - Used to run and debug applets without a web browser.
Jar - Create and manage java achieve.
Jdb - Java debugger used to debug our java programs to find out any errors.
Javah - C header and stub generator. Used to write native methods.
javap - Java disassemble used to convert byte codes to a program description.
JAVA JDK Versions:
Major release versions of Java, along with their release dates:
JDK 1.0 (January 21, 1996)
JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
J2SE 1.3 (May 8, 2000)
J2SE 1.4 (February 6, 2002)
J2SE 5.0 (September 30, 2004)
Java SE 6 (December 11, 2006)
Java SE 7 (July 28, 2011)
Java SE 8 (March 18, 2014)
-
JDK 22
Java SE 11.0.22 (JAN 16,2024)
JAVA Features/Buzzwords/Characteristics:
Simple
Java Inherits the C/C++ syntax and many of the object-oriented features C++. Many confusing
features like pointers and operator overloading are removed from java. So for the professional
programmers learning java is easy.
Java Is Object-Oriented
Java is a true object-oriented language which supports all the features of OOP like Inheritance,
Encapsulation and Polymorphism. Almost everything is an object in java. All program code and data
reside within classes.
Java Is Distributed
Java is designed for the distributed environment of the internet, because it handles TCP/IP protocols
like HTTP and FTP. Java supports network programming to communicate with remote objects
distributed over the network. Java provides libraries like RMI and CORBA to develop network
applications.
Architectural Neutral
The java Compiler generates byte code, which has nothing to do with particular computer
architecture; hence a Java program is easy to interpret on any machine.
Portable
Java Byte code can be carried to any platform. No implementation dependent features. Everything
related to storage is predefined, example: size of primitive data types.
Robust
Robust simply means strong. Java uses strong memory management. There is automatic garbage
collection in java. There is exception handling and type checking mechanism in java which makes
java robust.
Multithreaded
Java multithreading feature makes it possible to write program that can do many tasks simultaneously.
Benefit of multithreading is that it utilizes same memory and other resources to execute multiple
threads at the same time.
Ex: While typing in MS Word, grammatical errors are checked along.
Platform Independent
Java programs can be run on computer systems with different OS and processor environment. Java
code is compiled by the compiler and converted into byte code. This byte code is a platform
independent code because it can be run on multiple platforms.
Secure
Java security feature enable us to develop virus free applications. Java programs always run in Java
runtime environment with null interaction with system OS that restricts them from introducing virus,
deleting or modifying files in the host computers, hence it is more secure.
Compiled and interpreted language
Java uses a two-step translation process. Java source code is compiled down to "byte code" by the
Java compiler (javac).
Then byte code is converted into machine code by the Java Interpreter (Java Virtual Machine - JVM).

Difference b/w C, C++ & JAVA.

Classes and Objects in Java


In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that
are used to represent real-world concepts and entities. The class represents a group of objects having
similar properties and behavior.
For example, the animal type Dog is a class while a particular dog named Jimmy is an object
of the Dog class.
Java Classes
A class in Java is a set of objects which shares common characteristics and common properties. It is a
user-defined blueprint or prototype from which objects are created. For example, Student is a class
while a particular student named Ravi is an object.

Properties of Java Classes


Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are
created.
Class does not occupy memory.
Class is a group of variables of different data types and a group of methods.
A Class in Java can contain:
 Data member
 Method
 Constructor
 Nested Class
 Interface
Class Declaration syntax in Java:
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}

Components of Java Classes


In general, class declarations can include these components, in order:
Modifiers: A class can be public or has default access.
Class keyword: Class keyword is used to create a class.
Class name: The name should begin with an initial letter (capitalized by convention).
Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded
by the keyword implements. A class can implement more than one interface.
Body: The class body is surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provide the state of the
class and its objects, and methods are used to implement the behavior of the class and its objects.
There are various types of classes that are used in real-time applications such as nested classes,
anonymous classes and lambda expressions.

Example 1: Here, the below Java code demonstrates the basic use of class in Java.
// Java Class example
class Student {

// data member (also instance variable)


int id;

// data member (also instance variable)


String n;

public static void main(String args[]) {

// creating an object of
// Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.n);
}
}

Output
0
null

Objects:
An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities.
Objects are the instances of a class that are created to use the attributes and methods of a class. A
typical Java program creates many objects, which as you know, interact by invoking methods.
An object consists of:
State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object with
other objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.
Example of an object: Dog
Java Objects
Objects correspond to things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, and “menu”. An online shopping system might have objects such
as “shopping cart”, “customer”, and “product”.
Note: When we create an object which is a non primitive data type, it’s always allocated on the heap
memory.
Declaring Objects (Also called instantiating a Class)
When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for
each object. A single class may have any number of instances.
Example:

Declaring Objects in Java


Java Object Declaration

As we declare variables like (type name;). This notifies the compiler that we will use the name to refer
to data whose type is type. With a primitive variable, this declaration also reserves the proper amount
of memory for the variable. So for reference variables, the type must be strictly a concrete class name.
In general, we can’t create objects of an abstract class or an interface.

Dog tuffy;

If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object
is actually created and assigned to it. Simply declaring a reference variable does not create an object.
Initializing a Java Object
The new operator instantiates a class by allocating memory for a new object and returning a reference
to that memory. The new operator also invokes the class constructor.
Example:
// Java Program to Demonstrate the
// use of a class with instance variable

// Class Declaration
public class Dog {

// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed, int age,
String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// method 1
public String getName() {
return name;
}

// method 2
public String getBreed() {
return breed;
}

// method 3
public int getAge() {
return age;
}

// method 4
public String getColor() {
return color;
}

@Override public String toString()


{
return ("Name is: " + this.getName()
+ "\nBreed, age, and color are: "
+ this.getBreed() + "," + this.getAge()
+ "," + this.getColor());
}

public static void main(String[] args)


{
Dog tuffy
= new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy.toString());
}
}

Output
Name is: tuffy
Breed, age, and color are: papillon,5,white
Java Development Kit (JDK):
The Java Development Kit (JDK) is a collection of tools and libraries for developing Java
applications and applets. It includes the Java Runtime Environment (JRE) and Java Virtual
Machine (JVM).
What does the JDK include?
 Compilers: Transforms Java text files into executable programs
 Debuggers: Helps identify and fix errors in Java programs
 Performance monitoring tools: Helps monitor the performance of Java applications
 Utilities: Other tools that help Java programmers

JRE in Java

Java Runtime Environment (JRE) is an open-access software distribution that has a Java class library,
specific tools, and a separate JVM. In Java, JRE is one of the interrelated components in the Java
Development Kit (JDK). It is the most common environment available on devices for running Java
programs. Java source code is compiled and converted to Java bytecode. If you want to run this
bytecode on any platform, you need JRE. The JRE loads classes check memory access and get system
resources. JRE acts as a software layer on top of the operating system.
Components of Java JRE
The components of JRE are mentioned below:
 Integration libraries include Java Database Connectivity (JDBC)
 Java Naming, Interface Definition Language (IDL)
 Directory Interface (JNDI)
 Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP)
 Remote Method Invocation (RMI)
 Scripting
Working of JRE
Java Development Kit (JDK) and Java Runtime Environment (JRE) both interact with each other to
create a sustainable runtime environment that enables Java-based applications to run seamlessly on
any operating system. The JRE runtime architecture consists of the following elements as listed:
1. Class Loader
2. Byte Code verifier
3. Interpreter

How does JRE work with JVM?


Working of JRE
JRE has an object of JVM with it, development tools, and library classes. To understand the working
of Java Runtime Environment let us see an example of a simple Java program that prints “JAVA
DEMO”.
// Java class
class GFG {
// Main driver method
public static void main (String[] args) {
// Print statement
System.out.println("JAVA DEMO ");
}
}

Once you write your Java program, you must save it with a file name with
a “.java” extension. Then after you Compile your program. The output of the Java compiler
is byte code which is a platform-independent code. After compiling, the compiler generates
a .class file that contains the byte code. Bytecode is platform-independent that runs on all
devices which contain Java Runtime Environment (JRE).
Difference between JVM, JRE, and JDK.
 JVM: JVM stands for Java Virtual Machine. JVM is used for running Java bytecode. Java
applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and can expect it to run on any other Java-enabled system
without any adjustment. This is all possible because of JVM.
 JRE: JRE stands for Java Runtime Environment. JRE is made up of class libraries.
 JDK: JDK stands for Java Development Kit. JDK contains the JRE with compiler,
interpreter, debugger, and other tools. It provides features to run as well as develop Java
Programs.
JVM(Java Virtual Machine):
JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that
actually calls the main method present in a Java code. JVM is a part of JRE(Java Runtime
Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and can expect it to run on any other Java-enabled system without
any adjustment. This is all possible because of JVM.
When we compile a .java file, .class files (contains byte-code) with the same class names present
in .java file are generated by the Java compiler. This .class file goes into various steps when we run it.
These steps together describe the whole JVM.

Class Loader Subsystem


It is mainly responsible for three activities.
 Loading
 Linking
 Initialization
JVM Memory
1. Method area: In the method area, all class level information like class name,
immediate parent class name, methods and variables information etc. are stored,
including static variables. There is only one method area per JVM, and it is a shared
resource.
2. Heap area: Information of all objects is stored in the heap area. There is also one
Heap Area per JVM. It is also a shared resource.
3. Stack area: For every thread, JVM creates one run-time stack which is stored here.
Every block of this stack is called activation record/stack frame which stores methods
calls. All local variables of that method are stored in their corresponding frame. After
a thread terminates, its run-time stack will be destroyed by JVM. It is not a shared
resource.
4. PC Registers: Store address of current execution instruction of a thread. Obviously,
each thread has separate PC Registers.
5. Native method stacks: For every thread, a separate native stack is created. It stores
native method information.
Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses
data and information present in various memory area and executes instructions. It can be
classified into three parts:
 Interpreter: It interprets the bytecode line by line and then executes. The
disadvantage here is that when one method is called multiple times, every time
interpretation is required.
 Just-In-Time Compiler (JIT): It is used to increase the efficiency of an interpreter. It
compiles the entire bytecode and changes it to native code so whenever the interpreter
sees repeated method calls, JIT provides direct native code for that part so re-
interpretation is not required, thus efficiency is improved.
 Garbage Collector: It destroys un-referenced objects.

Java Native Interface (JNI):


It is an interface that interacts with the Native Method Libraries and provides the native
libraries (C, C++) required for the execution. It enables JVM to call C/C++ libraries and to be
called by C/C++ libraries which may be specific to hardware.
Native Method Libraries:
It is a collection of the Native Libraries (C, C++) which are required by the Execution
Engine.

Types of Java Programs


Java Programs are classified into two types:

1. Standalone application [Java application]


2. Web applets [Java applets]
Java Program

Standalone Applications Java applets

Standalone applications are programs written in java to perform specific task in a standard
local computer.
Java applets are very small java application developed for internet application, applets can
run only in browsers.

Disadvantages of Java
1. Little slow, an interpreter called JVM must first translate byte code into equivalent
microprocessor instruction so this takes time.
2. Java does not support real time programming.

Structure of Java Program


Documentation section
Package Statement

Import Statement

Interface Statement

Class Statement

main method class


{
main method definition
}

a. Documentation section: A set of comment lines like: name of the program, author
name, date of creation, etc.
b. Package statement: This is the first statement allowed in Java file, this statement
declares a package names.
c. Import statement: This statement imports the packages that the classes and methods
of particular package can be used in the current program.
d. Interface statement: An interface is like a class but includes group of methods
declaration. Inter face is used to implement the multiple inheritance in the program.
e. Class definition/statements: A Java program may contains one more class
definitions.
f. Main method class: Every Java standalone program requires a main method, as it
begins the execution, this is essential part of Java program
Steps to execute a Java program:

 Edit: First write the source code in a text editor,


 Compile: Then compile it using the javac compiler to generate bytecode, this
generates .class file.
 Load: Then load that .class file from disk to main memory.
 Verify: Bytecode verifier verifies the .class file against java security constraints, if it
is according to java rules, then it is passed to next step.
 Execute: Now execute that bytecode through the Java Virtual Machine
(JVM). (Finally run the bytecode using the java command on the compiled class
file; essentially, this involves writing the code, compiling it into machine-independent
bytecode.)

First Java Program


import java.io.*;
public class Welcome
{
public static void main (String args[])
{
System.out.println(“welcome to Java Program”);
}
}
public: It is access specifier and this method can be called from outside also.
static: This main method must always declared as static because the whole program has
only one main method and without using object the main method can be executed by using
the class name.

void: The main method does not return anything.

main: The main method similar to main function in c and c++.This main method call first
(execute first)by the interpreter to run the java program.

String: It is built-in class under language package.

args[]: This is an array of type string. a command line argument holds the argument in this
array.

System.out.println

System:-It is a class which contains several useful methods.


out:-It is an object for a system class to execute the method.
println:-This is a method to print string which can be given within the double coats. After
printed the contents the cursor should be positioned at beginning of next line

print:- after printed the content the cursor should be positioned next to the printed content
To compile and run simple program in JDK editor
 Type the source code in any text editor like notepad
 Save the title name as class name java in the bin folder[welcom.java]
 To compile the source code file Welocome.java
 Open a command prompt and move to the directory
 C:\Program Files\Java\jdk22\bin>
 javac is used to compile the source code
C:\program Files\java\jdk22\bin>java Welcom.java
It successfully compiled with no-errors, Java compiler converts source code [welcome.java] to byte
code [welcome. class] into particular machine instruction to run java program

To execute the Java program outside the bin folder


 Save java file in D drive
 Set the path where bin\folder path
 D:\>set path=c:\program files\java\jdk22\bin or D:, cd c:\program files\java\jdk22\bin
 D:\>javac Welcome.java
 D:>java Welcome
Java Tokens: Tokens are the basic building-blocks of the java language.

Keywords: There are around 60 keywords are reserved words and it can’t be used as
identifiers such as variable name, method name, object names, class name, package name,
etc.

abstract Final Super


boolean Int New
break Finally Package
byte While Private
case Try Public
catch Void Protected
char Float Return
class interface Short
continue For Static
default If Strictfp
do Import Switch
double implement This
else instanceof Throw
extend Long Throws

Identifier: Identifier is case sensitive n30.ames given to variable, methods, class, object,
packages etc

 Identifier can of any length in a single line


 They can have both letters and digits
 Ex: XYZ //legal , xyz //legal, 123asd //illegal
 Identifier is case sensitive
 Spaces are not allowed in between identifier name

Literals: Literals used to indicate values in Java program


 Integer literals= 33, 09, 3, 4…….
 Floating literals= 0.6, 33.7,2.6…….
 Character literals= ‘A’, ‘B’, ‘D’, ‘+’,’/‘…
 Boolean literals= true, false
 String literals= “Nelamangala”, “Hoysala Degree College”

Separators: They are character used to group and arrange Java source code
Ex: , [ , ] , ( , ) , ; , : ,etc.

Operators:
1. Unary operator: ++,--,+,-
(Binary Operators)
2. Arithmetic operator: +, -, *, / , %
3. Relational operator: ==, <=, >=, !, &&, , <,>
4. Bitwise operator: <<,>>,|,&

5. Ternary Operator
6. Special operator: .(dot operator)

Comment: A comment is non executable portion of program that is used as


 Single line comment (//)
 Multiline comment (/*……….*/)
 Javadoc comment (/**………...*/)

Data types:

Data Types Data types represent the different values to be stored in the variable. In java, there
are two types of data types:
i) Primitive datatypes
ii) ii) non-primitive datatypes.
Type Size Range
Byte 8 bits -128 to +127
Short 2 bytes -32768 to +32767
Int 4 bytes -2147483648 to +2147483647
Float 4 bytes -3.4+38(-3.4*1038) to 3.4+38(-3.4*1038)
Char 2 bytes 0 to 65,535
Double 8 bytes -1.7*10308 to 1.7*10308
Long 8 bytes -9223372036854775808 to
9223372036854775807
boolean 1 byte True/false [default false]

Command Line arguments: We pass the arguments by using command line argument
technique, the argument whatever we mentioned in the command line that will be stored in
the array args of type string.

Eg: import java.io.*;


public class Xyz
{
public static void main (String args[])
{
System.out.println (“Command line arguments”);
System.out.println (args [0]);
System.out.println (args [1]);
System.out.println (args [2]);
System.out.println (args [3]);
}
}

Reading Input from keyboard:


Reading input from keyboard a stream is required to accept data from keyboard.

A stream represents flow of data from one place to another place.

A stream is required to carry a data from keyboard to memory or from memory to keyboard
Or from memory to monitor or memory to printer.

There are two types of streams


i) Input stream (System.in)
ii) Output stream (System.out)

There are many ways to read data from the keyboard. For example:
o InputStreamReader
o Console
o Scanner
o DataInputStream etc.

InputStreamReader: this class can be used to read data from keyboard. It performs two
tasks:
o connects to input stream of keyboard
o converts the byte-oriented stream into character-oriented stream

BufferedReader: this class can be used to read data line by line by readLine() method.

Eg:

import java.io.*;
class G5{
public static void main (String args[])throws Exception{

InputStreamReader r=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}

Output:
Enter your name
ABC
Welcome ABC

Character stream: operates on 2 bytes.

a) Reader b) Writer
InputStreamReader is = new InputStreamReader(System.in);
BufferedReaderbr= new BufferedReader (is);
String s = br.readLine();

Byte stream: operates on 1 bytes.


DataInputStream ds = new DataInputStream (System.in);
String s = ds.readLine();
System.in : We have created input stream object or DataInputStreamobject and connecting
the keyboard system into it
readLine() : Used to accept or read the data in a line.
Write a programto accept user name and display the same
import java.io.*;
public class Xyz
{
public static void main (String args[]) throws IOException
{
DataInputStream ds = new DataInputStream(Sysem.in);
System.out.println(“Enter your Name”);
String s= ds.readLine();
System.out.println(“Your Name:” +s);
}
}

Write a program to accept your name, your class, your college & display
the same
import java.io.*;
publicclass Name
{
public static void main (String args[])throws IOException
{
String s1, s2, s3;
DataInputStream ds = new DataInputStream(System.in);
System.out.println (“Enter your Name”);
s1= ds.readLine();
System.out.println (“Enter your Class name”);
s2= ds.readLine();
System.out.println (“Enter your College name”);
s3= ds.readLine();
System.out.println (“Your Name:” +s1);
System.out.println (“Your Class name:” +s2);
System.out.println (“Your College name:” +s3);
}
}

Java Console Class


The Java Console class is be used to get input from console. It provides methods to read texts
and passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io. Console class is attached with system console internally. The Console
class is introduced since 1.5.

Let's see a simple example to read text from console.


1. String text=System.console().readLine();
2. System.out.println("Text is:"+text);
Java ConsoleExample
Import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome"+n);
}
}

Java Console Class


The Java Console class is be used to get input from console. It provides methods to read texts
and passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io. Console class is attached with system console internally.
The Console class is introduced since 1.5.

Let's see a simple example to read text from console.


1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);

Java Console Example


import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}

Output
Enter your name: ABC
Welcome ABC
Constructors:
“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.

There are basically two rules defined for the constructor.


1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

Types of java constructors:

There are two types of constructors


1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
<class_name>()
{
}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.

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

Output:
Bike is created

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display()
{System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}}
Output:
111Karan
222Aryan

Constructor Overloading in Java:


Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Example of Constructor Overloading

Class Student5{
int id;
String name;
int age;
Student5(int i , String n){
id = i;
name = n;
}
Student5(int i, String n, int a){
id = i;
name = n;
age=a;
}

Void display()
{System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}}

Output:
111 Karan 0
222 Aryan 25

Java 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

In this example, we are going to copy the values of one object into another using java
constructor.

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

Output:
111Karan
111Karan

Type casting or Data conversion


Definition: Type casting is used to convert data from one data type to another data type
Integer conversion:
int a = Integer .parseInt (s1);
This is to convert the string s1 to integer data type using function parse int that can be called
by classinteger

Float Conversion:
float a = Float.parsefloat (s1);
This is to convert the string s1 to float data type using function parse float that can be called
by class float

Double Conversion:
double a = Double.parseDouble (s1);
This is to convert the string s1 to double data type using function parse double that can be
called by class double

Write a program to accept an integer number and display the same


import java.io.*;
publicclass Name
{
public static void main (String args[])throws IOException
{
String s;
int a;
DataInputStream ds = new DataInputStream(System.in);
System.out.println(“Enter a number”);
s=ds.readLine();
a=Ineger.parseInt(s);
System.out.println (“Number=” +a)’
}
}

Write a program to accept two numbers and print the addition of two
numbers
import java.io.*;
publicclass Name
{
public static void main (String args[]) throws IOException
{
String s1, s2;
int a, b, c;
DataInputStream ds = new DataInputStream(System.in)
System.out.println(“Enter 2 number”);
s1=ds.readLine();
s2=ds.readLine();
a=Ineger.parseInt(s1);
b=Ineger.parseInt(s2);
c=a+b;
System.out.println (“Number=”+c);
}
}

Control Statements:
Decision making statements: if, if-else, switch-case.
Looping Statements: while, do-while,for.
Jumping Statements: break, continue.

if statement:
Syntax: if (expression)
Statement 1;

if-else statement:
Syntax: if (expression)
Statement 1:
else
Statement 2;

switch statement:
Syntax: switch (expression)
{
case value1: Statements1; break;
case value2: Statements2; break;
case value3: Statements3; break;
case value4: Statements4; break;
default : statement-n;
}

Write a program to check whether the given number is odd or even.

import java.io.*;
public class Name
{
public static void main (String args [])throwsIOException
{
DataInputStream ds = new DataInputStream(System.in)
System.out.println(“Enter any number”);
int n=Ineger.parseInt(ds, readLine ());
if(n%2==0)
System.out.println (“Even Number”);
else
System.out.println (“Odd Number”);
}
}

Write a program to find largest of three numbers


import java.io.*;
publicclass Name
{
public static void main(String args [])throwsIOException
{
int a, b, c large;
DataInputStream ds = new DataInputStream(System.in)
System.out.println(“Enter 3 number”);
a=Ineger.ParseInt (ds.readLine());
b=Ineger.ParseInt (ds.readLine());
c=Integr.ParseInt (ds.readline()):
if ((a>b) && (a>c))
large=a
else
if (b>c)
large=b;
else
large=c:
System.out.println (“Large =”+large);
}
}

Looping: Executes the block of statements repeatedly until the condition


become false.
while Loop:
Syntax: initialization;
while(condition)
{
Statement1:
Increment/decrement;
}

do-while:
Syntax:initialization
do
{
Statement 1;
Increment/decrement;
}while (condition);

for loop:
Syntax: for(initiation; Condition; Inc/Dec)
{
Statement 1;
Statement 2;
}
Write a program to factorial of given number using for loop
import java.io.*;
publicclass Name
{
public static void main(String args [])throwsIOException
{
int i, fact=1, n;
DataInputStream ds = new DataInputStream (System.in)
System.out.println (“Enter any number”);
n=Ineger.parseInt (ds.readLine ());
for(i=1; i<n; i++)
System.out.println (“Factorial=”+fact);
}
}

Write a program to find factorial of given number using while loop


import java.io.*;
publicclass Name
{
public static void main (String args [])throwsIOException
{
int i, fact=1, n;
DataInputStream ds = new DataInputStream(System.in);
System.out.println(“Enter any number”);
n=Ineger.parseInt (ds.readLine ());
while (i<n)
{
fact =fact*i:
i=i++;
}
System.out.println (“Factorial=”+fact);
}
}
Jumping statements
break Statements: - It is used to terminate block of statements that can be mentioned by
looping statements and switch case statements
for(i=;i<=10;i++)
{
if(i==6)
break;
System.out.println(i);
}
Output: 1 2 3 4 5

continue: - It is used to skip the current iteration and execute next iteration
if(i=1;i<=10;i++)
{
if(i==5)
continue:
System.out.println(i);
}
Output: 1 2 3 4 6 7 8 9 10

return statements
1. Simple Return
return;
Ex: void add()
{
System.out.println(“Sum=”+(10+20));
return;
}
2. Return with value return(value);

Ex: public static voidmain(String args[])


{
int c = add();
System.out.println();
}
int add()
{
return(10+20);
}

Scope of Variable
Scope determine when the variable is created and destroyed the variable can be include in 3
categories depending on these position in program.

1. Local Variable:
Local variable can be declared anywhere in the method or within a block the local
variable scope begins when the function or method or block starts execution and the
scope end when the function or method or block terminate initial value of LV is
garbage value.

2. Instance variable[Member variable]


This variable can be declared anywhere in class and can be accessed by any method
with in a class initial value of it is zero for int or float , null for string, true for
Boolean.

3. Static variable[class variable]


It is also called as class variable
The variable declared with static class and it is applicable to all the object[share to
all the object ].The scope begins when the program execution starts and scope ends
when the program execution stops.

Ex: - public class Xyz


{
int a; //Instance variable
static int b; //Static variable or class variable
void add()
{
int c; //Local variable
c=a+b;
a=20;
}
}
b

500

Obj 1 Obj 2 Obj3


 Here b is an static variable or class variable which is common to all object
 A is an instance variable or member variable which is related to particular object

Arrays: An array is a collection of homogenous elements of the same data type.

Array Creation: There are mainly 3-steps that are to be followed for create an array.
1. Declaration of array
An array must have a specific type like byte, int, float, String, double.etc.
Syntax:datatype[] variable_name;
Ex: int[] a;
float[] b;
string[] s;
double[] d;

2. Allocation of an memory for array:


Declaring an array doesn’t create an array, to actually create array using the ‘new’ operator.
When we create an array we need to tell the compiler how many elements will be stored in it.
Syntax: variable_name =new datatype[size];
a=new int[10];
b=new Float[20];
s=new string[[30];

3. Initialization of an array:
After declaration and allocation of an array it doesn’t have a valid value in it, so the array
need to be loaded with an initial value & this is called as initialization.
a[0]=10; b[0]=10.5 name[0]=”Bengaluru”
a[1]=20; b[1]=2.56 name[1]=”HDC”
a[2]=30; b[2]=5.86 name[2]=”123”
int []n=new int [] {10,20,30,40,50}; //valid
int [] n={10,20,30,40,50}; //valid
n={10,20,30,40,50} //in-valid
Accessing Java Array Elements using for Loop
Each element in the array is accessed via its index. The index begins with 0 and ends at (total
array size)-1. All the elements of array can be accessed using Java for Loop.

Example Program
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);

// Java program to illustrate creating an array


// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i
+ " : " + arr[i]);
}
}

Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Multidimensional array:
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other arrays. These are also known as Jagged Arrays. A multidimensional array
is created by appending one set of square brackets ([]) per dimension.

Syntax: datatype [][][]………[] array_name;


Array_name = new datatype [size][size][size]………[size];
Ex:int [][][][] a= new int [3][2][4][3];

Example Program
// Java Program to demonstrate Java Multidimensional Array

import java.io.*;
// Driver class
class GFG {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column

// Number of Rows
System.out.println("Number of Rows:"+
arr.length);

// Number of Columns
System.out.println("Number of Columns:"+
arr[0].length);
}
}

Output:
Number of Rows:3
Number of Columns:3

Java -Methods
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
Here,
 public static −modifier
 int − returntype
 methodName − name of the method
 a, b − formalparameters
 int a, int b − list ofparameters
Method definition consists of a method header and a method body. The same is shown in the
following syntax −
Syntax
The syntax shown above includes −
 modifier− It defines the access type of the method and it is optional touse.
 returnType− Method may return avalue.
 nameOfMethod− This is the method name. The method signature consists of themethod
name and the parameter list.
public static int methodName(int a, int b) {
// body
}
modifier returnType nameOfMethod (Par

You might also like