0% found this document useful (0 votes)
3 views71 pages

Module 2

The document provides a comprehensive introduction to Java programming, covering syntax, the structure of a Java program, data types, user input handling, methods, and object-oriented concepts like classes and constructors. It explains the importance of the main method, how to create classes and objects, and demonstrates various programming examples including arithmetic operations and user input. Additionally, it discusses method overloading and the use of static methods and variables in Java.

Uploaded by

poojapa
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)
3 views71 pages

Module 2

The document provides a comprehensive introduction to Java programming, covering syntax, the structure of a Java program, data types, user input handling, methods, and object-oriented concepts like classes and constructors. It explains the importance of the main method, how to create classes and objects, and demonstrates various programming examples including arithmetic operations and user input. Additionally, it discusses method overloading and the use of static methods and variables in Java.

Uploaded by

poojapa
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

First JAVA Program

Java Syntax:
File Name: [Link]
/* The code below will print the words Hello World to the screen, and it is amazing – Multiline
Comment */
import [Link].*;
class Main
{
public static void main(String[] args)
{
[Link]("Hello World"); // Single line comment
}
}

Every line of code that runs in Java must be inside a class. In our example, we named the class Main. A class
should always start with an uppercase first letter.
Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.
The name of the java file must match the class name. When saving the file, save it using the class name and add
".java" to the end of the filename.
The main Method
The main() method is required and you will see it in every Java program:
public static void main(String[] args)

Any code inside the main( ) method will be executed. For now, just remember that every Java program has
a class name which must match the filename, and that every program must contain the main( ) method.

[Link]( )
Inside the main( ) method, we can use the println( ) method to print a line of text to the screen:

public static void main(String[] args)


{
[Link]("Hello World");
}
Note: The curly braces {} marks the beginning and the end of a block of code.
System is a built-in Java class that contains useful members, such as out, which is short for "output".
The println( ) method, short for "print line", is used to print a value to the screen (or a file).
You should also note that each code statement must end with a semicolon (;).
Classes, Objects,
Data Members &
Member Functions
❑Java Classes/Objects:
• Java is an object-oriented programming language.
• Everything in Java is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.
• A Class is like an object constructor, or a "blueprint" for creating objects.
➢Create a Class:
• To create a class, use the keyword class:
[Link]
➢Create a class named “Main” with a variable x:
class Main
{
int x = 5;
}
➢Create an Object:
• In Java, an object is created from a class. We have already created the class named Main, so
now we can use this to create objects.
• To create an object of Main, specify the class name, followed by the object name, and use the
keyword new:

➢Example:
• Create an object called “myObj” and print the value of x:
class Main
{
int x = 5;
public static void main(String[] args)
{
Main myObj = new Main();
[Link](myObj.x);
}
}
❑ Data types:
Programming example:
import [Link].*;
public class Main {
public static void main(String[] args) {
int myNum = 5; // integer (whole number)
float myFloatNum = 5.99f; // floating point number
char myLetter = 'D'; // character
boolean myBool = true; // boolean
String myText = "Hello"; // String
[Link](myNum);
[Link](myFloatNum);
[Link](myLetter);
[Link](myBool);
[Link](myText);
}
}
• Addition of two numbers:
import [Link];
public class SumOfNumbers1
{
public static void main(String args[])
{
int n1 = 225, n2 = 115, sum;
sum = n1 + n2;
[Link]("The sum of numbers is: "+sum);
}
}
• Area of rectangle:
import [Link];
public class rectangle
{
public static void main(String args[])
{
int width=5;
int height=10;
int area=width*height;
[Link]("Area of rectangle="+area);
}
}
• Program to perform arithmetic operations:
import [Link];
public class arithop
{
public static void main(String[] args)
{
//Variables Definition and Initialization
int number1 = 12, number2 = 4;

//Addition Operation
int sum = number1 + number2;
[Link]("Sum is: " + sum);

//Subtraction Operation
int dif = number1 - number2;
[Link]("Difference is : " + dif);
//Multiplication Operation
int mul = number1 * number2;
[Link]("Multiplied value is : " + mul);

//Division Operation
int div = number1 / number2;
[Link]("Quotient is : " + div);

//Modulus Operation
int rem = number1 % number2;
[Link]("Remainder is : " + rem);
}
}
❑How to get input from user in Java?
▪ Java Scanner Class:
✓Java Scanner class allows the user to take input from the console.
✓It belongs to [Link] package.
✓It is used to read the input of primitive types like int, double, long, short, float,
and byte.
✓It is the easiest way to read input in Java program.

▪ Syntax:
Scanner sc=new Scanner([Link]);

✓The above statement creates a constructor of the Scanner class


having [Link] as an argument.
✓It means it is going to read from the standard input stream of the program.
✓The [Link] package should be import while using Scanner class.
❑ Methods of Java Scanner Class:
➢Example of sum of 3 numbers:
import [Link];
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner([Link]); //[Link] is a standard input stream
[Link]("Enter first number: ");
int a= [Link]();
[Link]("Enter second number: ");
int b= [Link]();
[Link]("Enter third number: ");
int c= [Link]();
int sum=a+b+c;
[Link](“Sum is= " +sum);
}
}
//Output:
//Enter first number: 11
//Enter second number: 23
//Enter third number: 14
//Sum is=48
➢ Example: Take input from user and display Name & Age.

import [Link];
class Main
{
public static void main(String[] args)
{
Scanner myObj = new Scanner([Link]);
[Link]("Enter name and age:");
String name = [Link](); // String input
int age = [Link](); // Numerical input
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
//Output:
//Enter name and age:
// ABC
// 25
// Name: ABC
// Age: 25
• Java program to perform all arithmetic operation:
import [Link];
public class ArithmeticOperation
{
public static void main(String[] args)
{
// Create scanner class object
Scanner sc = new Scanner([Link]);
// Input two numbers from user
[Link]("Enter first number :");
int num1 = [Link]();
[Link]("Enter second number :");
int num2 = [Link]();
// Perform arithmetic operations
int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
int quotient = num1 / num2;
int modulo = num1 % num2;
// Print result to console
[Link]("Sum : " + sum);
[Link]("Difference : " + difference);
[Link]("Product : " + product);
[Link]("Quotient : " + quotient);
[Link]("Modulo : " + modulo);
}
}
❑ Java Method:
• A method is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also known as functions.
• Why use methods? To reuse code: define the code once, and use it many times.
• A method must be declared within a class. It is defined with the name of the method,
followed by parentheses ( ). Java provides some pre-defined methods, such as
[Link]( ) , but you can also create your own methods to perform certain
actions.

➢How to Name a Method?


✓Some of the rules and tips to name the methods in Java are:
✓Try to use a name that corresponds to the functionality (if the method is adding two
numbers, use add() or sum())
✓The method name should start with a verb and in lowercase (Ex: sum(), divide(), area())
✓For a multi-word name, the first word should be a verb followed by a noun or adjective
without any space and with the first letter capitalized (Ex: addIntegers(), areaOfSquare)
• Declaration of method:
➢Syntax:
public int addNumbers (int a, int b)
{
//method body
}

➢There are a total of six components included in a method declaration. The


components provide various information about the method.

✓Access specifier:
It is used to define the access type of the method. The above syntax sees the use of
the “public” access specifier. However, Java provides four different specifiers,
which are:
✓ ReturnType:
It defines the return type of the method. In the above syntax, “int” is the return type. We
can mention void as the return type if the method returns no value.

✓ Method name:
It is used to give a unique name to the method. In the above syntax, “addNumbers” is
the method name. This tutorial looks at some tips for naming a method, shortly.
✓Parameter list:
It is a list of arguments (data type and variable name) that will be used in the method. In
the above syntax, “int a, int b” mentioned within the parentheses is the parameter list.
You can also keep it blank if you don’t want to use any parameters in the method.

✓Method signature:
You don’t have to do anything additional here. The method signature is just a
combination of the method name and parameter list.

✓Method body:
This is the set of instructions enclosed within curly brackets that the method will
perform.
In the above example:
➢Example: •‘Public’ is the access specifier.

•The return type is ‘int’ (i.e.


integer)

•The method name is


addNumbers.

•int x and int y are the parameters.

•addNumbers (int x, int y) is the


method signature.

•The method body is:


{
int addition = x + y;
return addition;
}
❑Static Method: Example:
public class Main
{
static void myMethod()
{
// code to be executed
}
}

• myMethod is the name of the method,


• static means that the method belongs to the Main class and not an object of the Main
class.
• void means that this method does not have a return value.
➢Call a Static Method:
• To call a method in Java, write the method's name followed by two parentheses ( ) and a
semicolon;
• In the following example, myMethod is used to print a text (the action), when it is called:

public class Main


{
static void myMethod( ) // this is static method
{
[Link]("I just got executed!");
}
public static void main(String[] args)
{
myMethod( ); // calling static method without creating any object
}
}
// Outputs: "I just got executed!"
➢Java Static Variables:
• A static variable is common to all the instances (or objects) of the class
because it is a class level variable. In other words you can say that only a
single copy of static variable is created and shared among all the
instances of the class. Memory allocation for such variables only
happens once when the class is loaded in the memory.
Few Important Points:
• Static variables are also known as Class Variables.
• Unlike non-static variables, such variables can be accessed directly in
static and non-static methods.
Example: Static Variable and Static Method:

class JavaExample
{
static int var1=10;
static String var2=“Hello”;

static void disp( ) //This is a Static Method


{
[Link]("Var1 is: "+var1);
[Link]("Var2 is: "+var2);
}
public static void main(String args[])
{
disp( );
}
}

//Var1 is: 10
//Var2 is: Hello
❑ Parameters and Arguments:
➢ Example: Single parameter: • Information can be passed to methods
public class Main as parameter. Parameters act as
{ variables inside the method.
static void myMethod(String fname) • Parameters are specified after the
{ method name, inside the parentheses.
[Link](fname + " Lopes");
You can add as many parameters as you
want, just separate them with a comma.
}
• The following example has a method
public static void main(String[] args)
that takes a string called fname as
{ parameter. When the method is called,
myMethod("Liam"); we pass along a first name, which is
myMethod("Jenny"); used inside the method to print the full
myMethod("Anuja");
name:
}
}
// Liam Lopes
// Jenny Lopes
// Anuja Lopes
Example: Multiple Parameters:
public class Main
{
static void myMethod(String fname, int age)
{
[Link](fname + " is " + age);
}
public static void main(String[] args)
{
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anuja", 31);
}
}

// Liam is 5
// Jenny is 8
// Anuja is 31
❑Methods in Java:
• Methods in Java can be broadly classified into two types:
i. Predefined
ii. User-defined

i) Predefined Methods:
• As the name gives it, predefined methods in Java are the ones that the Java class libraries
already define. This means that they can be called and used anywhere in our program
without defining them. There are numerous predefined methods, such as length(), sqrt(),
max(), and print(), and each of them is defined inside their respective classes.
• The example mentioned below uses three predefined methods, which are main(), print(),
and sqrt().
Example_1:

Example_2:
public class LengthExample{
public static void main(String args[]){
String s1="javatpoint";
String s2="python";
[Link]("string length is: "+[Link]());//10 is the length of javatpoint string
[Link]("string length is: "+[Link]());//6 is the length of python string
}}
ii) User-defined Methods:

• Custom methods defined by the user are known as user-defined methods. It is possible to modify these
methods according to the situation. Here’s an example of a user-defined method.
❑ Constructor:
• A constructor in Java is similar to a method that is invoked when an
object of the class is created.
• Unlike Java methods, a constructor has the same name as that of the
class and does not have any return type. For example,

Here, Test() is a constructor. It has the same name as that of the class and doesn't
have a return type.
Example:
Types of Constructor:
1) No-argument constructor:
a) private:
b) public:
2) Parameterised constructor:
3) Default constructor:
• Constructor Overloading:
In Java, we can overload constructors like methods. The constructor overloading can be
defined as the concept of having more than one constructor with different parameters so
that every constructor can perform a different task.
➢Example:
Public class Employee
{
Employee()
{
[Link]("Employee Details:");
}
Employee(String name)
{
[Link]("Employee name: " +name);
}
Employee(String nCompany, int id)
{
[Link]("Company name: " +nCompany);
[Link]("Employee id: " +id);
}
}

Public class Myclass


{
public static void main(String[] args)
{
Employee emp = new Employee();
Employee emp2 = new Employee("Deep");
Employee emp3 = new Employee("HCL", 12234);
}
}
❑ Method Overloading:
• Method Overloading is a feature that allows a class to have more than one
method with the same name, if their argument lists are different.
• This is an important feature in java, there are several cases where we need more
than one methods with same name.
• For example, if we are building an application for calculator, we need different
variants of add method based on the user inputs such as add(int, int), add(float,
float) etc.
• Argument list means the parameters that a method has: For example the argument
list of a method add(int a, int b) having two int parameters is different from the
argument list of the method add(int a, int b, int c) having three int parameters.
Example:
Example:
❑Example: Area of Rectangle using method overloading:

import [Link].*;
class Rectangle
{
// Overloaded Area() function to calculate the area of the rectangle
//It takes two double parameters
void Area(double S, double T)
{
[Link]("Area of the rectangle: "+ S * T);
}

// Overloaded Area() function to calculate the area of the rectangle


// It takes two int parameters
void Area(int S, int T)
{
[Link]("Area of the rectangle: " + S * T);
}
}
class Main
{
public static void main(String[] args)
{
// Creating object of Rectangle class
Rectangle obj = new Rectangle();

// Calling function
[Link](20, 10);
[Link](10.5, 5.5);
}
}
❑ Packages:
• A java package is a group of similar types of classes, interfaces and sub-
packages.
• Package in java can be categorized in two form, built-in package and user-
defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.
• Here, we will have the detailed learning of creating and using user-defined
packages.

❑Types of Packages in Java:


• They can be divided into two categories:
[Link] API packages or built-in packages
[Link]-defined packages.
1) Java API (Application Programming Interface) packages or built-in packages:
• Java provides a large number of classes grouped into different packages based on
a particular functionality.
➢Examples:
✓[Link]: It contains classes for primitive types, strings, math functions, threads,
and exceptions.
✓[Link]: It contains classes such as vectors, hash tables, dates, Calendars, etc.
✓[Link]: It has stream classes for Input/Output.
✓[Link]: Classes for implementing Graphical User Interface – windows, buttons,
menus, etc.
✓[Link]: Classes for networking
✓java. Applet: Classes for creating and implementing applets
2) User-defined packages:
As the name suggests, these packages are defined by the user. We create a directory whose
name should be the same as the name of the package. Then we create a class inside the
directory.

❑Creating a Package in Java:


The package keyword is used to create a package in java.
//save as [Link]
package mypack;
public class Simple
{
public static void main(String args[])
{
[Link]("Welcome to package");
}
}
➢How to compile java package?
If you are not using any Integrated Development Environment (IDE), you need to follow
the syntax given below:
javac -d . [Link]
Note: The -d switch specifies the destination where to put the generated class file. You can use any directory
name like /home (in case of Linux), e:/abc (in case of windows) etc. If you want to keep the package within
the same directory, you can use . (dot).

➢How to run java package program?


You need to use fully qualified name e.g. [Link] to run the class.
java [Link]

//Output: Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
Note: If class file of [Link] is source file in classes folder of c: drive, Then
e:\sources> javac -d c:\classes [Link]
e:\sources> java -classpath c:\classes [Link]
❑ Access Modifiers:
• There are four types of Java access modifiers:
[Link]: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
[Link]: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
[Link]: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from outside
the package.
[Link]: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside.
❑How to access package from another package:
1) Using packagename.*
• If you use package.* then all the classes and interfaces of this package will be accessible,
but not sub-packages.
• The import keyword is used to make the classes and interface of another package
accessible to the current package.

• Example:
2) Using [Link]
• If you import [Link] then only declared class of this
package will be accessible.
• Example:
3) Using fully qualified name
• If you use fully qualified name then only declared class of this
package will be accessible. Now there is no need to import. But you
need to use fully qualified name every time when you are accessing
the class or interface.
• It is generally used when two packages have same class name e.g.
[Link] and [Link] packages contain Date class.
• Example:
❑Subpackage in java:
• Package inside the package is called the subpackage. It should be
created to categorize the package further.

•The package java has subpackages like awt, applet, io, lang, net, util etc.
The package java doesn't have any class, interface, enums etc inside it.

•The package [Link] has subpackages like color, font, image etc inside
it. The package [Link] itself has many classes and interfaces declared
inside it.
➢Example_1: Here, the package name is [Link] which is a subpackage.

package [Link];
class MySubPackageProgram
{
public static void main(String args [])
{
[Link]("My sub package program");
}
}

• Compile and Run:


javac -d. [Link]
java [Link]
➢Example_2:
Here, package is defined as [Link]
i.e. [Link] , Since the website name is [Link]

package [Link];
class Simple
{
public static void main(String args[])
{
[Link]("Hello subpackage");
}
}

To Compile: javac -d . [Link]


To Run: java [Link]
❑Standard I/O Streams In Java:
• Java language offers access to system resources, standard input-output devices, etc.
using a “System” class. This class implements a system-dependent programming
interface to access various resources.
• The System class belongs to the “[Link]” package of Java. Apart from providing
standard I/O streams, System class also provides access to environment variables,
external variables, loading files and libraries, and also a utility method arrayCopy for
copying part of an array.

1) Standard Input Stream ([Link])


• The input stream provided by System class, [Link] is used to read the input data
from a standard input device like a keyboard.
• The stream remains open and is ready to read the data supplied by the user to the
standard input device.
❖ JAVA user input:
In the Java program, there are 3 ways we can read input from the user in the
command line environment to get user input.
i. Java BufferedReader Class
• BufferedReader reads input from the character-input stream and buffers
characters, so as to provide an efficient reading of all the inputs.
• The default size is large for buffering.
• When the user makes any request to read, the corresponding request goes to
the reader, and it makes a read request of the character or byte streams (used to
read/write binary data) ; thus, BufferedReader class is wrapped around
another input streams such as FileReader or InputStreamReaders.
• BufferedReader can read data line by line using method readLine() method.
➢The read() method of BufferedReader class in Java is of two types:
a) The read() method of BufferedReader class in Java is used to read a single character
from the given buffered reader.
• This read() method reads one character at a time from the buffered stream and return it
as an integer value.
• Syntax:
public int read() throws IOException

✓Overrides: It overrides the read() method of Reader class.


✓Parameters: This method does not accept any parameter.
✓Return value: This method returns the character that is read by this method in the
form of an integer. If the buffered stream has ended and there is no character to be read
then this method return -1.
✓Exceptions: This method throws IOException if an I/O error occurs.
• Program: Assume the existence of the file “c:/[Link]” containing text as “ Hello. welcome”

import [Link];
import [Link];
import [Link];

public class JavaBufferedReaderReadExample1


{
public static void main(String[] args) throws IOException
{
FileReader f=new FileReader("C:/[Link]");
BufferedReader b=new BufferedReader(f);
int i;
while((i=[Link]())!=-1)
{
[Link]((char)i);
}
[Link]();
[Link]();
}
}
b) The read(char[ ], int, int) method of BufferedReader class in Java is used to read
characters in a part of a specific array.
➢The general contract of this read() method is as following:
• It reads maximum possible characters by calling again and again the read() method of
the main stream.
• It continues till the reading of specified number of characters or till the ending of file.
• This method is specified by read() method of Reader class.
• Syntax:
public int read(char[] cbuf, int offset, int length) throws IOException
✓Parameters: This method accepts three parameters:
• cbuf – It represents the destination buffer.
• offset – It represents the starting point to store the characters.
• length – It represents the maximum number of characters that is to be read.
✓Return value: This method returns the number of characters that is read by this
method. If the buffered stream has ended and there is no character to be read then
this method return -1.
✓Exceptions: This method throws IOException if an I/O error occurs.
• Program: Assume the existence of the file “c:/[Link]” containing text "GEEKSFORGEEKS"

import [Link].*;
public class GFG
{
public static void main(String[] args)
{

// Read the stream ‘[Link]’ containing text "GEEKSFORGEEKS"


FileReader fileReader= new FileReader("c:/[Link]");

// Convert fileReader to bufferedReader


BufferedReader buffReader= new BufferedReader(fileReader);

// Create a character array


char[] cbuf = new char[13];

// Initialize and declare offset and length


int offset = 2;
int length = 5;
// Calling read() method on buffer reader
[Link]("Total number of characters read: " + [Link](cbuf, offset, length));
// For each char in cbuf
for (char c : cbuf)
{
if (c = = (char)0)
c = '-';
[Link]((char)c);
}
}
}

Output:
-GEEKS-------
ii. Java Scanner Class
• [Link]. scanner class is one of the classes used to read user input from
the keyboard.
• It is available at the util package.
• Scanner classes break the user input using a delimiter that is mostly
whitespaces by default.
• The scanner has many methods to read console input of many primitive
types such as double, int, float, long, Boolean, short, byte, etc.
• It is the simplest way to get input in java.
• The scanner provides nextInt() and many primitive type methods to read
inputs of primitive types.
• The next() method is used for string inputs.
➢Functions
• Below are mentioned the method to scan the primitive types from console input through
Scanner class.
✓nextInt()
✓nextFloat()
✓nextDouble()
✓nextLong()
✓nextShort()
✓nextBoolean()
✓nextDouble()
✓nextByte()
➢Program to read from Scanner Class:
Using scanner class. import [Link];
/*package whatever //do not write package name here */
class ScannerDemo
{
public static void main (String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter your number");
int t = [Link]();
[Link]("Number you entered is: " + t);
[Link]("Enter your string");
String s = [Link]();
[Link]("String you entered is: " + s);
}
}
iii. Using console Class
• Using the console class to read the input from the command-line interface. It does not
work on IDE.

Code:
public class Main
{
public static void main(String[] args)
{
// Using Console to input data from user
[Link]("Enter your data");
String name = [Link]().readLine();
[Link]("You entered: "+name);
}
}
2) Standard Output Stream ([Link])
• The [Link] interface of the System class is used to write the program output to the
standard output device like the monitor. In most cases, the [Link] interface writes
the command output to the standard output device.
• It uses three methods from the “PrintStream” class as the standard output derives from
this class.
• These methods are:
✓print
✓println
✓write
• The methods “print” and “println” have the same functionality except for a single
difference that the println method appends a newline character (\n) to the output

You might also like