Java Concepts: Practice Questions and Examples
Java Concepts: Practice Questions
- Primitive data type variables cannot be used to invoke methods.
- Import statements are not needed if one class in a package uses another in the same package.
- Classes declared as
final
cannot be subclassed. - Methods in an abstract class do not have to be abstract.
- Static/private methods cannot be overridden.
Data Type Conversion
- String to int:
int result = Integer.parseInt(string);
Threads
Create and start a thread that checks if an integer is even (divisible by 2):
new Thread(() -> System.out.println(x % 2 == 0)).start();
Lists
HashSet
allows only one null key.HashMap
can allow one null key and multiple null values. Example:Set s = new HashSet<>();
List strList = new LinkedList<>();
// Prints out contents surrounded with [ ]
Map & HashMap
Map
= interface,HashMap
= implementation of theMap
interface.Map map = new HashMap(); variable.put("Model", "Charger");
Set set = hashmapvariable.entrySet(); System.out.println(set);
for (Map.Entry<KeyType, ValueType> e : m.entrySet())
// Make a new map ‘e’ and iterate through ‘m’
Ternary Operator
result = testCondition ? value1 : value2
// If testCondition is true, assign the value of value1 to result; otherwise, assign value2.
Comparable
When sorting objects:
public class ... implements Comparable
Then use Arrays.sort(objectVariable, new Comparator<>()
int x = 5; x.compareTo(3)
// If the integer is equal to the argument, then 0 is returned; if less, then -1; if greater, then 1.
Equals and HashCode
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof ClassName)) {
return false;
}
ClassName classvar = (ClassName) o;
return fieldint == classvar.fieldint &&
Objects.equals(stringfield, classvar.stringfield) &&
Objects.equals(stringfield2, classvar.stringfield2);
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + varfieldString.hashCode();
result = 31 * result + varfieldInt;
// etc..
return result;
}
Lambdas
Concise function without a name. Functional interface = one abstract method.
Student student = new Student("John");
Exam exam = s -> { return s + ": Pass"; };
System.out.println(result(student, exam));
- Lambdas reduce typing and eliminate the need to look elsewhere for a method’s definition.
InputStream and OutputStream
InputStreamReader istream = new InputStreamReader(System.in); // Reads from keyboard
BufferedReader bufRead = new BufferedReader(istream); // Reads the input stream
try {
System.out.println("Please Enter In Your First Name: ");
String firstName = bufRead.readLine();
} catch (IOException err) {
System.out.println("Error reading line");
}
URL u = new URL("http://" + args[i]);
InputStream is = u.openStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String theLine;
while ((theLine = br.readLine()) != null) {
System.out.println(theLine);
}
Java Socket Programming
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept(); // Establishes connection
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = (String) dis.readUTF();
System.out.println("message= " + str);
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 6666);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Iterator
import java.util.*; Iterator it = strList.iterator(); while (it.hasNext()) { System.out.println(it.next()); } // IT boolean hasNext(), Object next(), void remove()
Remote Method Invocation (RMI)
// public class className implements Serializable {
import java.io.*;
/** Register RMI Server **/
public class RegisterServer {
public RegisterServer() {
try {
Register r = new RegisterImpl();
java.rmi.Naming.rebind("Wonderful", r);
} catch (Exception e) {
System.out.println("Trouble: " + e);
}
}
public static void main(String args[]) {
new RegisterServer();
}
}
/** Register RMI Client **/
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.util.Vector;
import java.io.*;
public class RegisterClient {
public static void main(String[] args) {
Car c = new Car("WV", "Mine", 3.2);
System.out.println(c);
try {
Register r = (Register)
Naming.lookup("Wonderful");
Car cc = r.register(c);
System.out.println(cc);
} catch (Exception e) {
System.out.println(e);
}
}
}
Collections
import java.util.*;
public class FilterStudents {
ArrayList myStudens = new ArrayList<>();
public FilterStudents() {
myStudens.add(new Student("John", 55));
myStudens.add(new Student("Mary", 75));
myStudens.add(new Student("Wei", 80));
}
public void filter(Collection coll) {
for (Iterator it = coll.iterator(); it.hasNext();)
if (!cond(it.next()))
it.remove();
}
Interface Set
import java.util.*;
public class FindDistinct {
public static void main(String args[]) {
Set s = new HashSet<>();
for (int i = 0; i < args.length; i++)
if (!s.add(args[i]))
System.out.println("Duplicate: " + args[i]);
System.out.println(s.size() + " distinct : " + s);
}
}
Interface List
import java.util.*;
public class ListExample {
public static void main(String[] args) {
List strList = new LinkedList<>();
// Adding elements to the end
strList.add("First");
strList.add("Second");
strList.add("Third");
System.out.println(strList);
Iterator it = strList.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
List subList = strList.subList(1, 3);
System.out.println(subList);
System.out.println("All strings in the list: " + strList);
strList.removeIf(s -> s.length() <= 5);
System.out.println("After removing all strings with length <= 5 " + strList);
}
}
Interface Map
import java.util.*;
public class Rate {
public static void main(String[] args) {
Map m = new HashMap<>();
for (String key : args) {
Integer val = m.get(key);
Integer newVal = (val == null) ? 1 : val + 1;
m.put(key, newVal);
}
for (Map.Entry<String, Integer> e : m.entrySet())
System.out.println(e.getKey() + "--> " + e.getValue());
}
}
Interface Comparable
public class Student implements Comparable<Student> {
private String firstName, lastName;
public Student(String firstName, String lastName) {
if (firstName == null || lastName == null)
throw new NullPointerException();
this.firstName = firstName;
this.lastName = lastName;
}
public boolean equals(Object o) {
if (!(o instanceof Student))
return false;
Student n = (Student) o;
return n.firstName.equals(firstName) && n.lastName.equals(lastName);
}
public int hashCode() {
return 31 * firstName.hashCode() + lastName.hashCode();
}
public String toString() {
return firstName + "." + lastName;
}
public int compareTo(Student n) {
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
}
}
import java.util.*;
class AlphabeticalStudents {
public static void main(String args[]) {
Student[] s = {
new Student("John", "Savage"),
new Student("Eric", "Marx"),
new Student("Cuong", "Marx"),
new Student("Oscar", "Savage"),
new Student("Abe", "Vu")
};
List<Student> list = Arrays.asList(s);
Collections.sort(list);
System.out.println(list);
}
}
Algorithms
import java.util.*;
public class CollegeStudent extends Student {
private int GPA;
private long id;
public CollegeStudent(String firstName, String lastName, int gPA, long id) {
super(firstName, lastName);
GPA = gPA;
this.id = id;
}
static final Comparator<CollegeStudent> STUDENT_ORDER = new Comparator<CollegeStudent>() {
public int compare(CollegeStudent s1, CollegeStudent s2) {
int gpaCmp = s1.GPA - s2.GPA;
if (gpaCmp != 0)
return gpaCmp;
return s1.id < s2.id ? -1 : (s1.id == s2.id ? 0 : 1);
}
};
public String toString() {
return super.toString() + "[gpa=" + GPA + " , id=" + id + " ]";
}
public static void main(String[] args) {
CollegeStudent[] cs = {
new CollegeStudent("Abe", "Vu", 345, 123321),
new CollegeStudent("Eric", "Marx", 340, 234432),
new CollegeStudent("Cuong", "Marx", 340, 456654),
new CollegeStudent("Oscar", "Savage", 345, 987789),
new CollegeStudent("John", "Savage", 340, 876678)
};
List<CollegeStudent> list = Arrays.asList(cs);
Collections.sort(list, STUDENT_ORDER);
System.out.println(list);
}
}