0% found this document useful (0 votes)
27 views34 pages

Kunal Kushwaha Java (AutoRecovered)

The document provides an overview of Java programming concepts, including user input handling with the Scanner class, method parameters, and the distinction between static and non-static variables. It explains Java's pass-by-value mechanism, the use of arrays, and the behavior of ArrayLists, along with examples of function overloading and linear search algorithms. Additionally, it covers topics such as variable scope, shadowing, and the immutability of strings versus the mutability of arrays.

Uploaded by

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

Kunal Kushwaha Java (AutoRecovered)

The document provides an overview of Java programming concepts, including user input handling with the Scanner class, method parameters, and the distinction between static and non-static variables. It explains Java's pass-by-value mechanism, the use of arrays, and the behavior of ArrayLists, along with examples of function overloading and linear search algorithms. Additionally, it covers topics such as variable scope, shadowing, and the immutability of strings versus the mutability of arrays.

Uploaded by

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

1.

Java User Input


- Scanner class in [Link] package
- Create an object of the Scanner class and
use the available methods.

error: non-static method sum() cannot be


referenced from a static context
2. Methods in java
Java is pass by value
2a. Java creates a copy of the variables
being passed in the methods and then does
the manipulations – so the changes inside a
method do not reflect in the main.

Output: 5

2b. In java all primitives or objects of any


class are always references. When we pass
object references to methods – Java creates a
copy of the references and pass it to method
but they still point to the same memory
reference.

2c. Integer class is a wrapper class for the


primitive type int. An object of the Integer
class can hold a single int value.
Output: i: 10 j: 5

Output: i:5 j:10

2d. In java everything is passed by value, For


primitive types like int , float – the actual
value is passed. For objects the reference
(address) is passed by value. Student s1= new
Student(); - here s1 stores a reference to the
Student object. When s1 is passed to modify a
copy of the reference is sent. s1 and s both
now point to the same object. When doing
[Link] = 100 you are not changing the
reference – you are changing the data inside
the object. When you create s = new Student()
inside the modify method – s now points to a
new object different from the one s1 is
pointing to. So the original object s1 remains
unchanged.

Output: Before change: 50 After change:50


Output: Before change: 50 After change:100
2e. Here when change method is called the then
nums receives a copy of the value of the
reference that contains the same object – So
nums and arr both point to the memeory
location where the memory is stored.

Output: [99,3,2,45,6]

2f.
Function scope: Variables in a method can only
be accessed from within the method.
Block Scope: a variable declared in a method
cannot be declared again in a block inside
that method but can be accessed (ex. It’s
value can be changed). However, a variable
declared in a block cannot be used or accessed
outside the block and can be initialised
again.

error: variable a is already defined in method


main(String[])
int a = 15;

Output: The value of a is :15


Output:
the value of c is: 15
the value of c is: 30

Output:
error: cannot find symbol
[Link]("The value
of c is :" + c);
symbol: variable c

Meowmeeowwmeowwwwwmeeowmeowwmoeoowwwmeowwwwoeo
woowmewow
2g. Static vs. Non satic
Output: error: non-static variable x cannot be
referenced from a static context
x = 10;

Output: The value of x is: 10

Static keyword in java is used for memory


management and belongs to the class rather
than a specific instance. It allows members to
be shared among all objects of a class.
Static variables is a.k.a class variable is
shared among all the instances of the class
(i.e common to all the objects)
Static block is executed only once when the
class is first loaded into memory. It is used
to initialise the static variables or perform
configuration tasks before the main method
executes.
Static method belongs to the class and not to
any object. It can be called directly using
the class name. It can only access static data
directly. It cannot access instance variables
or methods directly. Cannot use this or super
keywords.
Static nested class is a class declared inside
another class. It can be accessed without
creating an object of the outer class.
The inner class is accessed using
[Link]()

Non static are individual and unique for an


instance. Static belong to the entire class.
Non static is created sperately for each
object unlike static which is created only
once when the object is loaded.
Static can be accessed using the class name ..
non static accessed using object reference.
Static objects can only access other static
objects. Non static can access both.
Object-specific data and behavior are non
static. Utility methods, shared constants and
shared data are static.

2h. Shadowing
Using two variables of the same name within a
scope that overlaps – the variable with the
higher level scope will be hidden.
The variable at high level scope is shadowed
by the low level variable.
Shadowing begins whenever the local variable
is declared.
Variable shadowing occurs when a variable
declared in an inner scope (such as a method
or block) has the same name as a variable in
the outer scope (such as a class field). In
this case, the inner variable shadows or
overrides access to the outer variable.

Output:
10 40 10
Output: error: variable x might not have been
initialized
[Link](x);
2i:VarArgs: Syntax is telling that the method
fun can be called via 0 or more arguments – a
variable number of arguments.

Output: [2, 3, 4, 5, 6, 7]

Output: [Isha, Vishakha, Pramod]


The arguments given to fun are stored as an
int array and String array in the first and
second case repectively. To print this array
we use an inbuilt Array method
[Link]()available in the
[Link] library.
Without this if we directly try to print an
array … the output displayed will be of the
form:
[class name]@[memory hash]

Ex.

Output: [[Link];@372f7a8d

What if you want to have a mix of arguments?

Output:
2 + 3 = 5
[Isha, Pramod]

2j. Function Overloading


Two functions of the same name can exist in
the parameters are of different types or have
different number of arguments of the same
type. At compile time it decides which
function to use.

[Link] Prime or not

2l. Armstrong number


Sum of cubes of digits = same number
Ex. 153, 370, 371

3. Arrays
3a.
datatype[] variable_name = new datatype[size];
int[] rollNo = new int[100];
int[] rollNo = {23,35,12,56,70};
You cannot mix and match data types in an
array.
Reference variable rollNo points to the
object.
Int rollNo; /* This is declaration of array
and is the point where rollNo is defined in
the stack. This happens at compile time.*/
rollNo = new int[5];/* this is the declaration
and this is where the object is created in the
heap memory. The memory allocation happens at
run time whIch is why it is called dynamic
memory allocation. */
/*In C/C++ array elements are stored in
continuous memory location. In Java it depends
on the JVM whether they are in continuous
objects or not because array elements are
stored in the heap memory and heap objects are
generally not continuous. Heap is the runtime
data area in which dynamic memory allocation
takes place. ARRAY OBJECTS IN JAVA MAY NOT BE
CONTINUOUS. */
/* New keyword is used to create an object in
java.*/
/*in java int arrays are by default
initialised with zero and string arrays are
u=initialised with null. */
/*null is a literal – you can assign it to any
reference type but you cannot create a null
type. */
String str = null; //works fine
int num = null; // does not work because int
is a primitive data type.
Any reference variable is by default is going
to be null
In java orimitives are stored in the stack
memory but all other objects are stored in the
heap memory.

3b.
int[] arr = new int[5]
Here arr (the reference variable) is stored in
the stack memory but each element of arr is a
separate object that is stored in the heap
memory
Method 1:
for (int i = 0; i< [Link]; i++){
[Link](arr[i] + “ “}
}

Method 2:
[Link] gives length of the array
for (int num : arr){
//here num represents each element in the
array (not the index)
[Link]( num + “ “}
}

Method 3:
[Link]([Link](arr));

arr[0] = 25;
arr[i] = [Link]();

3c. How do arrays behave inside methods??


Strings are immutable and arrays are mutable
in java.

Before : [3, 4, 5, 6]
After : [99, 4, 5, 6]
The above code does not change anything.
Output:
Before : [3, 4, 5, 6]
After : [3, 4, 5, 6]

[Link] a 2d array mentioning number of rows is


mandatory but mentioning number of columns is
not mandatory. 2 ways of displaying output is
used below.

Input:1 2 3 4 5 6 7 8 9
Output:
[1, 2, 3]
[4, 5]
[6, 7, 8, 9]
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
4a. Array List
Used when you don’t know the size of the
array.
ArrayList<Integer> list = new ArrayList<>(3);
- 3 in this is the initial capacity. In the
code 5 elements are added even though the
initial capacity is specified as [Link] is
perfectly fine.
- inside <> is a generic. Generic cannot be a
primitive type. We use the wrapper class
object of the datatype.
- ArrayList<int> list ... would be wrong

Output: [67, 33, 45, 91, 23]


Output:
[67, 33, 45, 91, 23]
true
false
[99, 33, 45, 91, 23]
[99, 33, 91, 23]
Input:
1 2 3 4 5
Output:
[99, 33, 91, 23, 1, 2, 3, 4, 5]
993391
4b. In the stack java stores the reference
variable of the object. How is it that the
size not fixed???
Size is fixed internally. When the arrayList
fills to a particular amount. It will create a
new Arraylist of maybe double the size – copy
the elements from the initial arrayList to the
new arrayList and delete the old one. This is
amortised time complexity – O(1).
How does the arrayList work?

Input:
1 2 3 4 5 6 7 8 9
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In line 5 of the above code we add one
arrayList. Each element of this arrayList is a
null element. From line 8 we initialize the
array such that each element is now an
arrayList. Only then can we add the elements
of the arrayList.

Output:
[1, 3, 23, 9, 18]
[1, 9, 23, 3, 18]
[Link] Search Algorithm
5a. arr = [18, 12, 9, 14, 77, 50]; Find
whether 14 exists in this array or not.
Each element can be accessed via [Link] or b.
for each loop. Linear Search just starts
searching from the first element and checks
every [Link] no value found return -1.
Time complexity:
Best case: O(1) (constant): how many checks
will the program make if the element is at
first position? The answer is that it will
take only one check regarless of the length of
the array which is why time complexity is
constant.
Worst case: O(n) : how many checks does it
take if element is not in the array? The
number of checks required is the size of the
array.

Space complexity: constant because we are not


taking up any extra space (Auxiliary space)
other than that holding the array.
Below code uses Integer.MIN_VALUE
Q. Count the number of numbers that have an
even number of digits in the array.
To check for the number of digits – we can
convert the int into a string and then find
the length.
Note:
[Link]()
.length() for Strings

Common questions

Powered by AI

In Java, the static keyword is used to define class variables and methods that are shared across all instances of a class, rather than belonging to each individual instance. Static fields and methods can be accessed directly using the class name rather than through an instance, which aids in memory management by reducing redundant data storage and computation across instances. Static blocks are executed once when the class is loaded to initialize static variables or perform configuration tasks. This centralized approach to managing class-level data and behavior makes static members particularly useful for constants, utility methods, and shared resources .

Function overloading in Java allows multiple methods with the same name to coexist in a class, differentiated by their parameter types or the number of parameters. This allows functions to be invoked based on the number and type of arguments, providing flexibility and a way to handle different data inputs concisely. By using overloading, developers can design methods that handle a variety of input scenarios while maintaining logical cohesion and readability. This reduces code duplication and supports the concept of polymorphism by allowing one method signature to adapt its behavior based on its parameters .

Arrays in Java are mutable, which means their contents can be altered after initialization. When an array is passed to a method, a copy of the reference to the array is passed, not a copy of the array itself. As such, any alterations to the array elements within the method reflect outside the method since both in-method and external references point to the same array object. This behavior leverages Java's pass-by-value model for reference variables, allowing manipulations without reallocating or duplicating the array, which is efficient but requires careful management to avoid unwanted side effects .

The linear search algorithm in Java involves iterating through an array or list sequentially to find a specific element. Each element is compared against the target until the element is found or the list ends, making linear search simple but inefficient for large datasets. Its best-case time complexity is O(1), occurring when the element is at the first index. The worst-case time complexity is O(n), where 'n' is the size of the array, occurring when the element is not present. Linear search operates in constant space because it doesn't require additional memory allocations beyond storing the array and the loop index .

The Java Scanner class, part of the java.util package, allows for reading user input. To use it, one creates an instance of the Scanner class, often using System.in as a source of input. A common error encountered is referencing a non-static method, such as a method for parsing input, from a static context, like the main method, without an instance of the class that contains the method. This results in a compile-time error because non-static methods require an instance to be invoked .

ArrayLists in Java provide dynamic sizing and are part of the Java Collections Framework, offering greater flexibility compared to traditional arrays, which have a fixed size. ArrayList automatically resizes, providing amortized time complexity of O(1) for insertions. This flexibility comes at the cost of increased memory overhead and slight performance decreases due to the need for resizing operations and additional method calls. While ArrayLists support only objects (requiring autoboxing for primitives), they offer rich APIs for list manipulation, making them suitable for varied and unknown-sized data collections .

In Java, primitives are stored in stack memory, which is fast and allocated when a method is invoked. Objects, including arrays, are stored in heap memory, allowing for dynamic memory allocation at runtime. While primitives provide efficient storage and manipulation due to their fixed size, objects require more memory and management overhead. Arrays, even though mutable, are fixed in size relative to their declaration and retain their reference values in the stack, pointing to their actual data in the heap. This dual-layer memory model supports efficiency while accommodating Java's robust object-oriented features .

Variable shadowing occurs when a variable declared in an inner scope (e.g., method, block) has the same name as a variable in an outer scope (e.g., class field). The inner variable overrides the outer variable within its scope, making the outer variable inaccessible unless referenced with a specific qualifier, like 'this'. While shadowing can lead to cleaner or more organized code in some situations, it can also introduce potential pitfalls by creating confusion over which variable is being accessed, leading to subtle bugs and increased maintenance complexity .

Static methods and variables belong to the class as a whole rather than any specific instance of the class, meaning they are shared among all instances. Static methods can be invoked without creating an instance and cannot directly access non-static members because they do not belong to any particular object. Conversely, non-static methods and variables are unique to each instance and require an object reference for access. This distinction affects class behavior by centralizing class-level data and methods for statics, which is efficient for resources shared across instances, while non-static members carry data and methods specific to a particular object's state .

In Java, when objects are passed to methods, a copy of the reference is passed rather than the actual object. This means that while the object itself is not copied, the reference to it is, allowing both the original and the copied references to point to the same memory location where the object is stored. Consequently, changes made to the object through one reference are reflected when accessed through the other reference. However, if the reference is reassigned to a new object within the method, this does not affect the original reference outside the method, as it still points to the initial object . Thus, Java objects are mutable in this context, enabling modifications to the object's state, but not to the reference itself.

You might also like