0% found this document useful (0 votes)
14 views105 pages

Java Basic Syntax and Constructs Guide

The document provides an overview of basic syntactical constructs in Java, covering features, class definitions, object creation, data types, operators, and control structures. It emphasizes Java's simplicity, object-oriented nature, portability, and security, along with detailed explanations of classes, objects, data types, and variable scopes. Additionally, it discusses type casting and various operators used in Java programming.

Uploaded by

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

Java Basic Syntax and Constructs Guide

The document provides an overview of basic syntactical constructs in Java, covering features, class definitions, object creation, data types, operators, and control structures. It emphasizes Java's simplicity, object-oriented nature, portability, and security, along with detailed explanations of classes, objects, data types, and variable scopes. Additionally, it discusses type casting and various operators used in Java programming.

Uploaded by

vaishali jangam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

01

BASIC
SYNTACTICAL
CONSTRUCTS IN
JAVA
 Points to be covered in this unit:
1.1 Java features and the Java programming environment.
1.2 Defining a class, creating object, accessing class
members.
1.3 Java tokens and data types, symbolic constant, scope of
variable, typecasting, and different types of operators and
expressions, decision making and looping statements.
1.4 Arrays, strings, string buffer classes, vectors, wrapper
classes.
1.5 Constructors and methods, types of constructors,
method and constructor overloading, nesting of methods,
command line arguments, garbage collection, visibility
control: public, private, protected, default, private
protected.
1.1 Java features and java programming
environment:
Java Features:
[Link]
[Link]-Oriented
[Link]
[Link] independent
[Link]
[Link]
7. Architecture neutral
[Link]
[Link] Performance
[Link]
[Link]
[Link]
1. Simple:
Java language is a simple programming language
because:
Java syntax is based on C++ (so easier for
programmers to learn it after C++).
Java has removed many complicated and rarely-
used features, for example, explicit pointers,
operator overloading, etc.
There is no need to remove unreferenced objects
because there is an Automatic Garbage Collection
in Java.
2. Object-Oriented:
Object-oriented means we organize our
software as a combination of different types
of objects that incorporate both data and
behavior.

3. Portable:
Java is portable because it facilitates you
to carry the Java code to any platform.
4. Platform independent:
Java code can be executed on multiple
platforms, for example, Windows, Linux,
Sun Solaris, Mac/OS, etc.
5. Secured:
• Java is best known for its security. With Java, we
can develop virus-free systems. Java is secured
because:
• No explicit pointer
• Java Programs run inside a virtual machine
7. Robust:
Java is robust because:
1. It uses strong memory management.
2. There is a lack of pointers that avoids
security problems.
3. Java provides automatic garbage collection
which runs on the Java Virtual Machine to
get rid of objects which are not being used by
a Java application anymore.
4. There are exception handling and the type
checking mechanism in Java.
8. Interpreted:
Java employs both compilation and interpretation to run
code, it is known as a “compiler-interpreter language.”
9. High Performance:
Java architecture is defined in such a way that it reduces
overhead during the runtime and at some times java uses
Just In Time (JIT) compiler where the compiler
compiles code on-demand basis where it only compiles
those methods that are called making applications to
execute faster.
10. Multithreaded:
Java supports multithreading, enabling the concurrent
execution of multiple parts of a program. This feature is
particularly useful for applications that require high performance,
11. Distributed :
We can create distributed applications using the java
programming language. Remote Method Invocation and
Enterprise Java Beans are used for creating distributed
applications in java. The java programs can be easily
distributed on one or more systems that are connected to
each other through an internet connection.
12. Dynamic:
Java is a dynamic language. It supports the dynamic loading
of classes. It means classes are loaded on demand. It also
supports functions from its native languages, i.e., C and C+
+.
1.2 Defining a class, creating object, accessing class members.

1. In Java, classes and objects are basic concepts of


Object Oriented Programming (OOPs) that are
used to represent real-world concepts and entities.
2. The class represents a group of objects having
similar properties and behavior.
3. For example, the animal type Dog is a class while
a particular dog named Tommy is an object of
the Dog class.
Java Classes:
Definition of class:
• A class in Java is a set of objects which shares
common characteristics/ behavior and common
properties/ attributes.
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:
I. Data member(Variables e.g. int a,
b)
II. Method(void add())
III. Constructor(add())
IV. Nested Class
V. Interface
Example for Java class:

public class HelloWorld {


public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Output :
Hello, World!
Java Objects :
Definition of 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.
• 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”.
•An object consists of :
[Link] : It is represented by attributes of an object.
It also reflects the properties of an object.
[Link] : It is represented by the methods of an
object. It also reflects the response of an object
with other objects.
[Link] : It gives a unique name to an object and
enables one object to interact with other objects.
•Example of an object:
dog,pen,human body,student etc.
Example for class and object declarations:
class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;
public static void main(String args[])
{
// creating an object of
// Student
Student s1 = new Student();
[Link]([Link]);
[Link]([Link]);
}
}
Output :
0
null
1.3 Java tokens and data types, symbolic constant, scope of variable, typecasting, and
different types of operators and expressions, decision making and looping statements.

•Java Data types:


Data types are divided into two groups:
1. Primitive data types - includes byte,
short, int, long, float, double, Boolean
and char.
2. Non-primitive data types - such as
String, Arrays and Classes.
1. Primitive data types :
Data Type Description

byte Stores whole numbers from -128 to 127


short Stores whole numbers from -32,768 to 32,767
int Stores whole numbers from -2,147,483,648 to 2,147,483,647

long Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807
float Stores fractional numbers. Sufficient for storing 6 to 7 decimal
digits
double Stores fractional numbers. Sufficient for storing 15 to 16 decimal
digits
boolean Stores true or false values
char Stores a single character/letter or ASCII values
Java Tokens:
1. In Java, Tokens are the smallest building blocks(or
elements) of a program that are meaningful to the
compiler.
Example of tokens:
public class Demo
{
public static void main(String args[])
{
[Link](“Welcome to JPR");
}
}
In the above program, public, class, Demo, {, static, void,
main, (, String, args, [, ], ), System, ., out, println, Welcome
to JPR, etc. are the Java tokens.
Types of Tokens:

Java token includes the following:


1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
6. Comments
[Link]:
•These are the pre-defined reserved
words of any programming language.
•Each keyword has a special meaning.
•It is always written in lower case. Java
provides the following keywords:
Keywords:
01. abstract 02. boolean 03. byte 04. break 05. class

06. case 07. catch 08. char 09. continue 10. default

11. do 12. double 13. else 14. extends 15. final

16. finally 17. float 18. for 19. if 20. implements

21. import 22. instanceof 23. int 24. interface 25. long

26. native 27. new 28. package 29. private 30. protected

31. public 32. return 33. short 34. static 35. super

36. switch 37. synchronized 38. this 39. throw 40. throws

41. transient 42. try 43. void 44. volatile 45. while

46. assert 47. const 48. enum 49. goto 50. strictfp
2. Identifier:
• Identifier: Identifiers are used to name a variable, constant,
function, class, and array. It usually defined by the user.
Rules For Identifiers:
• The first letter of an identifier must be a letter,
underscore or a dollar sign. It cannot start with digits
but may contain digits.
• The whitespace cannot be included in the identifier.
• Identifiers are case sensitive.
3. Literals:
• In programming literal is a notation that represents a
fixed value (constant) in the source code.
• It can be categorized as an integer literal, string
literal, Boolean literal, etc. It is defined by the
programmer.
• Once it has been defined cannot be changed.
• Java provides five types of literals are as follows:
1. Integer
2. Floating Point
3. Character
4. String
[Link]:
• In programming, operators are the special symbol
that tells the compiler to perform a special
operation . E.g. +,-,*,/,% etc.
[Link]
In Java, separators are characters that help organize
and structure code by separating different parts of a
statement or expression.
The most commonly used separators include the
semicolon (;), comma (,), dot (.), and colon (:).
6. Comments:
• Comments in Java are used to explain code, making it
more readable and maintainable. They are ignored by
the compiler during execution.
• Types of comments:
1. Single-line Comments
Single-line comments start with //
// This is a single-line comment
[Link]("Hello, World!"); // This is another
single-line comment
2. Multi-line Comments:
Multi-line comments start with /* and end with */
/*
This is a multi-line comment
It can span multiple lines
*/
[Link]("Hello, World!");
[Link] Comments
Documentation comments start with /** and
end with */
Scope of Variables In Java :
1. Scope of a variable is the part of the
program where the variable is accessible.
2. There are four scopes for variables in Java:
[Link] Variables,
[Link] Variables,
[Link] Variables, and
[Link] parameters.
1. Local Variables :
I. Local variables are those that are declared
inside a method, constructor, or code block.
II. The Java compiler throws an error if a local
variable is not initialized before being used.
[Link] range of local variables is the smallest of
all the different variable types.
Example Of Local Variables:
[Link] SumExample
2.{
[Link] void calculateSum() {
4. int a = 5; // local variable
5. int b = 10; // local variable
6. int sum = a + b;
7. [Link]("The sum is: " + sum);
8.} // a, b, and sum go out of scope here
9.}
• Output: The sum is: 15
2. Instance Variables :
I. Within a class, but outside of any methods,
constructors, or blocks, instance variables are
declared.
II. They are accessible to all methods and blocks in
the class and are a part of an instance of the class.
III. If an instance variable is not explicitly
initialized, its default values are false for Boolean
types, null for object references, and 0 for
numeric kinds.
Example Of Instance class:
public class Circle {
double radius; //
instance variable public double calc
ulateArea() {
return [Link] * radius * radius;
}
}
3. Class Variables or(Static Variables):
I. In a class but outside of any method, constructor,
or block, the static keyword is used to declare
class variables, also referred to as static variables.
II. Example:
public class Bank {
static double interestRate; // class variable
// ...
}
4. Method parameters :
I. Variables that are supplied to a method when it
is invoked are known as method parameters.
II. The scope of method parameters is restricted
to the method in which they are defined,
making them local to that method.
[Link] values of the arguments given are
allocated to the respective parameters when a
method is called.
Example of Method Parameters:
public void printName(String name) {
// name is a method parameter
[Link]("Hello, " + name
+ "!");
}
Java Type Casting :

1. Type casting is when you assign a value of one


primitive data type to another type.
In Java, there are two types of casting:
2. Widening Casting (automatically) - converting a smaller
type to a larger type size
byte -> short -> char -> int -> long -> float -> double
2. Narrowing Casting (manually) - converting a larger type to a
smaller size type
double -> float -> long -> int -> char -> short -> byte
Example for Widening Casting :
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to
double

[Link](myInt); // Outputs 9
[Link](myDouble); // Outputs 9.0
}
}
Example for Narrowing Casting :
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting:
double to int

[Link](myDouble); // Outputs 9.78


[Link](myInt); // Outputs 9
}
}
Java Operators:
Java divides the operators as the following:
1. Arithmetic operators
[Link] operators
[Link] operators
[Link] operators
[Link] operators
1. Arithmetic operators

• Arithmetic operators are used to perform


common mathematical operations.
Operator Name Description Example
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x
2. Assignment operators :

[Link] operators are used to


assign values to variables.
2. In the example below, we use the
assignment operator (=) to assign
the value 10 to a variable called x:
int x = 10;
Assignment operators:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
[Link] operators:

1. Comparison operators are used to compare two values (or


variables).
2. This is important in programming, because it helps us to
find answers and make decisions.
3. The return value of a comparison is either true or false.
These values are known as Boolean values.
Example
int x = 5;
int y = 3;
[Link](x > y);
Comparison operators:
Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


[Link] operators :
[Link] can also test for true or
false values with logical
operators.
[Link] operators are used to
determine the logic between
variables or values.
Logical operators :
Operator Name Description Example

&& Logical and Returns true if both x < 5 && x < 10


statements are true

|| Logical or Returns true if one of the x < 5 || x < 4


statements is true

! Logical not Reverse the result, returns !(x < 5 && x <
false if the result is true 10)
5. Bitwise Operators:
Types of Bitwise Operator
•There are six types of the bitwise operator in
Java:

1. Bitwise AND
2. Bitwise exclusive OR
3. Bitwise inclusive OR
4. Bitwise Compliment
5. Bit Shift Operators
Bitwise Operators:
O Symbol Uses

Bitwise AND & op1 & op2

Bitwise exclusive OR ^ op1 ^ op2

Bitwise inclusive OR | op1 | op2

Bitwise Compliment ~ ~ op

Bitwise left shift << op1 << op2

Bitwise right shift >> op1 >> op2

Unsigned Right Shift


>>> op >>> number of places to shift
Operator
Decision making and looping statements :
I. A programming language uses control statements to control
the flow of execution of a program based on certain
conditions.
Java’s Selection statements:
a. if
b. if-else
c. nested-if
d. if-else-if
e. switch-case
f. jump – break, continue, return
a. if:
I. if statement is the most simple decision-making statement.
II. It is used to decide whether a certain statement or block of
statements will be executed or not i.e if a certain condition is true
then a block of statements is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Example for if statement :
import [Link].*;
class IfDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
[Link]("Inside If block");
[Link]("10 is less than 15");
[Link]("I am Not in if"); }
}
Output :
Inside If block
10 is less than 15
I am Not in if
b. if-else :
I. 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 won’t.
II. We can use the else statement with the if statement to execute a block of code
when the condition is false.
Syntax:
if (condition)
{
// Executes this block of code
}
else
{
// Executes this block of code
}
// Java program to illustrate if-else statement
import [Link].*;
class IfElseDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
}
Output :
• i is smaller than 15
3. nested-if
I. Nested if statements means an if statement inside an if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Java program to illustrate nested-if statement
//

import [Link].*;
class NestedIfDemo {
public static void main(String args[])
{
int i = 10;
if (i == 10 || i<15) {
if (i < 15)
[Link]("i is smaller than 15");
if (i < 12)
[Link]("i is smaller than 12 too");
} else{
[Link]("i is greater than 15");
}
}
Output :
i is smaller than 15
i is smaller than 12 too
d. if-else-if :

1. a user can decide among multiple options.


2. Syntax :
if (condition)
statement;
else if (condition)
statement;
……
else
statement;
// Java program to illustrate if-else-if ladder
import [Link].*;
class ifelseifDemo {
public static void main(String args[])
{
int i = 20;
if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
}
}
• Output : i is 20
e. Switch statement :
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
case valueN:
statementN;
break;
default:
statementDefault;
}
import [Link].*;
class GFG {
public static void main (String[] args) {
int num=20;
switch(num){
case 5 : [Link]("It is 5");
break;
case 10 : [Link]("It is 10");
break;
case 15 : [Link]("It is 15");
break;
case 20 : [Link]("It is 20");
break;
default: [Link]("Not present");
}
}
}

Output :
It is 20
f. jump – break, continue, return :
•Java supports three jump statements: break,
continue and return.
1. Break: In Java, a break is majorly used for:
Terminate a sequence in a switch statement.
To exit a loop.
2. Continue: Sometimes it is useful to force
an early iteration of a loop.
import [Link].*;
class ContinueDemo {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is even
// skip and continue
if (i % 2 == 0)
continue;
[Link](i + " ");
}
}
}
• Output : 1 3 5 7 9
return :
• The return statement is used to explicitly return from a method.
import [Link].*;
public class Return {
public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");
if (t)
return;
[Link]("This won't execute.");
}
}
Output
Before the return.
1.4 Arrays, strings, string buffer classes,
vectors, wrapper classes
1. Arrays are fundamental structures in Java that allow us to store multiple values
of the same type in a single variable.
public class Main {
public static void main(String[] args)
{ int[] arr = { 1, 2, 3, 4, 5 };
int n = [Link];
for (int i = 0; i < n; i++)
[Link](arr[i] + " ");
}
}
Output
12345
• Basics of Arrays in Java
• There are some basic operations we can start with as mentioned below:
1. Array Declaration
To declare an array in Java, use the following syntax:
type[] arrayName;
type: The data type of the array elements (e.g., int, String).
arrayName: The name of the array.
Note: The array is not yet initialized.
2 . Create an Array
To create an array, you need to allocate memory for it using the new keyword:
// Creating an array of 5 integers
numbers = new int[5];
This statement initializes the numbers array to hold 5 integers. The default value
for each element is 0.
• 3. Access an Element of an Array
• We can access array elements using their index, which starts from 0:
• numbers[0] = 10;
• int firstElement = numbers[0];
• The first line sets the value of the first element to 10. The second line
retrieves the value of the first element.
4. Change an Array Element
• To change an element, assign a new value to a specific index:
// Changing the first element to 20
• numbers[0] = 20;
• 5. Array Length
• We can get the length of an array using the length property:
• // Getting the length of the array
• int length = [Link];
Example of Array:
class GFG {
public static void main(String[] args)
{
int[] arr;
arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (int i = 0; i < [Link]; i++)
[Link]("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
Types of Arrays in Java
Java supports different types of arrays:
1. Single-Dimensional Arrays
These are the most common type of arrays, where elements are stored in
a linear order.
// A single-dimensional array
int[] singleDimArray = {1, 2, 3, 4, 5};
2. Multi-Dimensional Arrays:
Arrays with more than one dimension, such as two-dimensional arrays
(matrices).
// A 2D array (matrix)
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
import [Link].*;
class GFG {
public static void main(String[] args){
// Two Dimensional Array
// Declared and Initialized
int[][] arr = new int[3][3];
// Number of Rows
[Link]("Rows : " + [Link]);
// Number of Columns
[Link]("Columns : " + arr[0].length);
}
}
• String : is the type of objects that can store the sequence of characters
enclosed by double quotes.
• Example:
• String name = “Geeks”;
• String num = “1234”;
// Java Program to demonstrate String
public class Geeks {
// Main Function
public static void main(String args[])
{
// creating Java string using new keyword
String str = new String(“Java Programming");
[Link](str);
}
• StringBuffer
• StringBuffer is a peer class of String, it is mutable in nature
and it is thread safe class , we can use it when we have multi
threaded environment and shared object of string buffer i.e,
used by multiple thread. As it is thread safe so there is extra
overhead, so it is mainly used for multithreaded program.
• Syntax:
StringBuffer demoString = new
StringBuffer(“GeeksforGeeks”);
StringBuffer classes are :
StringBuilder
StringTokenizer
Java Vector :
• Vector is like the dynamic array which can grow or shrink its size.
Wrapper class :
• A Wrapper class in Java is a class whose object wraps or contains
primitive data types
Primitive Data Type Wrapper Class
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
1.5 Constructors and methods, types of constructors, method and
constructor overloading, nesting of methods, command line arguments,
garbage collection, visibility control: public, private, protected, default,
private protected.
Constructors :
public class Main {
int x; // Create a class attribute
public Main() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
[Link](myObj.x); // Print the value of x
}
}
// Outputs 5
Note that the constructor name must match the class name, and it cannot have a return
type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you.
 However, then you are not able to set initial values for object attributes.
Syntax For Constructor :
class A
{
.......
// A Constructor
A() {
}
.......
}
// We can create an object of the above class
A obj = new A();
Types of Constructors in Java :
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Default Constructor in Java :
A constructor that has no parameters is known as default constructor.
A default constructor is invisible.
And if we write a constructor with no arguments, the compiler does not create a
default constructor.
It is being overloaded and called a parameterized constructor.
The default constructor changed into the parameterized constructor. But
Parameterized constructor can’t change the default constructor.
// Java Program to demonstrate
// Default Constructor
import [Link].*;
// Driver class
class GFG {
// Default Constructor
GFG() { [Link]("Default constructor"); }
// Driver function
public static void main(String[] args)
{
GFG hello = new GFG();
}
}
Output
Default constructor
2. Parameterized Constructor :

• A constructor that has parameters is known as parameterized


constructor. If we want to initialize fields of the class with our
own values, then use a parameterized constructor.
// Java Program for Parameterized Constructor
import [Link].*;
class Geek {
String name;
int id;
Geek(String name, int id) {
[Link] = name;
[Link] = id;
}
}
class GFG
{
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
Geek geek1 = new Geek("Avinash", 68);
[Link]("GeekName :" + [Link] + " and GeekId :" + [Link]);
}
}
3. Copy Constructor in Java

Unlike other constructors copy constructor is passed with another object


which copies the data available from the passed object to the newly
created object.
// Java Program for Copy Constructor
import [Link].*;
class Geek {
// data members of the class.
String name;
int id;
// Parameterized Constructor
Geek(String name, int id)
{
[Link] = name;
[Link] = id;
}
// Copy Constructor
Geek(Geek obj2)
{
[Link] = [Link];
[Link] = [Link];
}
}
class GFG {
{
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
[Link]("First Object");
Geek geek1 = new Geek("Avinash", 68);
[Link]("GeekName :" + [Link]
+ " and GeekId :" + [Link]);

[Link]();

// This would invoke the copy constructor.


Geek geek2 = new Geek(geek1);
[Link](
"Copy Constructor used Second Object");
[Link]("GeekName :" + [Link]
+ " and GeekId :" + [Link]);
}
Constructor Overloading:
Constructor overloading is a concept where a class can have multiple constructors with
different parameters.
class Box {
double width, height, depth;
// Constructor with three parameters
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// Default constructor
Box() {
width = height = depth = 0;
}
// Constructor with one parameter
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}
}
public class Test {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
[Link]("Volume of mybox1 is " + [Link]());
[Link]("Volume of mybox2 is " + [Link]());
[Link]("Volume of mycube is " + [Link]());
}
}
Java Methods :
• The method in Java or Methods of Java is a collection of statements that
perform some specific tasks.
• Java Methods allows us to reuse the code without retyping the code.
Syntax of Method:
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Advantage of Method:
Code Reusability
Code Optimization
• ;;;;;;;;;;
Example for methods:
import [Link].*;
class Addition {
int sum = 0;
public int addTwoInt(int a, int b)
{
sum = a + b;
return sum;
}
}
class A {
public static void main(String[] args)
{
Addition add = new Addition();
int s = [Link](1, 2);
[Link]("Sum of two integer values :" + s);
}
}
Method Overloading :
• In Java, Method Overloading allows different methods to have the
same name, but different signatures where the signature can differ by
the number of input parameters or type of input parameters, or a
mixture of both.
• Method overloading in Java is also known as
Compile-time Polymorphism, Static
Polymorphism, or Early binding
public class Sum {
public int sum(int x, int y) { return (x + y); }
public int sum(int x, int y, int z)
{
return (x + y + z);
} public double sum(double x, double y)
{
return (x + y);
}
public static void main(String args[])
{
Sum s = new Sum();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
}
}
Command-line argument:
Java command-line argument is an argument i.e. passed at the time of
running the Java program.
In Java, the command line arguments passed from the console can be
received in the Java program and they can be used as input.
The users can pass the arguments during the execution bypassing the
command-line arguments inside the main() method.
Example:
class CommandLineExample{
public static void main(String args[]){
[Link]("Your first argument is: "+args[0]);
}
}
• Output:
compile by > javac [Link]

run by > java CommandLineExample SYB


Output: Your first argument is: SYB
Garbage Collection :
• Garbage collection in Java is the process by which
Java programs perform automatic memory
management.

Examples for garbage collection :


Suppose you go for the internship at, and you were told
to write a program to count the number of employees
working in the company(excluding interns). To make
this program, you have to use the concept of a garbage
collector.
Visibility control :
This is achieved through the use of access modifiers, which determine the accessibility or scope of a class, constructor,
variable, method, or data member. Java provides four types of access modifiers:
private, default, protected, and public:
Private Access Modifier:
The private access modifier restricts the visibility of a member to within the class it is declared in. This means that
private members cannot be accessed from outside the class. For example:
class Data {
private String name;
}
public class Main {
public static void main(String[] args) {
Data d = new Data();
[Link] = "Kapil"; // Error: name has private access in Data
}
}
Default Access Modifier
The default access modifier (no keyword) allows members to be accessible
only within the same package. If no access modifier is specified, it is treated as
default. For example:
package p1;
class Geek {
void display() {
[Link]("Hello World!");
}
}
package p2;
import p1.*;
class GeekNew {
public static void main(String[] args) {
Geek obj = new Geek(); // Error: Geek is not public in p1
[Link]();
}
Protected Access Modifier
The protected access modifier allows members to be accessible within the same
package and by subclasses in different packages. For example:
package p1;
public class A {
protected void display() {
[Link]("GeeksforGeeks");
}
}
package p2;
import p1.*;
class B extends A {
public static void main(String[] args) {
B obj = new B();
[Link](); // Output: GeeksforGeeks
}
}
Public Access Modifier
The public access modifier allows members to be accessible from anywhere in the program. It has the
widest scope among all access modifiers. For example:
package p1;
public class A {
public void display() {
[Link]("GeeksforGeeks");
}
}
package p2;
import p1.*;
class B {
public static void main(String[] args) {
A obj = new A();
[Link](); // Output: GeeksforGeeks
}
}

You might also like