0% found this document useful (0 votes)
41 views12 pages

Varargs:-: Class Coaching (

Varargs allow a method to accept a variable number of arguments of the same type. At compile time, varargs are converted to an array. A vararg parameter must be the last parameter in a method signature. Varargs provide convenience over traditional arrays when calling methods.

Uploaded by

Kuldeep Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
41 views12 pages

Varargs:-: Class Coaching (

Varargs allow a method to accept a variable number of arguments of the same type. At compile time, varargs are converted to an array. A vararg parameter must be the last parameter in a method signature. Varargs provide convenience over traditional arrays when calling methods.

Uploaded by

Kuldeep Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 12

Varargs:-

In Java 5.0, it adds convenience of using variable arbitrary parameters, known less formally as varargs.
One particularly nice feature about varargs is that a variable-length argument can be take from zero
to n arguments.
class Coaching {
public static void printStudentName(String... names) {
for (String s: names) {// foreach for loop
System.out.println("Hello " + s + ". ");
}
}
public static void main(String[] args) {
printStudentName("Ashok");
printStudentName("Sanjeev", "Shani");
printStudentName("Arun", "Shivani", "Monu", "Sonu");
}
}
At compile time a vararg is converted to an array. The varargs facility is just implicit syntax for creating
and passing arrays, an array can be passed directly.
class Coaching {
public static void printStudentName(String... names) {
for (String s: names) {
System.out.println("Hello " + s + ". ");
}
}
public static void main(String[] args) {
printStudentName(args);
}
}
Rules for Vararg Methods
 To declare a method using a var-arg parameter, the var-arg parameter's syntax is three times dot(.) after
parameter’s data type like String... name.
 It must be last parameter of method or first if there is only one parameter.
public class Student {

public static void main(String[] arg) {


int k=4;
Student st=new Student();
st.show(k);
}

void show(int... i) {
System.out.println("i=" + i);// i[0] to access first element value.
}
}
Method Overload:-
public class Student {
public static void main(String[] arg) {
int k=4;
Student st=new Student();
st.show(k);
}
void show(long lg) {
System.out.println("lg=" + lg);
}
void show(int... i) {
System.out.println("i=" + i);
}
}
Notice:- Widening always beats varags.

public class Rahul extends Student{

public static void main(String[] arg) {


int k=4;
Rahul st=new Rahul ();
st.test(k); // compile time error. Replace Student st=new Rahul() output
}
@Override
void test(int[] i) {
System.out.println(“Rahul Test");
}
}

class Student{
void test(int... i) {
System.out.println(“student test ");
}
}
Java Operators:-
 Assignment Operators
Assignment operator, "=“ is using to initialize a variable.
 Compound Assignment Operators:-
(+=, -=, *=, and /=) int k=2; k *= 2 + 5; output:-
 Relational Operators:-
(<, <=, >, >=, ==, and !=).
Don't mistake = for == in a boolean expression. The following is legal:
boolean b=false; if(b=true){System.out.println(“true”);} output:-

 instanceof Comparison
The instanceof operator is used for object reference variables only, and you can use it to check whether an object is of a particular type.
public static void main(String[] args) {
String s = new String(“Test");
if (s instanceof String) {
System.out.print("s is a String");
}
}
instanceof Compiler Error
You can't use the instanceof operator to test across two different class hierarchies.
For instance, the following will NOT compile:
class Cat { }
class Dog {
public static void main(String [] args) {
Dog d = new Dog();
System.out.println(d instanceof Cat);
}
}
Compilation fails—there's no way d could ever refer to a Cat or a subtype of Cat.
Note:- null instanceOf any class or interface type will always false.
Student[] s=new Student[1];
if(s instanceof Student) output:- false
if(s instanceof Object) output:- true
int[] intArr=new int[]; if(intArr instanceOf Object) output:- true

A---B-----C instanceOf C will true for C,B,A and Object.

Arithmetic Operators
We're sure you're familiar with the basic arithmetic operators.
■ + addition
■ – subtraction
■ * multiplication
■ / division

The Remainder (%) Operator


The remainder operator divides the left operand by the right operand, and the result is
the remainder, as the following code demonstrates:
class MathTest {
public static void main (String [] args) {
int x = 15;
int y = x % 4;
System.out.println("The result of 15 % 4 is the "
+ "remainder of 15 divided by 4. The remainder is " + y);
}
}
String Concatenation Operator
The plus sign can also be used to concatenate two strings together, as we saw earlier
(and as we'll definitely see again):
String animal = "Grey " + "elephant";
If either operand is a String, the + operator becomes a String concatenation
operator. If both operands are numbers, the + operator is the addition operator.

Increment and Decrement Operators


Java has two operators that will increment or decrement a variable by exactly one.
These operators are composed of either two plus signs (++) or two minus signs (--):
■ ++ increment (prefix and postfix)
■ -- decrement (prefix and postfix)
The operator is placed either before (prefix) or after (postfix) a variable to change
its value. Whether the operator comes before or after the operand can change the
outcome of an expression.
Post fix increment:-
int k=1,i=0;
k+= i++;
System.out.println(k);
System.out.println(i);
k+= ++i;
System.out.println(k);
System.out.println(i);
Note:- The increment and decrement operators can't be used with final varible.
final int x = 5;
int y = x++; Output- Compiler Error
Conditional Operator
The conditional operator is a ternary operator (it has three operands) and is used
to evaluate boolean expressions.
int m=(3>4)?1:2; System.out.println(m);
We can even nest conditional operators into one statement:-
int m=(1>4)?1:(3>2)?3:2; System.out.println(m);
 Logical Operators
(&, |, ^, !, &&, and ||).
Three of them (&, |, and ^) can also be used as "bitwise" operators.
and others are Short-Circuit Logical Operators.
int i=1;
Student st=null;
if(i!=2 | st.equals(2)){
} else {
Systme.out.println(“Bitwise OR”);
} Output:- Runtime Exception:-java.lang.NullPointerException
int i=1;
Student st=null;
if(i!=2 || st.equals(2)){
} else {
Systme.out.println(“Logical OR”);
} Output:- Logical OR.
int i=1;
Student st=null;
if(i==2 & st.equals(2)){
} else {
Systme.out.println(“Bitwise AND”);
} Output:- Runtime Exception:-java.lang.NullPointerException
int i=1;
Student st=null;
if(i==2 && st.equals(2)){
} else {
Systme.out.println(“Logical AND”);
} Output:- Logical AND.
 Logical invert
boolean i=false;
if(!i){
System.out.println("hello");
} output:- hello

^ exclusive-OR (XOR):-
false +false=false
false +true=true
true +true=false
public class Test{
public static void main(String[] arg) {
Integer i = 42;
String s = (i<40)?"life":(i>50)?"universe":"everything";
System.out.println(s);
}
}

if(args.length == 1 | args[1].equals("test")) {
System.out.println("test case");
} else {
System.out.println("production " + args[0]);
}
}
==, .equals(), compareTo(), and compare()

Comparison Primitives Objects

•Compares references, not values. The use of == with


object references is generally limited to the
Equal following:Comparing to see if a reference is null.
a == b, a != b
values •Comparing two enum values. This works because there is
only one object for each enum constant.
•You want to know if two references are to the same object

Compares values for equality. Because this method is defined


in the Object class, from which all other classes are derived,
it's automatically defined for every class. However, it doesn't
perform an intelligent comparison for most classes unless the
class overrides it. It has been defined in a meaningful way for
a.equals(b) N/A most Java core classes. If it's not defined for a (user) class, it
behaves the same as ==.It turns out that
defining equals() isn't trivial; in fact it's moderately hard to
get it right, especially in the case of subclasses. The best
treatment of the issues is in Horstmann's Core Java Vol 1.
[TODO: Add explanation and example]
Comparable interface. Compares values and returns an int
which tells if the values compare less than, equal, or greater
than. If your class objects have a natural order, implement
a.compareTo(b) N/A
the Comparable<T> interface and define this method. All
Java classes that have a natural ordering implement this
(String, Double, BigInteger, ...).

•Comparator interface. Compares values of two objects.


This is implemented as part of the Comparator<T> interface,
and the typical use is to define one or more small utility
classes that implement this, to pass to methods such
as sort() or for use by sorting data structures such as
TreeMap and TreeSet. You might want to create a
Comparator object for the following.
•Multiple comparisons. To provide several different ways
to sort something. For example, you might want to sort a
Person class by name, ID, age, height, ... You would define a
compare(a, b) N/A
Comparator for each of these to pass to the sort()method.
•System class. To provide comparison methods for classes
that you have no control over. For example, you could define
a Comparator for Strings that compared them by length.
•Strategy pattern. To implement a strategy pattern, which
is a situation where you want to represent an algorithm as
an object that you can pass as a parameter, save in a data
structure, etc.
If your class objects have one natural sorting order, you may
not need this.
Thanks

You might also like